Programs & Examples On #Debian

QUESTIONS MUST BE PROGRAMMING RELATED. Use this tag only if your question relates to development on Debian using operating system API's or Debian-specific features, or to creating packages in the deb format.

Adding a rule in iptables in debian to open a new port

(I presume that you've concluded that it's an iptables problem by dropping the firewall completely (iptables -P INPUT ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F) and confirmed that you can connect to the MySQL server from your Windows box?)

Some previous rule in the INPUT table is probably rejecting or dropping the packet. You can get around that by inserting the new rule at the top, although you might want to review your existing rules to see whether that's sensible:

iptables -I INPUT 1 -p tcp --dport 3306 -j ACCEPT

Note that iptables-save won't save the new rule persistently (i.e. across reboots) - you'll need to figure out something else for that. My usual route is to store the iptables-save output in a file (/etc/network/iptables.rules or similar) and then load then with a pre-up statement in /etc/network/interfaces).

Test a weekly cron job

The solution I am using is as follows:

  1. Edit crontab(use command :crontab -e) to run the job as frequently as needed (every 1 minute or 5 minutes)
  2. Modify the shell script which should be executed using cron to prints the output into some file (e.g: echo "Working fine" >>
    output.txt)
  3. Check the output.txt file using the command : tail -f output.txt, which will print the latest additions into this file, and thus you can track the execution of the script

Call Python script from bash with argument

and take a look at the getopt module. It works quite good for me!

No module named _sqlite3

Is the python-pysqlite2 package installed?

sudo apt-get install python-pysqlite2

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

Switching users inside Docker image to a non-root user

You should also be able to do:

apt install sudo

sudo -i -u tomcat

Then you should be the tomcat user. It's not clear which Linux distribution you're using, but this works with Ubuntu 18.04 LTS, for example.

CUDA incompatible with my gcc version

In my case, I had CUDA already installed from the Ubuntu version and cmake would detect that one instead of the newly installed version using the NVidia SDK Manager.

I ran dpkg -l | grep cuda and could see both versions.

What I had to do is uninstall the old CUDA (version 9.1 in my case) and leave the new version alone (version 10.2). I used the purge command like so:

sudo apt-get purge libcudart9.1 nvidia-cuda-dev nvidia-cuda-doc \
                                nvidia-cuda-gdb nvidia-cuda-toolkit

Please verify that the package names match the version you want to remove from your installation.

I had to rerun cmake from a blank BUILD directory to redirect all the #include and libraries to the SDK version (since the old paths were baked in the existing build environment).

How to upgrade glibc from version 2.13 to 2.15 on Debian?

In fact you cannot do it easily right now (at the time I am writing this message). I will try to explain why.

First of all, the glibc is no more, it has been subsumed by the eglibc project. And, the Debian distribution switched to eglibc some time ago (see here and there and even on the glibc source package page). So, you should consider installing the eglibc package through this kind of command:

apt-get install libc6-amd64 libc6-dev libc6-dbg

Replace amd64 by the kind of architecture you want (look at the package list here).

Unfortunately, the eglibc package version is only up to 2.13 in unstable and testing. Only the experimental is providing a 2.17 version of this library. So, if you really want to have it in 2.15 or more, you need to install the package from the experimental version (which is not recommended). Here are the steps to achieve as root:

  1. Add the following line to the file /etc/apt/sources.list:

    deb http://ftp.debian.org/debian experimental main
    
  2. Update your package database:

    apt-get update
    
  3. Install the eglibc package:

    apt-get -t experimental install libc6-amd64 libc6-dev libc6-dbg
    
  4. Pray...

Well, that's all folks.

Version of Apache installed on a Debian machine

dlocate -s apache2 | grep '^Version:'

How to run a script at a certain time on Linux?

The at command exists specifically for this purpose (unlike cron which is intended for scheduling recurring tasks).

at $(cat file) </path/to/script

How do I download a package from apt-get without installing it?

There are a least these apt-get extension packages that can help:

apt-offline - offline apt package manager
apt-zip - Update a non-networked computer using apt and removable media

This is specifically for the case of wanting to download where you have network access but to install on another machine where you do not.

Otherwise, the --download-only option to apt-get is your friend:

 -d, --download-only
     Download only; package files are only retrieved, not unpacked or installed.
     Configuration Item: APT::Get::Download-Only.

E: Unable to locate package npm

Your system can't find npm package because you haven't add nodejs repository to your system..

Try follow this installation step:
Add nodejs PPA repository to our system and python software properties too

sudo apt-get install curl python-software-properties 
// sudo apt-get install curl software-properties-common

curl -sL https://deb.nodesource.com/setup_10.x | sudo bash -
sudo apt-get update

Then install npm

sudo apt-get install nodejs

Check if npm and node was installed and you're ready to use node.js

node -v
npm -v

If someone was failed to install nodejs.. Try remove the npm first, maybe the old installation was broken..

sudo apt-get remove nodejs
sudo apt-get remove npm

Check if npm or node folder still exist, delete it if you found them

which node
which npm

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

github: server certificate verification failed

You can also disable SSL verification, (if the project does not require a high level of security other than login/password) by typing :

git config --global http.sslverify false

enjoy git :)

How can I find a specific file from a Linux terminal?

find /the_path_you_want_to_find -name index.html

How to remove MySQL completely with config and library files?

With the command:

sudo apt-get remove --purge mysql\*

you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).

You can list all installed mysql packages with the command:

sudo dpkg -l | grep -i mysql

For more cleanup of the package cache, you can use the command:

sudo apt-get clean

Also, remember to use the command:

sudo updatedb

Otherwise the "locate" command will display old data.

To install mysql again, use the following command:

sudo apt-get install libmysqlclient-dev mysql-client

This will install the mysql client, libmysql and its headers files.

To install the mysql server, use the command:

sudo apt-get install mysql-server

Install sbt on ubuntu

It seems like you installed a zip version of sbt, which is fine. But I suggest you install the native debian package if you are on Ubuntu. That is how I managed to install it on my Ubuntu 12.04. Check it out here: http://www.scala-sbt.org/release/docs/Installing-sbt-on-Linux.html Or simply directly download it from here.

ps command doesn't work in docker container

Firstly, run the command below:

apt-get update && apt-get install procps

and then run:

ps -ef

How to use the command update-alternatives --config java

There are many other binaries that need to be linked so I think it's much better to try something like sudo update-alternatives --all and choosing the right alternatives for everything else besides java and javac.

How to search contents of multiple pdf files?

First convert all your pdf files to text files:

for file in *.pdf;do pdftotext "$file"; done

Then use grep as normal. This is especially good as it is fast when you have multiple queries and a lot of PDF files.

Forwarding port 80 to 8080 using NGINX

This worked for me:

server {
  listen  80; 
  server_name example.com www.example.com;

  location / { 
    proxy_pass                          http://127.0.0.1:8080/;
    proxy_set_header Host               $host;
    proxy_set_header X-Real-IP          $remote_addr;  
    proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
  }
}

If it does not work for you look at the logs at sudo tail -f /var/log/nginx/error.log

what is the multicast doing on 224.0.0.251?

I deactivated my "Arno's Iptables Firewall" for testing, and then the messages are gone

How to update-alternatives to Python 3 without breaking apt?

Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:

root:~# python -V
Python 3.5.2

root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode


root:~# update-alternatives --remove python /usr/bin/python3.5

root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).

    Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python2.7   2         auto mode
* 1            /usr/bin/python2.7   2         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0


root:~# python -V
Python 2.7.12

root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.

How to get file creation date/time in Bash/Debian?

Creation date/time is normally not stored. So no, you can't.

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

I know this is an old question, but I had the same problem and solved it thanks to this answer.

I use Putty regularly and have never had any problems. I use and have always used public key authentication. Today I could not connect again to my server, without changing any settings.

Then I saw the answer and remembered that I inadvertently ran chmod 777 . in my user's home directory. I connected from somewhere else and simply ran chmod 755 ~. Everything was back to normal instantly, I didn't even have to restart sshd.

I hope I saved some time from someone

How to set the locale inside a Debian/Ubuntu Docker container?

Just add

ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8

into your Dockerfile. (You may need to make sure the locales package is installed.) Nothing else is needed for the basic operation. Meanwhile, outside of Ubuntu, locale-gen doesn’t accept any arguments, that’s why none of the ‘fixes’ using it work e.g. on Debian. Ubuntu have patched locale-gen to accept a list of locales to generate but the patch at the moment has not been accepted in Debian of anywhere else.

Bash script prints "Command Not Found" on empty lines

Problems with running scripts may also be connected to bad formatting of multi-line commands, for example if you have a whitespace character after line-breaking "\". E.g. this:

./run_me.sh \ 
--with-some parameter

(please note the extra space after "\") will cause problems, but when you remove that space, it will run perfectly fine.

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

I had the same problem with Debian 8. I fixed it by restarting the system. It seems that the error can occur if the kernel image was updated and the system was not restarted thereafter.

How to check the version before installing a package using apt-get?

The following might work well enough:

aptitude versions ^hylafax+

See more in aptitude(8)

Fatal error: Call to undefined function curl_init()

There is solution with all necessary details for Windows 7 x64:

http://www.youtube.com/watch?v=7qNTi1sEfE8

It is in French, but you can understand everything! I solved same problem, even don't speak French. :-)

Many answers forget to mention that you need to add new version of php_curl.dll file from this location: http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/

I added new version of php_curl.dll from archive php_curl-5.4.3-VC9-x64.zip to folders: C:\wamp\bin\php\php5.4.3\ext and C:\Windows\System32 and everything was fine!

How to kill zombie process

I tried

kill -9 $(ps -A -ostat,ppid | grep -e '[zZ]'| awk '{ print $2 }')

and it works for me.

Setting Django up to use MySQL

As all said above, you can easily install xampp first from https://www.apachefriends.org/download.html Then follow the instructions as:

  1. Install and run xampp from http://www.unixmen.com/install-xampp-stack-ubuntu-14-04/, then start Apache Web Server and MySQL Database from the GUI.
  2. You can configure your web server as you want but by default web server is at http://localhost:80 and database at port 3306, and PhpMyadmin at http://localhost/phpmyadmin/
  3. From here you can see your databases and access them using very friendly GUI.
  4. Create any database which you want to use on your Django Project.
  5. Edit your settings.py file like:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'DB_NAME',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '',
    }}
    
  6. Install the following packages in the virtualenv (if you're using django on virtualenv, which is more preferred):

    sudo apt-get install libmysqlclient-dev

    pip install MySQL-python

  7. That's it!! you have configured Django with MySQL in a very easy way.

  8. Now run your Django project:

    python manage.py migrate

    python manage.py runserver

Debian 8 (Live-CD) what is the standard login and password?

Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:

It is also possible to change the default username "user" and the default password "live".

I tried the username user and password live and it did work. If you want to run commands as root you can preface each command with sudo

How to build a Debian/Ubuntu package from source?

  • put "debian" directory from original package to your source directory
  • use "dch" to update version of package
  • use "debuild" to build the package

ini_set("memory_limit") in PHP 5.3.3 is not working at all

If you have the suhosin extension enabled, it can prevent scripts from setting the memory limit beyond what it started with or some defined cap.

http://www.hardened-php.net/suhosin/configuration.html#suhosin.memory_limit

Uncompress tar.gz file

gunzip <filename>

then

tar -xvf <tar-file-name>

Bash Shell Script - Check for a flag and grab its value

Try shFlags -- Advanced command-line flag library for Unix shell scripts.

http://code.google.com/p/shflags/

It is very good and very flexible.

FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag.

DEFINE_string: takes any input, and intreprets it as a string.

DEFINE_boolean: typically does not take any argument: say --myflag to set FLAGS_myflag to true, or --nomyflag to set FLAGS_myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=0 or --myflag=false or --myflag=f or --myflag=1 Passing an option has the same affect as passing the option once.

DEFINE_float: takes an input and intreprets it as a floating point number. As shell does not support floats per-se, the input is merely validated as being a valid floating point value.

DEFINE_integer: takes an input and intreprets it as an integer.

SPECIAL FLAGS: There are a few flags that have special meaning: --help (or -?) prints a list of all the flags in a human-readable fashion --flagfile=foo read flags from foo. (not implemented yet) -- as in getopt(), terminates flag-processing

EXAMPLE USAGE:

-- begin hello.sh --
 ! /bin/sh
. ./shflags
DEFINE_string name 'world' "somebody's name" n
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"
echo "Hello, ${FLAGS_name}."
-- end hello.sh --

$ ./hello.sh -n Kate
Hello, Kate.

Note: I took this text from shflags documentation

python-dev installation error: ImportError: No module named apt_pkg

I met this problem when doing sudo apt-get update. My env is debian8, with python2.7 + 3.4(default) + 3.5.

The following code will only re-create a apt_pkg....so file for python 3.5

sudo apt-get install python3-apt --reinstall

The following code solved my problem,

cd /usr/lib/python3/dist-packages
sudo ln -s apt_pkg.cpython-{35m,34m}-x86_64-linux-gnu.so

So, obviously, python3-apt checks the highest python version, instead of the current python version in use.

What is difference between arm64 and armhf?

Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.

Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:

$ uname -a
armv7l

Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.

You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.

You can follow the GitHub issue for 64-bit support here, if you're interested.

Nginx: Permission denied for nginx on Ubuntu

Nginx needs to run by command 'sudo /etc/init.d/nginx start'

Extract Data from PDF and Add to Worksheet

You can open the PDF file and extract its contents using the Adobe library (which I believe you can download from Adobe as part of the SDK, but it comes with certain versions of Acrobat as well)

Make sure to add the Library to your references too (On my machine it is the Adobe Acrobat 10.0 Type Library, but not sure if that is the newest version)

Even with the Adobe library it is not trivial (you'll need to add your own error-trapping etc):

Function getTextFromPDF(ByVal strFilename As String) As String
   Dim objAVDoc As New AcroAVDoc
   Dim objPDDoc As New AcroPDDoc
   Dim objPage As AcroPDPage
   Dim objSelection As AcroPDTextSelect
   Dim objHighlight As AcroHiliteList
   Dim pageNum As Long
   Dim strText As String

   strText = ""
   If (objAvDoc.Open(strFilename, "") Then
      Set objPDDoc = objAVDoc.GetPDDoc
      For pageNum = 0 To objPDDoc.GetNumPages() - 1
         Set objPage = objPDDoc.AcquirePage(pageNum)
         Set objHighlight = New AcroHiliteList
         objHighlight.Add 0, 10000 ' Adjust this up if it's not getting all the text on the page
         Set objSelection = objPage.CreatePageHilite(objHighlight)

         If Not objSelection Is Nothing Then
            For tCount = 0 To objSelection.GetNumText - 1
               strText = strText & objSelection.GetText(tCount)
            Next tCount
         End If
      Next pageNum
      objAVDoc.Close 1
   End If

   getTextFromPDF = strText

End Function

What this does is essentially the same thing you are trying to do - only using Adobe's own library. It's going through the PDF one page at a time, highlighting all of the text on the page, then dropping it (one text element at a time) into a string.

Keep in mind what you get from this could be full of all kinds of non-printing characters (line feeds, newlines, etc) that could even end up in the middle of what look like contiguous blocks of text, so you may need additional code to clean it up before you can use it.

Hope that helps!

Javascript: Extend a Function

Use extendFunction.js

init = extendFunction(init, function(args) {
  doSomethingHereToo();
});

But in your specific case, it's easier to extend the global onload function:

extendFunction('onload', function(args) {
  doSomethingHereToo();
});

I actually really like your question, it's making me think about different use cases.

For javascript events, you really want to add and remove handlers - but for extendFunction, how could you later remove functionality? I could easily add a .revert method to extended functions, so init = init.revert() would return the original function. Obviously this could lead to some pretty bad code, but perhaps it lets you get something done without touching a foreign part of the codebase.

Difference between @Mock and @InjectMocks

In your test class, the tested class should be annotated with @InjectMocks. This tells Mockito which class to inject mocks into:

@InjectMocks
private SomeManager someManager;

From then on, we can specify which specific methods or objects inside the class, in this case, SomeManager, will be substituted with mocks:

@Mock
private SomeDependency someDependency;

In this example, SomeDependency inside the SomeManager class will be mocked.

How do you make a LinearLayout scrollable?

You need to wrap your linear layout with a scroll view

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout 
        android:id="@+id/container" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">


    </LinearLayout>
</ScrollView>

How to pass a single object[] to a params object[]

One option is you can wrap it into another array:

Foo(new object[]{ new object[]{ (object)"1", (object)"2" } });

Kind of ugly, but since each item is an array, you can't just cast it to make the problem go away... such as if it were Foo(params object items), then you could just do:

Foo((object) new object[]{ (object)"1", (object)"2" });

Alternatively, you could try defining another overloaded instance of Foo which takes just a single array:

void Foo(object[] item)
{
    // Somehow don't duplicate Foo(object[]) and
    // Foo(params object[]) without making an infinite
    // recursive call... maybe something like
    // FooImpl(params object[] items) and then this
    // could invoke it via:
    // FooImpl(new object[] { item });
}

What's the best practice using a settings file in Python?

Yaml and Json are the simplest and most commonly used file formats to store settings/config. PyYaml can be used to parse yaml. Json is already part of python from 2.5. Yaml is a superset of Json. Json will solve most uses cases except multi line strings where escaping is required. Yaml takes care of these cases too.

>>> import json
>>> config = {'handler' : 'adminhandler.py', 'timeoutsec' : 5 }
>>> json.dump(config, open('/tmp/config.json', 'w'))
>>> json.load(open('/tmp/config.json'))   
{u'handler': u'adminhandler.py', u'timeoutsec': 5}

What does from __future__ import absolute_import actually do?

The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:

$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/main1.py", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>> 
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 

In particular:

$ python2 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Note that python2 pkg/main2.py has a different behaviour then launching python2 and then importing pkg.main2 (which is equivalent to using the -m switch).

If you ever want to run a submodule of a package always use the -m switch which prevents the interpreter for chaining the sys.path list and correctly handles the semantics of the submodule.

Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.

What is the difference between print and puts?

A big difference is if you are displaying arrays. Especially ones with NIL. For example:

print [nil, 1, 2]

gives

[nil, 1, 2]

but

puts [nil, 1, 2]

gives

1
2

Note, no appearing nil item (just a blank line) and each item on a different line.

How can I revert a single file to a previous version?

Git doesn't think in terms of file versions. A version in git is a snapshot of the entire tree.

Given this, what you really want is a tree that has the latest content of most files, but with the contents of one file the same as it was 5 commits ago. This will take the form of a new commit on top of the old ones, and the latest version of the tree will have what you want.

I don't know if there's a one-liner that will revert a single file to the contents of 5 commits ago, but the lo-fi solution should work: checkout master~5, copy the file somewhere else, checkout master, copy the file back, then commit.

How can I style even and odd elements?

The problem with your CSS lies with the syntax of your pseudo-classes.

The even and odd pseudo-classes should be:

li:nth-child(even) {
    color:green;
}

and

li:nth-child(odd) {
    color:red;
}

Demo: http://jsfiddle.net/q76qS/5/

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" MaxWidth="200"/>
    </Grid.ColumnDefinitions>

    <TextBox Background="Azure" Text="Hello" />
</Grid>

How do I disable form fields using CSS?

You cannot do that I'm afraid, but you can do the following in jQuery, if you don't want to add the attributes to the fields. Just place this inside your <head></head> tag

$(document).ready(function(){ 
  $(".inputClass").focus(function(){
    $(this).blur();
  }); 
});

If you are generating the fields in the DOM (with JS), you should do this instead:

$(document).ready(function(){ 
  $(document).on("focus", ".inputClass", function(){
    $(this).blur();
  }); 
});

Cannot start session without errors in phpMyAdmin

For Xampp, Deleting temp flies from the 'root' folder works for me.

TH

Using "super" in C++

is this use of typedef super common/rare/never seen in the code you work with?

I have never seen this particular pattern in the C++ code I work with, but that doesn't mean it's not out there.

is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)?

It doesn't allow for multiple inheritance (cleanly, anyway).

should "super" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already?

For the above cited reason (multiple inheritance), no. The reason why you see "super" in the other languages you listed is that they only support single inheritance, so there is no confusion as to what "super" is referring to. Granted, in those languages it IS useful but it doesn't really have a place in the C++ data model.

Oh, and FYI: C++/CLI supports this concept in the form of the "__super" keyword. Please note, though, that C++/CLI doesn't support multiple inheritance either.

How do you revert to a specific tag in Git?

Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname to display the commit it points to.

In your case you have at least these two alternatives:

  1. Reset the current branch to specific tag:

    git reset --hard tagname
    
  2. Generate revert commit on top to get you to the state of the tag:

    git revert tag
    

This might introduce some conflicts if you have merge commits though.

VBA Excel - Insert row below with same format including borders and frames

Private Sub cmdInsertRow_Click()

    Dim lRow As Long
    Dim lRsp As Long
    On Error Resume Next

    lRow = Selection.Row()
    lRsp = MsgBox("Insert New row above " & lRow & "?", _
            vbQuestion + vbYesNo)
    If lRsp <> vbYes Then Exit Sub

    Rows(lRow).Select
    Selection.Copy
    Rows(lRow + 1).Select
    Selection.Insert Shift:=xlDown
    Application.CutCopyMode = False

   'Paste formulas and conditional formatting in new row created
    Rows(lRow).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone

End Sub

This is what I use. Tested and working,

Thanks,

"The public type <<classname>> must be defined in its own file" error in Eclipse

You can have only one public class in a file else you will get the error what you are getting now and name of file must be the name of public class

Android changing Floating Action Button color

Vijet Badigannavar's answer is correct but using ColorStateList is usually complicated and he didn't tell us how to do it. Since we often focus on changing View's color in normal and pressed state, I'm going to add more details:

  1. If you want to change FAB's color in normal state, you can just write

    mFab.setBackgroundTintList(ColorStateList.valueOf(your color in int));
    
  2. If you want to change FAB's color in pressed state, thanks for Design Support Library 22.2.1, you can just write

    mFab.setRippleColor(your color in int);
    

    By setting this attribute, when you long-pressed the FAB, a ripple with your color will appear at your touch point and reveal into whole surface of FAB. Please notice that it won't change FAB's color in normal state. Below API 21(Lollipop), there is no ripple effect but FAB's color will still change when you're pressing it.

Finally, if you want to implement more complex effect for states, then you should dig deeply into ColorStateList, here is a SO question discussing it: How do I create ColorStateList programmatically?.

UPDATE: Thanks for @Kaitlyn's comment. To remove stroke of FAB using backgroundTint as its color, you can set app:borderWidth="0dp" in your xml.

Make an Android button change background on click through XML

To change image by using code

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setImageResource(R.drawable.ImageName);
   }
}

Or, using an XML file:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true"
   android:drawable="@drawable/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

In OnClick, just add this code:

ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName));

How to comment/uncomment in HTML code

The following works well in a .php file.

<php? /*your block you want commented out*/ ?>

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

Uncaught TypeError: undefined is not a function example_app.js:7

This error message tells the whole story. On this line, you are trying to execute a function. However, whatever is being executed is not a function! Instead, it's undefined.

So what's on example_app.js line 7? Looks like this:

var tasks = new ExampleApp.Collections.Tasks(data.tasks);

There is only one function being run on that line. We found the problem! ExampleApp.Collections.Tasks is undefined.

So lets look at where that is declared:

var Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

If that's all the code for this collection, then the root cause is right here. You assign the constructor to global variable, called Tasks. But you never add it to the ExampleApp.Collections object, a place you later expect it to be.

Change that to this, and I bet you'd be good.

ExampleApp.Collections.Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

See how important the proper names and line numbers are in figuring this out? Never ever regard errors as binary (it works or it doesn't). Instead read the error, in most cases the error message itself gives you the critical clues you need to trace through to find the real issue.


In Javascript, when you execute a function, it's evaluated like:

expression.that('returns').aFunctionObject(); // js
execute -> expression.that('returns').aFunctionObject // what the JS engine does

That expression can be complex. So when you see undefined is not a function it means that expression did not return a function object. So you have to figure out why what you are trying to execute isn't a function.

And in this case, it was because you didn't put something where you thought you did.

Git error: src refspec master does not match any error: failed to push some refs

One classic root cause for this message is:

  • when the repo has been initialized (git init lis4368/assignments),
  • but no commit has ever been made

Ie, if you don't have added and committed at least once, there won't be a local master branch to push to.

Try first to create a commit:

  • either by adding (git add .) then git commit -m "first commit"
    (assuming you have the right files in place to add to the index)
  • or by create a first empty commit: git commit --allow-empty -m "Initial empty commit"

And then try git push -u origin master again.

See "Why do I need to explicitly push a new branch?" for more.

Proxy Error 502 : The proxy server received an invalid response from an upstream server

Add this into your httpd.conf file

Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore 

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

Run a mySQL query as a cron job?

I personally find it easier use MySQL event scheduler than cron.

Enable it with

SET GLOBAL event_scheduler = ON;

and create an event like this:

CREATE EVENT name_of_event
ON SCHEDULE EVERY 1 DAY
STARTS '2014-01-18 00:00:00'
DO
DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7;

and that's it.

Read more about the syntax here and here is more general information about it.

Installing Python packages from local file system folder to virtualenv with pip

To install only from local you need 2 options:

  • --find-links: where to look for dependencies. There is no need for the file:// prefix mentioned by others.
  • --no-index: do not look in pypi indexes for missing dependencies (dependencies not installed and not in the --find-links path).

So you could run from any folder the following:

pip install --no-index --find-links /srv/pkg /path/to/mypackage-0.1.0.tar.gz

If your mypackage is setup properly, it will list all its dependencies, and if you used pip download to download the cascade of dependencies (ie dependencies of depencies etc), everything will work.

If you want to use the pypi index if it is accessible, but fallback to local wheels if not, you can remove --no-index and add --retries 0. You will see pip pause for a bit while it is try to check pypi for a missing dependency (one not installed) and when it finds it cannot reach it, will fall back to local. There does not seem to be a way to tell pip to "look for local ones first, then the index".

Add params to given URL in Python

I find this more elegant than the two top answers:

from urllib.parse import urlencode, urlparse, parse_qs

def merge_url_query_params(url: str, additional_params: dict) -> str:
    url_components = urlparse(url)
    original_params = parse_qs(url_components.query)
    # Before Python 3.5 you could update original_params with 
    # additional_params, but here all the variables are immutable.
    merged_params = {**original_params, **additional_params}
    updated_query = urlencode(merged_params, doseq=True)
    # _replace() is how you can create a new NamedTuple with a changed field
    return url_components._replace(query=updated_query).geturl()

assert merge_url_query_params(
    'http://example.com/search?q=question',
    {'lang':'en','tag':'python'},
) == 'http://example.com/search?q=question&lang=en&tag=python'

The most important things I dislike in the top answers (they are nevertheless good):

  • Lukasz: having to remember the index at which the query is in the URL components
  • Sapphire64: the very verbose way of creating the updated ParseResult

What's bad about my response is the magically looking dict merge using unpacking, but I prefer that to updating an already existing dictionary because of my prejudice against mutability.

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

Scrollview vertical and horizontal in android

use this way I tried this I fixed it

Put All your XML layout inside

<android.support.v4.widget.NestedScrollView 

I explained this in this link vertical recyclerView and Horizontal recyclerview scrolling together

What is the "right" way to iterate through an array in Ruby?

In Ruby 2.1, each_with_index method is removed. Instead you can use each_index

Example:

a = [ "a", "b", "c" ]
a.each_index {|x| print x, " -- " }

produces:

0 -- 1 -- 2 --

How to reliably open a file in the same directory as a Python script

I'd do it this way:

from os.path import abspath, exists

f_path = abspath("fooabar.txt")

if exists(f_path):
    with open(f_path) as f:
        print f.read()

The above code builds an absolute path to the file using abspath and is equivalent to using normpath(join(os.getcwd(), path)) [that's from the pydocs]. It then checks if that file actually exists and then uses a context manager to open it so you don't have to remember to call close on the file handle. IMHO, doing it this way will save you a lot of pain in the long run.

What are Unwind segues for and how do you use them?

For example if you navigate from viewControllerB to viewControllerA then in your viewControllerA below delegate will call and data will share.

@IBAction func unWindSeague (_ sender : UIStoryboardSegue) {
        if sender.source is ViewControllerB  {
            if let _ = sender.source as? ViewControllerB {
                self.textLabel.text = "Came from B = B->A , B exited"
            }
            
        }

}
  • Unwind Seague Source View Controller ( You Need to connect Exit Button to VC’s exit icon and connect it to unwindseague:

enter image description here

  • Unwind Seague Completed -> TextLabel of viewControllerA is Changed.

enter image description here

How do I get monitor resolution in Python?

It's a little troublesome for retina screen, i use tkinter to get the fake size, use pilllow grab to get real size :

import tkinter
root = tkinter.Tk()
resolution_width = root.winfo_screenwidth()
resolution_height = root.winfo_screenheight()
image = ImageGrab.grab()
real_width, real_height = image.width, image.height
ratio_width = real_width / resolution_width
ratio_height = real_height/ resolution_height

Print page numbers on pages when printing html

   **@page {
            margin-top:21% !important; 
            @top-left{
            content: element(header);

            }

            @bottom-left {
            content: element(footer
 }
 div.header {

            position: running(header);

            }
            div.footer {

            position: running(footer);
            border-bottom: 2px solid black;


            }
           .pagenumber:before {
            content: counter(page);
            }
            .pagecount:before {
            content: counter(pages);
            }      
 <div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
                <span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
            </div >**

Can an AJAX response set a cookie?

For the record, be advised that all of the above is (still) true only if the AJAX call is made on the same domain. If you're looking into setting cookies on another domain using AJAX, you're opening a totally different can of worms. Reading cross-domain cookies does work, however (or at least the server serves them; whether your client's UA allows your code to access them is, again, a different topic; as of 2014 they do).

How do I prevent mails sent through PHP mail() from going to spam?

<?php 
$to1 = '[email protected]';
$subject = 'Tester subject'; 

    // To send HTML mail, the Content-type header must be set

    $headers .= "Reply-To: The Sender <[email protected]>\r\n"; 
    $headers .= "Return-Path: The Sender <[email protected]>\r\n"; 
    $headers .= "From: [email protected]" ."\r\n" .
    $headers .= "Organization: Sender Organization\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
?>

read.csv warning 'EOF within quoted string' prevents complete reading of file

I also ran into this problem, and was able to work around a similar EOF error using:

read.table("....csv", sep=",", ...)

Notice that the separator parameter is defined within the more general read.table().

How do you reset the stored credentials in 'git credential-osxkeychain'?

On Mac, use the command git credential-osxkeychain erase.

OR remove manually from keychain from Applications ? Utilities ? Keychain Access. Then remove the github.com keychain. Then use push; it will ask for the keychain access; then deny.

It will ask for the new username and password, add it then pushes a file for that.

After git push I found this error. Then I use the upper case- issue:

remote: Permission to user1/file.git denied to user2(previously exist user ). fatal: unable to access 'https://github.com/xxxxxxxxxxxx/': The requested URL returned error: 403

Is there a way to make AngularJS load partials in the beginning and not at when needed?

You can pass $state to your controller and then when the page loads and calls the getter in the controller you call $state.go('index') or whatever partial you want to load. Done.

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

How can I use a JavaScript variable as a PHP variable?

<script type="text/javascript">
var jvalue = 'this is javascript value';

<?php $abc = "<script>document.write(jvalue)</script>"?>   
</script>
<?php echo  'php_'.$abc;?>

How do I get to IIS Manager?

To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.

if the IIS Manager doesn't open that means you need to install it.

So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7

Get list of JSON objects with Spring RestTemplate

After multiple tests, this is the best way I found :)

Set<User> test = httpService.get(url).toResponseSet(User[].class);

All you need there

public <T> Set<T> toResponseSet(Class<T[]> setType) {
    HttpEntity<?> body = new HttpEntity<>(objectBody, headers);
    ResponseEntity<T[]> response = template.exchange(url, method, body, setType);
    return Sets.newHashSet(response.getBody());
}

How can I create C header files

Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.

If a header file contains a function, and is included by multiple .c files, each .c file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.

It is technically possible to create static functions in a header file for inclusion in multiple .c files. Though this is generally not done because it breaks from the convention that code is found in .c files and declarations are found in .h files.

See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.

Remove items from one list in another

In my case I had two different lists, with a common identifier, kind of like a foreign key. The second solution cited by "nzrytmn":

var result =  list1.Where(p => !list2.Any(x => x.ID == p.ID && x.property1 == p.property1)).ToList();

Was the one that best fit in my situation. I needed to load a DropDownList without the records that had already been registered.

Thank you !!!

This is my code:

t1 = new T1();
t2 = new T2();

List<T1> list1 = t1.getList();
List<T2> list2 = t2.getList();

ddlT3.DataSource= list2.Where(s => !list1.Any(p => p.Id == s.ID)).ToList();
ddlT3.DataTextField = "AnyThing";
ddlT3.DataValueField = "IdAnyThing";
ddlT3.DataBind();

Launching Google Maps Directions via an intent on Android

if you know point A, point B (and whatever features or tracks in between) you can use a KML file along with your intent.

String kmlWebAddress = "http://www.afischer-online.de/sos/AFTrack/tracks/e1/01.24.Soltau2Wietzendorf.kml";
String uri = String.format(Locale.ENGLISH, "geo:0,0?q=%s",kmlWebAddress);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);

for more info, see this SO answer

NOTE: this example uses a sample file that (as of mar13) is still online. if it has gone offline, find a kml file online and change your url

Border for an Image view in Android?

Following is the code that i used to have black border. Note that i have not used extra xml file for border.

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/red_minus_icon"
    android:background="#000000"
    android:padding="1dp"/>

PivotTable to show values, not sum of values

Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =

In my case the column header is URL

Difference between MEAN.js and MEAN.io

I'm surprised nobody has mentioned the Yeoman generator angular-fullstack. It is the number one Yeoman community generator, with currently 1490 stars on the generator page vs Mean.js' 81 stars (admittedly not a fair comparison given how new MEANJS is). It is appears to be actively maintained and is in version 2.05 as I write this. Unlike MEANJS, it doesn't use Swig for templating. It can be scaffolded with passport built in.

No visible cause for "Unexpected token ILLEGAL"

This also could be happening if you're copying code from another document (like a PDF) into your console and trying to run it.

I was trying to run some example code out of a Javascript book I'm reading and was surprised it didn't run in the console.

Apparently, copying from the PDF introduces some unexpected, illegal, and invisible characters into the code.

Why can I not switch branches?

Try this if you don't want any of the merges listed in git status:

git reset --merge

This resets the index and updates the files in the working tree that are different between <commit> and HEAD, but keeps those which are different between the index and working tree (i.e. which have changes which have not been added).

If a file that is different between <commit> and the index has unstaged changes -- reset is aborted.

More about this - https://www.techpurohit.com/list-some-useful-git-commands & Doc link - https://git-scm.com/docs/git-reset

Filtering JSON array using jQuery grep()

_x000D_
_x000D_
var data = {_x000D_
  "items": [{_x000D_
    "id": 1,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 2,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 3,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 4,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 5,_x000D_
    "category": "cat1"_x000D_
  }]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
_x000D_
_x000D_

The $.grep() method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

Get day of week using NSDate

There are already a lot of answers here but I think there's another, perhaps better, way of doing this using the correct Calendar APIs.

I'd suggest getting the day of the week using the weekdaySymbols property of Calendar (docs) in an extension to Date:

extension Date {

    /// Returns the day of the week as a `String`, e.g. "Monday"
    var dayOfWeek: String {
        let calendar = Calendar.autoupdatingCurrent
        return calendar.weekdaySymbols[calendar.component(.weekday, from: self) - 1]
    }
}

This requires initialising a Date first, which I would do using a custom DateFormatter:

extension DateFormatter {

    /// returns a `DateFormatter` with the format "yyyy-MM-dd".
    static var standardDate: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }
}

This can then be called with:

DateFormatter.standardDate.date(from: "2018-09-18")!.dayOfWeek

Why I prefer this:

  1. dayOfWeek does not have to care about time zones because the user's calendar is used, some of the other solutions here will show the incorrect day because time zones are not considered.
  2. It's very likely that you'll need to use dates in the same format in other places so why not create a reusable DateFormatter and use that instead?
  3. weekdaySymbols is localised for you.
  4. weekDaySymbols can be replaced with other options such as shortWeekdaySymbols for "Mon", "Tues" etc.

Please note: This example DateFormatter also doesn't consider time zones or locales, you'll need to set them for what you need. If the dates are always precise, consider setting the time zone TimeZone(secondsFromGMT: 0).

How and where to use ::ng-deep?

Just an update:

You should use ::ng-deep instead of /deep/ which seems to be deprecated.

Per documentation:

The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

You can find it here

How to show grep result with complete path or file name

It is similar to BVB Media's answer.

grep -rnw 'blablabla' `pwd`

It works fine on my ubuntu bash.

Html table with button on each row

Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

<script type="text/javascript">

function handleClick(evt) {
  var node = evt.target || evt.srcElement;
  if (node.name == 'edit') {
    node.value = "Modify";
  }
}

</script>

<table id="table1" border="1" onclick="handleClick(event);">
    <thead>
      <tr>
          <th>Select
    </thead>
    <tbody>
       <tr> 
           <td>
               <form name="f1" action="#" >
                <input id="edit1" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f2" action="#" >
                <input id="edit2" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f3" action="#" >
                <input id="edit3" type="submit" name="edit" value="Edit">
               </form>

   </tbody>
</table>

Node.js Error: Cannot find module express

I had this error in vscode, although the modules where installed. I am using typescript and express. In the server.ts files all the imports had red squiggly underlines. It turns out I had a faulty tsconfig.json file.

{
    "compileOnSave": false,
    "compilerOptions": {
        "module": "commonjs", // Previously this value was `es6`
        "target": "es6",
        "allowSyntheticDefaultImports": true,
        "baseUrl": "public",
        "sourceMap": true,
        "outDir": "dist",
        "jsx": "react",
        "strict": true,
        "preserveConstEnums": true,
        "removeComments": true,
        "noImplicitAny": true,
        "allowJs": true
    },
    "exclude": [
        "node_modules",
        "build"
    ]
}

Is there a C# String.Format() equivalent in JavaScript?

Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

usage:

"{greeting} {who}!".format({greeting: "Hello", who: "world"})

_x000D_
_x000D_
String.prototype.format = function(placeholders) {_x000D_
    var s = this;_x000D_
    for(var propertyName in placeholders) {_x000D_
        var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
        s = s.replace(re, placeholders[propertyName]);_x000D_
    }    _x000D_
    return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

Open youtube video in Fancybox jquery

THIS IS BROKEN, SEE EDIT

<script type="text/javascript">
$("a.more").fancybox({
                    'titleShow'     : false,
                    'transitionIn'  : 'elastic',
                    'transitionOut' : 'elastic',
            'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'      : 'swf',
            'swf'       : {'wmode':'transparent','allowfullscreen':'true'}
        });
</script>

This way if the user javascript is enabled it opens a fancybox with the youtube embed video, if javascript is disabled it opens the video's youtube page. If you want you can add

target="_blank"

to each of your links, it won't validate on most doctypes, but it will open the link in a new window if fancybox doesn't pick it up.

EDIT

this, above, isn't referenced correctly, so the code won't find href under this. You have to call it like this:

$("a.more").click(function() {
    $.fancybox({
            'padding'       : 0,
            'autoScale'     : false,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'title'         : this.title,
            'width'     : 680,
            'height'        : 495,
            'href'          : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'          : 'swf',
            'swf'           : {
                 'wmode'        : 'transparent',
                'allowfullscreen'   : 'true'
            }
        });

    return false;
});

as covered at http://fancybox.net/blog #4, replicated above

Delimiter must not be alphanumeric or backslash and preg_match

The pattern must have delimiters. Delimiters can be a forward slash (/) or any non alphanumeric characters(#,$,*,...). Examples

$pattern = "/My name is '(.*)' and im fine/"; 
$pattern = "#My name is '(.*)' and im fine#";
$pattern = "@My name is '(.*)' and im fine@";  

C++ correct way to return pointer to array from function

Your code (which looks ok) doesn't return a pointer to an array. It returns a pointer to the first element of an array.

In fact that's usually what you want to do. Most manipulation of arrays are done via pointers to individual elements, not via pointers to the array as a whole.

You can define a pointer to an array, for example this:

double (*p)[42];

defines p as a pointer to a 42-element array of doubles. A big problem with that is that you have to specify the number of elements in the array as part of the type -- and that number has to be a compile-time constant. Most programs that deal with arrays need to deal with arrays of varying sizes; a given array's size won't vary after it's been created, but its initial size isn't necessarily known at compile time, and different array objects can have different sizes.

A pointer to the first element of an array lets you use either pointer arithmetic or the indexing operator [] to traverse the elements of the array. But the pointer doesn't tell you how many elements the array has; you generally have to keep track of that yourself.

If a function needs to create an array and return a pointer to its first element, you have to manage the storage for that array yourself, in one of several ways. You can have the caller pass in a pointer to (the first element of) an array object, probably along with another argument specifying its size -- which means the caller has to know how big the array needs to be. Or the function can return a pointer to (the first element of) a static array defined inside the function -- which means the size of the array is fixed, and the same array will be clobbered by a second call to the function. Or the function can allocate the array on the heap -- which makes the caller responsible for deallocating it later.

Everything I've written so far is common to C and C++, and in fact it's much more in the style of C than C++. Section 6 of the comp.lang.c FAQ discusses the behavior of arrays and pointers in C.

But if you're writing in C++, you're probably better off using C++ idioms. For example, the C++ standard library provides a number of headers defining container classes such as <vector> and <array>, which will take care of most of this stuff for you. Unless you have a particular reason to use raw arrays and pointers, you're probably better off just using C++ containers instead.

EDIT : I think you edited your question as I was typing this answer. The new code at the end of your question is, as you observer, no good; it returns a pointer to an object that ceases to exist as soon as the function returns. I think I've covered the alternatives.

Detecting the onload event of a window opened with window.open

The core problem seems to be you are opening a window to show a page whose content is already cached in the browser. Therefore no loading happens and therefore no load-event happens.

One possibility could be to use the 'pageshow' -event instead, as described in:

https://support.microsoft.com/en-us/help/3011939/onload-event-does-not-occur-when-clicking-the-back-button-to-a-previou

How to write a full path in a batch file having a folder name with space?

start "" AcroRd32.exe /A "page=207" "C:\Users\abc\Desktop\abc xyz def\abc def xyz 2015.pdf"

You may try this, I did it finally, it works!

Div table-cell vertical align not working

Set the height for the parent element.

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

MYSQL import data from csv using LOAD DATA INFILE

Syntax:

LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL]
INFILE 'file_name' INTO TABLE `tbl_name`
CHARACTER SET [CHARACTER SET charset_name]
FIELDS [{FIELDS | COLUMNS}[TERMINATED BY 'string']] 
[LINES[TERMINATED BY 'string']] 
[IGNORE number {LINES | ROWS}]

See this Example:

LOAD DATA LOCAL INFILE
'E:\\wamp\\tmp\\customer.csv' INTO TABLE `customer`
CHARACTER SET 'utf8'
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

How can I conditionally require form inputs with AngularJS?

For Angular2

<input type='email' 
    [(ngModel)]='contact.email'
    [required]='!contact.phone' >

scikit-learn random state in splitting dataset

when random_state set to an integer, train_test_split will return same results for each execution.

when random_state set to an None, train_test_split will return different results for each execution.

see below example:

from sklearn.model_selection import train_test_split

X_data = range(10)
y_data = range(10)

for i in range(5):
    X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size = 0.3,random_state = 0) # zero or any other integer
    print(y_test)

print("*"*30)

for i in range(5): 
    X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size = 0.3,random_state = None)
    print(y_test)

Output:

[2, 8, 4]

[2, 8, 4]

[2, 8, 4]

[2, 8, 4]

[2, 8, 4]


[4, 7, 6]

[4, 3, 7]

[8, 1, 4]

[9, 5, 8]

[6, 4, 5]

Using If/Else on a data frame

Use ifelse:

frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
...
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

The difference between if and ifelse:

  • if is a control flow statement, taking a single logical value as an argument
  • ifelse is a vectorised function, taking vectors as all its arguments.

The help page for if, accessible via ?"if" will also point you to ?ifelse

Error message "Forbidden You don't have permission to access / on this server"

If you are using MAMP Pro the way to fix this is by checking the Indexes checkbox under the Hosts - Extended tab.

In MAMP Pro v3.0.3 this is what that looks like: enter image description here

How to check if string contains Latin characters only?

There is no jquery needed:

var matchedPosition = str.search(/[a-z]/i);
if(matchedPosition != -1) {
    alert('found');
}

Can I open a dropdownlist using jQuery

As has been stated, you can't programmatically open a <select> using JavaScript.

However, you could write your own <select> managing the entire look and feel yourself. Something like what you see for the autocomplete search terms on Google or Yahoo! or the Search for Location box at The Weather Network.

I found one for jQuery here. I have no idea whether it would meet your needs, but even if it doesn't completely meet your needs, it should be possible to modify it so it would open as the result of some other action or event. This one actually looks more promising.

How to use LocalBroadcastManager?

enter code here if (createSuccses){
                        val userDataChange=Intent(BRODCAST_USER_DATA_CHANGE)
                        LocalBroadcastManager.getInstance(this).sendBroadcast(
                            userDataChange
                        )
                        enableSpinner(false)
                        finish()

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

Please note that for the sake of simplicity I have made reference to only the first code snippet i.e.,

// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
    public void onClick(View v) {
      // do something when the button is clicked
    }
};

protected void onCreate(Bundle savedValues) {
    ...
    // Capture our button from layout
    Button button = (Button)findViewById(R.id.corky);
    // Register the onClick listener with the implementation above
    button.setOnClickListener(mCorkyListener);
    ...
}

setOnClickListener(View.OnClickListener l) is a public method of View class. Button class extends the View class and can therefore call setOnClickListener(View.OnClickListener l) method.

setOnClickListener registers a callback to be invoked when the view (button in your case) is clicked. This answers should answer your first two questions:

1. Where does setOnClickListener fit in the above logic?

Ans. It registers a callback when the button is clicked. (Explained in detail in the next paragraph).

2. Which one actually listens to the button click?

Ans. setOnClickListener method is the one that actually listens to the button click.

When I say it registers a callback to be invoked, what I mean is it will run the View.OnClickListener l that is the input parameter for the method. In your case, it will be mCorkyListener mentioned in button.setOnClickListener(mCorkyListener); which will then execute the method onClick(View v) mentioned within

// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
    public void onClick(View v) {
      // do something when the button is clicked
    }
};

Moving on further, OnClickListener is an Interface definition for a callback to be invoked when a view (button in your case) is clicked. Simply saying, when you click that button, the methods within mCorkyListener (because it is an implementation of OnClickListener) are executed. But, OnClickListener has just one method which is OnClick(View v). Therefore, whatever action that needs to be performed on clicking the button must be coded within this method.

Now that you know what setOnClickListener and OnClickListener mean, I'm sure you'll be able to differentiate between the two yourself. The third term View.OnClickListener is actually OnClickListener itself. The only reason you have View.preceding it is because of the difference in the import statment in the beginning of the program. If you have only import android.view.View; as the import statement you will have to use View.OnClickListener. If you mention either of these import statements: import android.view.View.*; or import android.view.View.OnClickListener; you can skip the View. and simply use OnClickListener.

Print the data in ResultSet along with column names

1) Instead of PreparedStatement use Statement

2) After executing query in ResultSet, extract values with the help of rs.getString() as :

Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
    rs.getString(1); //or rs.getString("column name");
}

Simple parse JSON from URL on Android and display in listview

try as:

 // your get json request to server.. 
 HttpResponse response = httpClient.execute(httpPost);
 HttpEntity entity = response.getEntity();

 if(entity != null){
    JSONObject respObject = new JSONObject(EntityUtils.toString(entity));
    String active = respObject.getString("active");   
    String name = respObject.getString("name");  
    String tab1_text = respObject.getString("tab1_text");  
    //.... 
  }
else{
       //Do something here...
    }

see this example for Getting and parsing json response from server :

http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/

What is the difference between Normalize.css and Reset CSS?

I work on normalize.css.

The main differences are:

  1. Normalize.css preserves useful defaults rather than "unstyling" everything. For example, elements like sup or sub "just work" after including normalize.css (and are actually made more robust) whereas they are visually indistinguishable from normal text after including reset.css. So, normalize.css does not impose a visual starting point (homogeny) upon you. This may not be to everyone's taste. The best thing to do is experiment with both and see which gels with your preferences.

  2. Normalize.css corrects some common bugs that are out of scope for reset.css. It has a wider scope than reset.css, and also provides bug fixes for common problems like: display settings for HTML5 elements, the lack of font inheritance by form elements, correcting font-size rendering for pre, SVG overflow in IE9, and the button styling bug in iOS.

  3. Normalize.css doesn't clutter your dev tools. A common irritation when using reset.css is the large inheritance chain that is displayed in browser CSS debugging tools. This is not such an issue with normalize.css because of the targeted stylings.

  4. Normalize.css is more modular. The project is broken down into relatively independent sections, making it easy for you to potentially remove sections (like the form normalizations) if you know they will never be needed by your website.

  5. Normalize.css has better documentation. The normalize.css code is documented inline as well as more comprehensively in the GitHub Wiki. This means you can find out what each line of code is doing, why it was included, what the differences are between browsers, and more easily run your own tests. The project aims to help educate people on how browsers render elements by default, and make it easier for them to be involved in submitting improvements.

I've written in greater detail about this in an article about normalize.css

How to round the double value to 2 decimal points?

I guess that you need a formatted output.

System.out.printf("%.2f",d);

How do I get next month date from today's date and insert it in my database?

I know - sort of late. But I was working at the same problem. If a client buys a month of service, he/she expects to end it a month later. Here's how I solved it:

    $now = time(); 
    $day = date('j',$now);
    $year = date('o',$now);
    $month = date('n',$now);
    $hour = date('G');
    $minute = date('i');
    $month += $count;
    if ($month > 12)        {
            $month -= 12;
            $year++; 
            }
    $work = strtotime($year . "-" . $month . "-01");
    $avail = date('t',$work);
    if ($day > $avail)
            $day = $avail;
    $stamp = strtotime($year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute);

This will calculate the exact day n*count months from now (where count <= 12). If the service started March 31, 2019 and runs for 11 months, it will end on Feb 29, 2020. If it runs for just one month, the end date is Apr 30, 2019.

pandas how to check dtype for all columns in a dataframe?

The singular form dtype is used to check the data type for a single column. And the plural form dtypes is for data frame which returns data types for all columns. Essentially:

For a single column:

dataframe.column.dtype

For all columns:

dataframe.dtypes

Example:

import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})

df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')

df.dtypes
#A     int64
#B      bool
#C    object
#dtype: object

How to fill Matrix with zeros in OpenCV?

You can choose filling zero data or create zero Mat.

  1. Filling zero data with setTo():

    img.setTo(Scalar::all(0));
    
  2. Create zero data with zeros():

    img = zeros(img.size(), img.type());
    

The img changes address of memory.

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

#!/bin/bash
for i in $(seq 1 2 10)
do
   echo "skip by 2 value $i"
done

Difference between return and exit in Bash functions

The OP's question: What is the difference between the return and exit statement in BASH functions with respect to exit codes?

Firstly, some clarification is required:

  • A (return|exit) statement is not required to terminate execution of a (function|shell). A (function|shell) will terminate when it reaches the end of its code list, even with no (return|exit) statement.

  • A (return|exit) statement is not required to pass a value back from a terminated (function|shell). Every process has a built-in variable $? which always has a numeric value. It is a special variable that cannot be set like "?=1", but it is set only in special ways (see below *).

    The value of $? after the last command to be executed in the (called function | sub shell) is the value that is passed back to the (function caller | parent shell). That is true whether the last command executed is ("return [n]"| "exit [n]") or plain ("return" or something else which happens to be the last command in the called function's code.

In the above bullet list, choose from "(x|y)" either always the first item or always the second item to get statements about functions and return, or shells and exit, respectively.

What is clear is that they both share common usage of the special variable $? to pass values upwards after they terminate.

* Now for the special ways that $? can be set:

  • When a called function terminates and returns to its caller then $? in the caller will be equal to the final value of $? in the terminated function.
  • When a parent shell implicitly or explicitly waits on a single sub shell and is released by termination of that sub shell, then $? in the parent shell will be equal to the final value of $? in the terminated sub shell.
  • Some built-in functions can modify $? depending upon their result. But some don't.
  • Built-in functions "return" and "exit", when followed by a numerical argument both $? with argument, and terminate execution.

It is worth noting that $? can be assigned a value by calling exit in a sub shell, like this:

# (exit 259)
# echo $?
3

Detect backspace and del on "input" event?

keydown with event.key === "Backspace" or "Delete"

More recent and much cleaner: use event.key. No more arbitrary number codes!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Modern style:

input.addEventListener('keydown', ({key}) => {
    if (["Backspace", "Delete"].includes(key)) {
        return false
    }
})

Mozilla Docs

Supported Browsers

Ignore <br> with CSS?

For me looks better like this:

Some text, Some text, Some text

_x000D_
_x000D_
br {_x000D_
  display: inline;_x000D_
  content: '';_x000D_
}_x000D_
_x000D_
br:after {_x000D_
  content: ', ';_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div style="display:block">_x000D_
  <span>Some text</span>_x000D_
  <br>_x000D_
  <span>Some text</span>_x000D_
  <br>_x000D_
  <span>Some text</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Uninstall Eclipse under OSX?

Deleting the eclipse folder is equivalent to uninstalling it. In fact, if you don't want to tamper with the existing installation you can create another instance of eclipse and run from the new location.

Reading Space separated input in python

You can do the following if you already know the number of fields of the input:

client_name = raw_input("Enter you first and last name: ")
first_name, last_name = client_name.split() 

and in case you want to iterate through the fields separated by spaces, you can do the following:

some_input = raw_input() # This input is the value separated by spaces
for field in some_input.split():
    print field # this print can be replaced with any operation you'd like
    #             to perform on the fields.

A more generic use of the "split()" function would be:

    result_list = some_string.split(DELIMITER)

where DELIMETER is replaced with the delimiter you'd like to use as your separator, with single quotes surrounding it.

An example would be:

    result_string = some_string.split('!')    

The code above takes a string and separates the fields using the '!' character as a delimiter.

Is it possible to print a variable's type in standard C++?

Howard Hinnant used magic numbers to extract type name. ??? suggested string prefix and suffix. But prefix/suffix keep changing. With “probe_type” type_name automatically calculates prefix and suffix sizes for “probe_type” to extract type name:

#include <string_view>
using namespace std;

namespace typeName {
 template <typename T>
  constexpr string_view wrapped_type_name () {
#ifdef __clang__
    return __PRETTY_FUNCTION__;
#elif defined(__GNUC__)
    return  __PRETTY_FUNCTION__;
#elif defined(_MSC_VER)
    return  __FUNCSIG__;
#endif
  }

  class probe_type;
  constexpr string_view probe_type_name ("typeName::probe_type");
  constexpr string_view probe_type_name_elaborated ("class typeName::probe_type");
  constexpr string_view probe_type_name_used (wrapped_type_name<probe_type> ().find (probe_type_name_elaborated) != -1 ? probe_type_name_elaborated : probe_type_name);

  constexpr size_t prefix_size () {
    return wrapped_type_name<probe_type> ().find (probe_type_name_used);
  }

  constexpr size_t suffix_size () {
    return wrapped_type_name<probe_type> ().length () - prefix_size () - probe_type_name_used.length ();
  }

  template <typename T>
  string_view type_name () {
    constexpr auto type_name = wrapped_type_name<T> ();

    return type_name.substr (prefix_size (), type_name.length () - prefix_size () - suffix_size ());
  }
}

#include <iostream>

using typeName::type_name;
using typeName::probe_type;

class test;

int main () {
  cout << type_name<class test> () << endl;

  cout << type_name<const int*&> () << endl;
  cout << type_name<unsigned int> () << endl;

  const int ic = 42;
  const int* pic = &ic;
  const int*& rpic = pic;
  cout << type_name<decltype(ic)> () << endl;
  cout << type_name<decltype(pic)> () << endl;
  cout << type_name<decltype(rpic)> () << endl;

  cout << type_name<probe_type> () << endl;
}

Output

gcc 10.2:

test
const int *&
unsigned int
const int
const int *
const int *&
typeName::probe_type

clang 11.0.0:

test
const int *&
unsigned int
const int
const int *
const int *&
typeName::probe_type

VS 2019 version 16.7.6:

class test
const int*&
unsigned int
const int
const int*
const int*&
class typeName::probe_type

Blade if(isset) is not working Laravel

Use ?? instead or {{ $usersType ?? '' }}

Begin, Rescue and Ensure in Ruby?

Yes, ensure ensures that the code is always evaluated. That's why it's called ensure. So, it is equivalent to Java's and C#'s finally.

The general flow of begin/rescue/else/ensure/end looks like this:

begin
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
rescue SomeOtherException => some_other_variable
  # code that deals with some other exception
else
  # code that runs only if *no* exception was raised
ensure
  # ensure that this code always runs, no matter what
  # does not change the final value of the block
end

You can leave out rescue, ensure or else. You can also leave out the variables in which case you won't be able to inspect the exception in your exception handling code. (Well, you can always use the global exception variable to access the last exception that was raised, but that's a little bit hacky.) And you can leave out the exception class, in which case all exceptions that inherit from StandardError will be caught. (Please note that this does not mean that all exceptions are caught, because there are exceptions which are instances of Exception but not StandardError. Mostly very severe exceptions that compromise the integrity of the program such as SystemStackError, NoMemoryError, SecurityError, NotImplementedError, LoadError, SyntaxError, ScriptError, Interrupt, SignalException or SystemExit.)

Some blocks form implicit exception blocks. For example, method definitions are implicitly also exception blocks, so instead of writing

def foo
  begin
    # ...
  rescue
    # ...
  end
end

you write just

def foo
  # ...
rescue
  # ...
end

or

def foo
  # ...
ensure
  # ...
end

The same applies to class definitions and module definitions.

However, in the specific case you are asking about, there is actually a much better idiom. In general, when you work with some resource which you need to clean up at the end, you do that by passing a block to a method which does all the cleanup for you. It's similar to a using block in C#, except that Ruby is actually powerful enough that you don't have to wait for the high priests of Microsoft to come down from the mountain and graciously change their compiler for you. In Ruby, you can just implement it yourself:

# This is what you want to do:
File.open('myFile.txt', 'w') do |file|
  file.puts content
end

# And this is how you might implement it:
def File.open(filename, mode='r', perm=nil, opt=nil)
  yield filehandle = new(filename, mode, perm, opt)
ensure
  filehandle&.close
end

And what do you know: this is already available in the core library as File.open. But it is a general pattern that you can use in your own code as well, for implementing any kind of resource cleanup (à la using in C#) or transactions or whatever else you might think of.

The only case where this doesn't work, if acquiring and releasing the resource are distributed over different parts of the program. But if it is localized, as in your example, then you can easily use these resource blocks.


BTW: in modern C#, using is actually superfluous, because you can implement Ruby-style resource blocks yourself:

class File
{
    static T open<T>(string filename, string mode, Func<File, T> block)
    {
        var handle = new File(filename, mode);
        try
        {
            return block(handle);
        }
        finally
        {
            handle.Dispose();
        }
    }
}

// Usage:

File.open("myFile.txt", "w", (file) =>
{
    file.WriteLine(contents);
});

How to select true/false based on column value?

You can try something like

SELECT  e.EntityId, 
        e.EntityName, 
        CASE 
            WHEN ep.EntityId IS NULL THEN 'False' 
            ELSE 'TRUE' 
        END AS HasProfile 
FROM    Entities e LEFT JOIN 
        EntityProfiles ep ON e.EntityID = ep.EntityID

Or

SELECT e.EntityId, 
        e.EntityName, 
        CASE 
            WHEN e.EntityProfile IS NULL THEN 'False' 
            ELSE 'TRUE' 
        END AS HasProfile 

FROM    Entities e

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

Incase you have multiple versions of Postgres installed on your machine. You can remove all via brew command as:

brew uninstall --force postgresql

How do I pass a datetime value as a URI parameter in asp.net mvc?

i realize it works after adding a slash behind like so

mysite/Controller/Action/21-9-2009 10:20/

Changing the selected option of an HTML Select element

Excellent answers - here's the D3 version for anyone looking:

<select id="sel">
    <option>Cat</option>
    <option>Dog</option>
    <option>Fish</option>
</select>
<script>
    d3.select('#sel').property('value', 'Fish');
</script>

How to print a string in C++

You can't call "printf" with a std::string in parameter. The "%s" is designed for C-style string : char* or char []. In C++ you can do like that :

#include <iostream>
std::cout << YourString << std::endl;

If you absolutely want to use printf, you can use the "c_str()" method that give a char* representation of your string.

printf("%s\n",YourString.c_str())

Create a new txt file using VB.NET

Here is a single line that will create (or overwrite) the file:

File.Create("C:\my files\2010\SomeFileName.txt").Dispose()

Note: calling Dispose() ensures that the reference to the file is closed.

JSON Array iteration in Android/Java

On Arrays, look for:

JSONArray menuitemArray = popupObject.getJSONArray("menuitem"); 

Does bootstrap 4 have a built in horizontal divider?

in Bootstrap 5 you can do something like this:

<div class="py-2 my-1 text-center position-relative mx-2">
            <div class="position-absolute w-100 top-50 start-50 translate-middle" style="z-index: 2">
                <span class="d-inline-block bg-white px-2 text-muted">or</span>
            </div>
            <div class="position-absolute w-100 top-50 start-0 border-muted border-top"></div>
</div>

How to correctly catch change/focusOut event on text input in React.js?

You'd need to be careful as onBlur has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).

There is, however, no way to use onFocusOut in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.

How to update only one field using Entity Framework?

i'm using this:

entity:

public class Thing 
{
    [Key]
    public int Id { get; set; }
    public string Info { get; set; }
    public string OtherStuff { get; set; }
}

dbcontext:

public class MyDataContext : DbContext
{
    public DbSet<Thing > Things { get; set; }
}

accessor code:

MyDataContext ctx = new MyDataContext();

// FIRST create a blank object
Thing thing = ctx.Things.Create();

// SECOND set the ID
thing.Id = id;

// THIRD attach the thing (id is not marked as modified)
db.Things.Attach(thing); 

// FOURTH set the fields you want updated.
thing.OtherStuff = "only want this field updated.";

// FIFTH save that thing
db.SaveChanges();

Clone contents of a GitHub repository (without the folder itself)

If the current directory is empty, you can do that with:

git clone git@github:me/name.git .

(Note the . at the end to specify the current directory.) Of course, this also creates the .git directory in your current folder, not just the source code from your project.

This optional [directory] parameter is documented in the git clone manual page, which points out that cloning into an existing directory is only allowed if that directory is empty.

Change bundle identifier in Xcode when submitting my first app in IOS

Just change Product Name in your project's build settings. This will change the bundle identifier with no need to manually touch xcode configuration files.

How to enable SOAP on CentOS

After hours of searching I think my problem was that command yum install php-soap installs the latest version of soap for the latest php version.

My php version was 7.027, but latest php version is 7.2 so I had to search for the right soap version and finaly found it HERE!

yum install rh-php70-php-soap

Now php -m | grep -i soap works, Output: soap

Do not forget to restart httpd service.

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

Your email variable is empty because of the scope, you should set a use clause such as:

Mail::send('emails.activation', $data, function($message) use ($email, $subject) {
    $message->to($email)->subject($subject);
});

How to Add a Dotted Underline Beneath HTML Text

Without CSS, you basically are stuck with using an image tag. Basically make an image of the text and add the underline. That basically means your page is useless to a screen reader.

With CSS, it is simple.

HTML:

<u class="dotted">I like cheese</u>

CSS:

u.dotted{
  border-bottom: 1px dashed #999;
  text-decoration: none; 
}

Running Example

Example page

<!DOCTYPE HTML>
<html>
<head>
    <style>
        u.dotted{
          border-bottom: 1px dashed #999;
          text-decoration: none; 
        }
    </style>
</head>
<body>
    <u class="dotted">I like cheese</u>
</body>
</html>

What's wrong with overridable method calls in constructors?

In the specific case of Wicket: This is the very reason why I asked the Wicket devs to add support for an explicit two phase component initialization process in the framework's lifecycle of constructing a component i.e.

  1. Construction - via constructor
  2. Initialization - via onInitilize (after construction when virtual methods work!)

There was quite an active debate about whether it was necessary or not (it fully is necessary IMHO) as this link demonstrates http://apache-wicket.1842946.n4.nabble.com/VOTE-WICKET-3218-Component-onInitialize-is-broken-for-Pages-td3341090i20.html)

The good news is that the excellent devs at Wicket did end up introducing two phase initialization (to make the most aweseome Java UI framework even more awesome!) so with Wicket you can do all your post construction initialization in the onInitialize method that is called by the framework automatically if you override it - at this point in the lifecycle of your component its constructor has completed its work so virtual methods work as expected.

javascript find and remove object in array based on key value

var items = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

If you are using jQuery, use jQuery.grep like this:

items = $.grep(items, function(item) { 
  return item.id !== '88';
});
// items => [{ id: "99" }, { id: "108" }]

Using ES5 Array.prototype.filter:

items = items.filter(function(item) { 
  return item.id !== '88'; 
});
// items => [{ id: "99" }, { id: "108" }]

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

We can solve Q2 by summing both the numbers themselves, and the squares of the numbers.

We can then reduce the problem to

k1 + k2 = x
k1^2 + k2^2 = y

Where x and y are how far the sums are below the expected values.

Substituting gives us:

(x-k2)^2 + k2^2 = y

Which we can then solve to determine our missing numbers.

What's the Kotlin equivalent of Java's String[]?

you can use too:

val frases = arrayOf("texto01","texto02 ","anotherText","and ")

for example.

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

How to fix "Headers already sent" error in PHP

Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session().

Example of Unpredictable Error:

 <?php //a white-space before <?php also send for output and arise error
session_start();
session_regenerate_id();

//your page content

One more example:

<?php
includes 'functions.php';
?> <!-- This new line will also arise error -->
<?php
session_start();
session_regenerate_id();

//your page content

Conclusion: Do not output any character before calling session_start() or header() functions not even a white-space or new-line

How to remove folders with a certain name

To delete all directories with the name foo, run:

find -type d -name foo -a -prune -exec rm -rf {} \;

The other answers are missing an important thing: the -prune option. Without -prune, GNU find will delete the directory with the matching name and then try to recurse into it to find more directories that match. The -prune option tells it to not recurse into a directory that matched the conditions.

Bootstrap 3 breakpoints and media queries

Here are the selectors used in Bootstrap 4. There is no "lowest" setting in BS4 because "extra small" is the default. I.e. you would first code the XS size and then have these media overrides afterwards.

@media(min-width:576px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}

Angular 2 : No NgModule metadata found

I had this issue when i cloned from a git repository and I had it resolved when I created a new project and re-inserted the src folder from the old project.

The src folder is the only folder needed when deploying your angular application but you must reconfigure the dev environment, using this solution.

Flutter Countdown Timer

I have created a Generic Timer Widget which can be used to display any kind of timer and its flexible as well.

This Widget takes following properties

  1. secondsRemaining: duration for which timer needs to run in seconds
  2. whenTimeExpires: what action needs to be performed if timer finished
  3. countDownStyle: any kind of style which you want to give to timer
  4. countDownFormatter: the way user wants to display the count down timer e.g hh mm ss string like 01 hours: 20 minutes: 45 seconds

you can provide a default formatter ( formatHHMMSS ) in case you don't want to supply it from every place.

// provide implementation for this - formatHHMMSS(duration.inSeconds); or use below one which I have provided.

import 'package:flutter/material.dart';
class CountDownTimer extends StatefulWidget {
  const CountDownTimer({
    Key key,
    int secondsRemaining,
    this.countDownTimerStyle,
    this.whenTimeExpires,
    this.countDownFormatter,
  })  : secondsRemaining = secondsRemaining,
        super(key: key);

  final int secondsRemaining;
  final Function whenTimeExpires;
  final Function countDownFormatter;
  final TextStyle countDownTimerStyle;

  State createState() => new _CountDownTimerState();
}

class _CountDownTimerState extends State<CountDownTimer>
    with TickerProviderStateMixin {
  AnimationController _controller;
  Duration duration;

  String get timerDisplayString {
    Duration duration = _controller.duration * _controller.value;
    return widget.countDownFormatter != null
        ? widget.countDownFormatter(duration.inSeconds)
        : formatHHMMSS(duration.inSeconds);
      // In case user doesn't provide formatter use the default one
     // for that create a method which will be called formatHHMMSS or whatever you like
  }

  @override
  void initState() {
    super.initState();
    duration = new Duration(seconds: widget.secondsRemaining);
    _controller = new AnimationController(
      vsync: this,
      duration: duration,
    );
    _controller.reverse(from: widget.secondsRemaining.toDouble());
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed || status == AnimationStatus.dismissed) {
        widget.whenTimeExpires();
      }
    });
  }

  @override
  void didUpdateWidget(CountDownTimer oldWidget) {
    if (widget.secondsRemaining != oldWidget.secondsRemaining) {
      setState(() {
        duration = new Duration(seconds: widget.secondsRemaining);
        _controller.dispose();
        _controller = new AnimationController(
          vsync: this,
          duration: duration,
        );
        _controller.reverse(from: widget.secondsRemaining.toDouble());
        _controller.addStatusListener((status) {
          if (status == AnimationStatus.completed) {
            widget.whenTimeExpires();
          } else if (status == AnimationStatus.dismissed) {
            print("Animation Complete");
          }
        });
      });
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Center(
        child: AnimatedBuilder(
            animation: _controller,
            builder: (_, Widget child) {
              return Text(
                timerDisplayString,
                style: widget.countDownTimerStyle,
              );
            }));
  }
}

Usage:

 Container(
       width: 60.0,
       padding: EdgeInsets.only(top: 3.0, right: 4.0),
         child: CountDownTimer(
           secondsRemaining: 30,
           whenTimeExpires: () {
              setState(() {
                hasTimerStopped = true;
              });
            },
            countDownStyle: TextStyle(
                color: Color(0XFFf5a623),
                fontSize: 17.0,
                height: 1.2),
          ),
        )

example for formatHHMMSS:

String formatHHMMSS(int seconds) {
  int hours = (seconds / 3600).truncate();
  seconds = (seconds % 3600).truncate();
  int minutes = (seconds / 60).truncate();

  String hoursStr = (hours).toString().padLeft(2, '0');
  String minutesStr = (minutes).toString().padLeft(2, '0');
  String secondsStr = (seconds % 60).toString().padLeft(2, '0');

  if (hours == 0) {
    return "$minutesStr:$secondsStr";
  }

  return "$hoursStr:$minutesStr:$secondsStr";
}

SQL Server - In clause with a declared variable

I think problem is in

3 + ', ' + 4

change it to

'3' + ', ' + '4'

DECLARE @ExcludedList VARCHAR(MAX)

SET @ExcludedList = '3' + ', ' + '4' + ' ,' + '22'

SELECT * FROM A WHERE Id NOT IN (@ExcludedList)

SET @ExcludedListe such that your query should become

either

SELECT * FROM A WHERE Id NOT IN ('3', '4', '22')

or

SELECT * FROM A WHERE Id NOT IN (3, 4, 22)

How do I prevent Conda from activating the base environment by default?

So in the end I found that if I commented out the Conda initialisation block like so:

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
# __conda_setup="$('/Users/geoff/anaconda2/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
# if [ $? -eq 0 ]; then
    # eval "$__conda_setup"
# else
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
    . "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
else
    export PATH="/Users/geoff/anaconda2/bin:$PATH"
fi
# fi
# unset __conda_setup
# <<< conda initialize <<<

It works exactly how I want. That is, Conda is available to activate an environment if I want, but doesn't activate by default.

How to reduce the space between <p> tags?

As shown above, the problem is the margin preceding the <p> tag in rendering time. Not an elegant solution but effective would be to decrease the top margin.

p { margin-top: -20px; }

jQuery call function after load

Crude, but does what you want, breaks the execution scope:

$(function(){
setTimeout(function(){
//Code to call
},1);
});

Reset all the items in a form

If you have some panels or groupboxes reset fields should be recursive.

public class Utilities
{
    public static void ResetAllControls(Control form)
    {
        foreach (Control control in form.Controls)
        {
            RecursiveResetForm(control);
        }
    }

    private void RecursiveResetForm(Control control)
    {            
        if (control.HasChildren)
        {
            foreach (Control subControl in control.Controls)
            {
                RecursiveResetForm(subControl);
            }
        }
        switch (control.GetType().Name)
        {
            case "TextBox":
                TextBox textBox = (TextBox)control;
                textBox.Text = null;
                break;

            case "ComboBox":
                ComboBox comboBox = (ComboBox)control;
                if (comboBox.Items.Count > 0)
                    comboBox.SelectedIndex = 0;
                break;

            case "CheckBox":
                CheckBox checkBox = (CheckBox)control;
                checkBox.Checked = false;
                break;

            case "ListBox":
                ListBox listBox = (ListBox)control;
                listBox.ClearSelected();
                break;

            case "NumericUpDown":
                NumericUpDown numericUpDown = (NumericUpDown)control;
                numericUpDown.Value = 0;
                break;
        }
    }        
}

How do I tell Spring Boot which main class to use for the executable jar?

For those using Gradle (instead of Maven) :

springBoot {
    mainClass = "com.example.Main"
}

invalid target release: 1.7

When maven is working outside of Eclipse, but giving this error after a JDK change, Go to your Maven Run Configuration, and at the bottom of the Main page, there's a 'Maven Runtime' option. Mine was using the Embedded Maven, so after switching it to use my external maven, it worked.

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

    // Java 8
    System.out.println(LocalDateTime.now().getYear());       // 2015
    System.out.println(LocalDateTime.now().getMonth());      // SEPTEMBER
    System.out.println(LocalDateTime.now().getDayOfMonth()); // 29
    System.out.println(LocalDateTime.now().getHour());       // 7
    System.out.println(LocalDateTime.now().getMinute());     // 36
    System.out.println(LocalDateTime.now().getSecond());     // 51
    System.out.println(LocalDateTime.now().get(ChronoField.MILLI_OF_SECOND)); // 100

    // Calendar
    System.out.println(Calendar.getInstance().get(Calendar.YEAR));         // 2015
    System.out.println(Calendar.getInstance().get(Calendar.MONTH ) + 1);   // 9
    System.out.println(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)); // 29
    System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));  // 7
    System.out.println(Calendar.getInstance().get(Calendar.MINUTE));       // 35
    System.out.println(Calendar.getInstance().get(Calendar.SECOND));       // 32
    System.out.println(Calendar.getInstance().get(Calendar.MILLISECOND));  // 481

    // Joda Time
    System.out.println(new DateTime().getYear());           // 2015
    System.out.println(new DateTime().getMonthOfYear());    // 9
    System.out.println(new DateTime().getDayOfMonth());     // 29
    System.out.println(new DateTime().getHourOfDay());      // 7
    System.out.println(new DateTime().getMinuteOfHour());   // 19
    System.out.println(new DateTime().getSecondOfMinute()); // 16
    System.out.println(new DateTime().getMillisOfSecond()); // 174

    // Formatted
    // 2015-09-28 17:50:25.756
    System.out.println(new Timestamp(System.currentTimeMillis()));

    // 2015-09-28T17:50:25.772
    System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(new Date()));

    // Java 8
    // 2015-09-28T17:50:25.810
    System.out.println(LocalDateTime.now());

    // joda time
    // 2015-09-28 17:50:25.839
    System.out.println(DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS").print(new org.joda.time.DateTime()));

How to change HTML Object element data attribute value in javascript

and in jquery:

$('element').attr('some attribute','some attributes value')

i.e

$('a').attr('href','http://www.stackoverflow.com/')

Getting Database connection in pure JPA setup

Hibernate uses a ConnectionProvider internally to obtain connections. From the hibernate javadoc:

The ConnectionProvider interface is not intended to be exposed to the application. Instead it is used internally by Hibernate to obtain connections.

The more elegant way of solving this would be to create a database connection pool yourself and hand connections to hibernate and your legacy tool from there.

How can I add additional PHP versions to MAMP

If you need to be able to switch between more than two versions at a time, you can use the following to change the version of PHP manually.

MAMP automatically rewrites the following line in your /Applications/MAMP/conf/apache/httpd.conf file when it restarts based on the settings in preferences. You can comment out this line and add the second one to the end of your file:

# Comment this out just under all the modules loaded
# LoadModule php5_module        /Applications/MAMP/bin/php/php5.x.x/modules/libphp5.so

At the bottom of the httpd.conf file, you'll see where additional configurations are loaded from the extra folder. Add this to the bottom of the httpd.conf file

# PHP Version Change
Include /Applications/MAMP/conf/apache/extra/httpd-php.conf

Then create a new file here: /Applications/MAMP/conf/apache/extra/httpd-php.conf

# Uncomment the version of PHP you want to run with MAMP
# LoadModule php5_module /Applications/MAMP/bin/php/php5.2.17/modules/libphp5.so
# LoadModule php5_module /Applications/MAMP/bin/php/php5.3.27/modules/libphp5.so
# LoadModule php5_module /Applications/MAMP/bin/php/php5.4.19/modules/libphp5.so
LoadModule php5_module /Applications/MAMP/bin/php/php5.5.3/modules/libphp5.so

After you have this setup, just uncomment the version of PHP you want to use and restart the servers!

How do I change the android actionbar title and icon

In Android 5.0 material design guidelines discourage the use of icon in actionBar

to enable it add the following code

getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);

credit goes to author of this article

RESTful call in Java

I see many answers, here's what we are using in 2020 WebClient, and BTW RestTemplate is going to get deprecated. (can check this) RestTemplate going to be deprecated

Find a commit on GitHub given the commit hash

View single commit:
https://github.com/<user>/<project>/commit/<hash>

View log:
https://github.com/<user>/<project>/commits/<hash>

View full repo:
https://github.com/<user>/<project>/tree/<hash>

<hash> can be any length as long as it is unique.

How to cast the size_t to double or int C++

Assuming that the program cannot be redesigned to avoid the cast (ref. Keith Thomson's answer):

To cast from size_t to int you need to ensure that the size_t does not exceed the maximum value of the int. This can be done using std::numeric_limits:

int SizeTToInt(size_t data)
{
    if (data > std::numeric_limits<int>::max())
        throw std::exception("Invalid cast.");
    return std::static_cast<int>(data);
}

If you need to cast from size_t to double, and you need to ensure that you don't lose precision, I think you can use a narrow cast (ref. Stroustrup: The C++ Programming Language, Fourth Edition):

template<class Target, class Source>
Target NarrowCast(Source v)
{
    auto r = static_cast<Target>(v);
    if (static_cast<Source>(r) != v)
        throw RuntimeError("Narrow cast failed.");
    return r;
}

I tested using the narrow cast for size_t-to-double conversions by inspecting the limits of the maximum integers floating-point-representable integers (code uses googletest):

EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 2 })), size_t{ IntegerRepresentableBoundary() - 2 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 1 })), size_t{ IntegerRepresentableBoundary() - 1 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() })), size_t{ IntegerRepresentableBoundary() });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 1 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 2 })), size_t{ IntegerRepresentableBoundary() + 2 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 3 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 4 })), size_t{ IntegerRepresentableBoundary() + 4 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 5 }), std::exception);

where

constexpr size_t IntegerRepresentableBoundary()
{
    static_assert(std::numeric_limits<double>::radix == 2, "Method only valid for binary floating point format.");
    return size_t{2} << (std::numeric_limits<double>::digits - 1);
}

That is, if N is the number of digits in the mantissa, for doubles smaller than or equal to 2^N, integers can be exactly represented. For doubles between 2^N and 2^(N+1), every other integer can be exactly represented. For doubles between 2^(N+1) and 2^(N+2) every fourth integer can be exactly represented, and so on.

How to send string from one activity to another?

You can send data from one actvity to another with an Intent

Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);

You then can retrieve this information in the second activity by getting the intent and extracting the string extra. Do this in your onCreate() method.

Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);

Then all you have to do is call setText on your TextView and use that string.

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Is canny your own function? Do you use Canny from OpenCV inside it? If yes check if you feed suitable argument for Canny - first Canny argument should meet following criteria:

  • type: <type 'numpy.ndarray'>
  • dtype: dtype('uint8')
  • being single channel or simplyfing: grayscale, that is 2D array, i.e. its shape should be 2-tuple of ints (tuple containing exactly 2 integers)

You can check it by printing respectively

type(variable_name)
variable_name.dtype
variable_name.shape

Replace variable_name with name of variable you feed as first argument to Canny.

How to update primary key

First, we choose stable (not static) data columns to form a Primary Key, precisely because updating Keys in a Relational database (in which the references are by Key) is something we wish to avoid.

  1. For this issue, it doesn't matter if the Key is a Relational Key ("made up from the data"), and thus has Relational Integrity, Power, and Speed, or if the "key" is a Record ID, with none of that Relational Integrity, Power, and Speed. The effect is the same.

  2. I state this because there are many posts by the clueless ones, who suggest that this is the exact reason that Record IDs are somehow better than Relational Keys.

  3. The point is, the Key or Record ID is migrated to wherever a reference is required.

Second, if you have to change the value of the Key or Record ID, well, you have to change it. Here is the OLTP Standard-compliant method. Note that the high-end vendors do not allow "cascade update".

  • Write a proc. Foo_UpdateCascade_tr @ID, where Foo is the table name

  • Begin a Transaction

  • First INSERT-SELECT a new row in the parent table, from the old row, with the new Key or RID value

  • Second, for all child tables, working top to bottom, INSERT-SELECT the new rows, from the old rows, with the new Key or RID value

  • Third, DELETE the rows in the child tables that have the old Key or RID value, working bottom to top

  • Last, DELETE the row in the parent table that has the old Key or RID value

  • Commit the Transaction

Re the Other Answers

The other answers are incorrect.

  • Disabling constraints and then enabling them, after UPDATing the required rows (parent plus all children) is not something that a person would do in an online production environment, if they wish to remain employed. That advice is good for single-user databases.

  • The need to change the value of a Key or RID is not indicative of a design flaw. It is an ordinary need. That is mitigated by choosing stable (not static) Keys. It can be mitigated, but it cannot be eliminated.

  • A surrogate substituting a natural Key, will not make any difference. In the example you have given, the "key" is a surrogate. And it needs to be updated.

    • Please, just surrogate, there is no such thing as a "surrogate key", because each word contradicts the other. Either it is a Key (made up from the data) xor it isn't. A surrogate is not made up from the data, it is explicitly non-data. It has none of the properties of a Key.
  • There is nothing "tricky" about cascading all the required changes. Refer to the steps given above.

  • There is nothing that can be prevented re the universe changing. It changes. Deal with it. And since the database is a collection of facts about the universe, when the universe changes, the database will have to change. That is life in the big city, it is not for new players.

  • People getting married and hedgehogs getting buried are not a problem (despite such examples being used to suggest that it is a problem). Because we do not use Names as Keys. We use small, stable Identifiers, such as are used to Identify the data in the universe.

    • Names, descriptions, etc, exist once, in one row. Keys exist wherever they have been migrated. And if the "key" is a RID, then the RID too, exists wherever it has been migrated.
  • Don't update the PK! is the second-most hilarious thing I have read in a while. Add a new column is the most.

How do I get the current time only in JavaScript

You can simply use this methods.

_x000D_
_x000D_
console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit", hour12: false }));
console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit" }));
_x000D_
_x000D_
_x000D_

How to listen for 'props' changes

I work with a computed property like:

    items:{
        get(){
            return this.resources;
        },
        set(v){
            this.$emit("update:resources", v)
        }
    },

Resources is in this case a property:

props: [ 'resources' ]

How to check whether mod_rewrite is enable on server?

  1. To check if mod_rewrite module is enabled, create a new php file in your root folder of your WAMP server. Enter the following

    phpinfo();

  2. Access your created file from your browser.

  3. CtrlF to open a search. Search for 'mod_rewrite'. If it is enabled you see it as 'Loaded Modules'

  4. If not, open httpd.conf (Apache Config file) and look for the following line.

    #LoadModule rewrite_module modules/mod_rewrite.so

  5. Remove the pound ('#') sign at the start and save the this file.

  6. Restart your apache server.

  7. Access the same php file in your browser.

  8. Search for 'mod_rewrite' again. You should be able to find it now.

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I had this problem and it was because the panel was outside of the [data-role="page"] element.

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

Change to another USB port works for me. I tried reset ADB, but problem still there.

How to remove leading zeros using C#

return numberString.TrimStart('0');

JQuery select2 set default value from an option in list?

Step 1: You need to append one blank option with a blank value in your select tag.

Step 2: Add data-placeholder attribute in select tag with a placeholder value

HTML

<select class="select2" data-placeholder='--Select--'>
  <option value=''>--Select--</option>
  <option value='1'>Option 1</option>
  <option value='2'>Option 2</option>
  <option value='3'>Option 3</option>
</select>

Jquery

$('.select2').select2({
    placeholder: $(this).data('placeholder')
});

OR

$('.select2').select2({
    placeholder: 'Custom placeholder text'
});

How to initialize static variables

Here is a hopefully helpful pointer, in a code example. Note how the initializer function is only called once.

Also, if you invert the calls to StaticClass::initializeStStateArr() and $st = new StaticClass() you'll get the same result.

$ cat static.php
<?php

class StaticClass {

  public static  $stStateArr = NULL;

  public function __construct() {
    if (!isset(self::$stStateArr)) {
      self::initializeStStateArr();
    }
  }

  public static function initializeStStateArr() {
    if (!isset(self::$stStateArr)) {
      self::$stStateArr = array('CA' => 'California', 'CO' => 'Colorado',);
      echo "In " . __FUNCTION__. "\n";
    }
  }

}

print "Starting...\n";
StaticClass::initializeStStateArr();
$st = new StaticClass();

print_r (StaticClass::$stStateArr);

Which yields :

$ php static.php
Starting...
In initializeStStateArr
Array
(
    [CA] => California
    [CO] => Colorado
)

CSS: background image on background color

really interesting problem, haven't seen it yet. this code works fine for me. tested it in chrome and IE9

<html>
<head>
<style>
body{
    background-image: url('img.jpg');
    background-color: #6DB3F2;
}
</style>
</head>
<body>
</body>
</html>

How to use Bootstrap 4 in ASP.NET Core

Use nmp configuration file (add it to your web project) then add the needed packages in the same way we did using bower.json and save. Visual studio will download and install it. You'll find the package the under the nmp node of your project.

Recursively find all files newer than a given time

You can find every file what is created/modified in the last day, use this example:

find /directory -newermt $(date +%Y-%m-%d -d '1 day ago') -type f -print

for finding everything in the last week, use '1 week ago' or '7 day ago' anything you want

Pass a variable to a PHP script running from the command line

Save this code in file myfile.php and run as php myfile.php type=daily

<?php
$a = $argv;
$b = array();
if (count($a) === 1) exit;
foreach ($a as $key => $arg) {
    if ($key > 0) {
        list($x,$y) = explode('=', $arg);
        $b["$x"] = $y;  
    }
}
?>

If you add var_dump($b); before the ?> tag, you will see that the array $b contains type => daily.

How to enable C++17 compiling in Visual Studio?

There's now a drop down (at least since VS 2017.3.5) where you can specifically select C++17. The available options are (under project > Properties > C/C++ > Language > C++ Language Standard)

  • ISO C++14 Standard. msvc command line option: /std:c++14
  • ISO C++17 Standard. msvc command line option: /std:c++17
  • The latest draft standard. msvc command line option: /std:c++latest

(I bet, once C++20 is out and more fully supported by Visual Studio it will be /std:c++20)

Get first day of week in PHP?

Keep it simple :

<?php    
$dateTime = new \DateTime('2020-04-01');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');    
?>

Source : PHP manual

NB: as some user commented the $dateTime value will be modified.

How do I assert equality on two classes without an equals method?

If you're using hamcrest for your asserts (assertThat) and don't want to pull in additional test libs, then you can use SamePropertyValuesAs.samePropertyValuesAs to assert items that don't have an overridden equals method.

The upside is that you don't have to pull in yet another test framework and it'll give a useful error when the assert fails (expected: field=<value> but was field=<something else>) instead of expected: true but was false if you use something like EqualsBuilder.reflectionEquals().

The downside is that it is a shallow compare and there's no option for excluding fields (like there is in EqualsBuilder), so you'll have to work around nested objects (e.g. remove them and compare them independently).

Best Case:

import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs;
...
assertThat(actual, is(samePropertyValuesAs(expected)));

Ugly Case:

import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs;
...
SomeClass expected = buildExpected(); 
SomeClass actual = sut.doSomething();

assertThat(actual.getSubObject(), is(samePropertyValuesAs(expected.getSubObject())));    
expected.setSubObject(null);
actual.setSubObject(null);

assertThat(actual, is(samePropertyValuesAs(expected)));

So, pick your poison. Additional framework (e.g. Unitils), unhelpful error (e.g. EqualsBuilder), or shallow compare (hamcrest).

How does one remove a Docker image?

docker rmi  91c95931e552

Error response from daemon: Conflict, cannot delete 91c95931e552 because the container 76068d66b290 is using it, use -f to force FATA[0000] Error: failed to remove one or more images

Find container ID,

# docker ps -a

# docker rm  daf644660736 

Check if a user has scrolled to the bottom

Here's a fairly simple approach

const didScrollToBottom = elm.scrollTop + elm.clientHeight == elm.scrollHeight

Example

elm.onscroll = function() {
    if(elm.scrollTop + elm.clientHeight == elm.scrollHeight) {
        // User has scrolled to the bottom of the element
    }
}

Where elm is an element retrieved from i.e document.getElementById.

Change text from "Submit" on input tag

The value attribute is used to determine the rendered label of a submit input.

<input type="submit" class="like" value="Like" />

Note that if the control is successful (this one won't be as it has no name) this will also be the submitted value for it.

To have a different submitted value and label you need to use a button element, in which the textNode inside the element determines the label. You can include other elements (including <img> here).

<button type="submit" class="like" name="foo" value="bar">Like</button>

Note that support for <button> is dodgy in older versions of Internet Explorer.

Use basic authentication with jQuery and Ajax

Let me show you and Apache alternative- IIS which is need it before start real JQuery Ajax authentication

If we have /secure/* path for example. We need to create web.config and to prohibited access. Only after before send applayed must be able to access it pages in /secure paths

<?xml version="1.0"?>
<configuration>
  <system.web>
    <!-- Anonymous users are denied access to this folder (and its subfolders) -->
    <authorization>
      <deny users="?" />
    </authorization>
  </system.web>
</configuration>



<security>
   <authentication>
      <anonymousAuthentication enabled="false" />
      <basicAuthentication enabled="true" />
   </authentication>
</security>

React Native: Getting the position of an element

This seems to have changed in the latest version of React Native when using refs to calculate.

Declare refs this way.

  <View
    ref={(image) => {
    this._image = image
  }}>

And find the value this way.

  _measure = () => {
    this._image._component.measure((width, height, px, py, fx, fy) => {
      const location = {
        fx: fx,
        fy: fy,
        px: px,
        py: py,
        width: width,
        height: height
      }
      console.log(location)
    })
  }

How to call a SOAP web service on Android

This is a working example of consuming SOAP web services in android.

**Note ::***DON'T FORGET TO ADD ksoap2.jar in your project and also add the INTERNET permission in AndroidManifest file*

public final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
public final String METHOD_NAME = "FahrenheitToCelsius";
public final String PROPERTY_NAME = "Fahrenheit";
public final String SOAP_ACTION = "http://tempuri.org/FahrenheitToCelsius";
public final String SOAP_ADDRESS = "http://www.w3schools.com/webservices/tempconvert.asmx";


private class TestAsynk extends AsyncTask<String, Void, String> {

    @Override
    protected void onPostExecute(String result) {

        super.onPostExecute(result);
        Toast.makeText(getApplicationContext(),
                String.format("%.2f", Float.parseFloat(result)),
                Toast.LENGTH_SHORT).show();
    }

    @Override
    protected String doInBackground(String... params) {
        SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
                METHOD_NAME);
        request.addProperty(PROPERTY_NAME, params[0]);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;

        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(
                SOAP_ADDRESS);
        Object response = null;
        try {

            androidHttpTransport.call(SOAP_ACTION, envelope);
            response = envelope.getResponse();
            Log.e("Object response", response.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.toString();
    }
}

CSS strikethrough different color from text?

This CSS3 will make you line through property more easier, and working fine.

span{
    text-decoration: line-through;
    text-decoration-color: red;
}

How do I enable TODO/FIXME/XXX task tags in Eclipse?

All those settings are necessary to choose which tags you are interested in, but in order to display these tags in a list, you also need to select the right Eclipse perspective. I finally discovered that the "Markers" tab containing the "Task" list is only available under the "Java EE" perspective... Hope this helps! :-)

How to check not in array element

I prefer this

if(in_array($id,$user_access_arr) == false)

respective

if (in_array(search_value, array) == false) 
// value is not in array 

Can't create project on Netbeans 8.2

@ubuntu 18.04

sudo apt install openjdk-8-jdk
then
sudo update-alternatives --config java


  Selection    Path                                            Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      auto mode
  1            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      manual mode
* 2            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      manual mode

Press <enter> to keep the current choice[*], or type selection number: 

choose java 8 then restart netbeans
Done

Laravel 5 Carbon format datetime

Try that:

$createdAt = Carbon::parse(date_format($item['created_at'],'d/m/Y H:i:s');
$createdAt= $createdAt->format('M d Y');

c - warning: implicit declaration of function ‘printf’

You need to include the appropriate header

#include <stdio.h>

If you're not sure which header a standard function is defined in, the function's man page will state this.

Templated check for the existence of a class member function?

template<class T>
auto optionalToString(T* obj)
->decltype( obj->toString(), std::string() )
{
     return obj->toString();
}

template<class T>
auto optionalToString(T* obj)
->decltype( std::string() )
{
     throw "Error!";
}

How to make a select with array contains value clause in psql

SELECT * FROM table WHERE arr && '{s}'::text[];

Compare two arrays for containment.

REST vs JSON-RPC?

REST is tightly coupled with HTTP, so if you only expose your API over HTTP then REST is more appropriate for most (but not all) situations. However, if you need to expose your API over other transports like messaging or web sockets then REST is just not applicable.

Google Maps API OVER QUERY LIMIT per second limit


This approach is not correct beacuse of Google Server Overload. For more informations see https://gis.stackexchange.com/questions/15052/how-to-avoid-google-map-geocode-limit#answer-15365


By the way, if you wish to proceed anyway, here you can find a code that let you load multiple markers ajax sourced on google maps avoiding OVER_QUERY_LIMIT error.

I've tested on my onw server and it works!:

var lost_addresses = [];
    geocode_count  = 0;
    resNumber = 0;
    map = new GMaps({
       div: '#gmap_marker',
       lat: 43.921493,
       lng: 12.337646,
    });

function loadMarkerTimeout(timeout) {
    setTimeout(loadMarker, timeout)
}

function loadMarker() { 
    map.setZoom(6);         
    $.ajax({
            url: [Insert here your URL] ,
            type:'POST',
            data: {
                "action":   "loadMarker"
            },
            success:function(result){

                /***************************
                 * Assuming your ajax call
                 * return something like: 
                 *   array(
                 *      'status' => 'success',
                 *      'results'=> $resultsArray
                 *   );
                 **************************/

                var res=JSON.parse(result);
                if(res.status == 'success') {
                    resNumber = res.results.length;
                    //Call the geoCoder function
                    getGeoCodeFor(map, res.results);
                }
            }//success
    });//ajax
};//loadMarker()

$().ready(function(e) {
  loadMarker();
});

//Geocoder function
function getGeoCodeFor(maps, addresses) {
        $.each(addresses, function(i,e){                
                GMaps.geocode({
                    address: e.address,
                    callback: function(results, status) {
                            geocode_count++;        

                            if (status == 'OK') {       

                                //if the element is alreay in the array, remove it
                                lost_addresses = jQuery.grep(lost_addresses, function(value) {
                                    return value != e;
                                });


                                latlng = results[0].geometry.location;
                                map.addMarker({
                                        lat: latlng.lat(),
                                        lng: latlng.lng(),
                                        title: 'MyNewMarker',
                                    });//addMarker
                            } else if (status == 'ZERO_RESULTS') {
                                //alert('Sorry, no results found');
                            } else if(status == 'OVER_QUERY_LIMIT') {

                                //if the element is not in the losts_addresses array, add it! 
                                if( jQuery.inArray(e,lost_addresses) == -1) {
                                    lost_addresses.push(e);
                                }

                            } 

                            if(geocode_count == addresses.length) {
                                //set counter == 0 so it wont's stop next round
                                geocode_count = 0;

                                setTimeout(function() {
                                    getGeoCodeFor(maps, lost_addresses);
                                }, 2500);
                            }
                    }//callback
                });//GeoCode
        });//each
};//getGeoCodeFor()

Example:

_x000D_
_x000D_
map = new GMaps({_x000D_
  div: '#gmap_marker',_x000D_
  lat: 43.921493,_x000D_
  lng: 12.337646,_x000D_
});_x000D_
_x000D_
var jsonData = {  _x000D_
   "status":"success",_x000D_
   "results":[  _x000D_
  {  _x000D_
     "customerId":1,_x000D_
     "address":"Via Italia 43, Milano (MI)",_x000D_
     "customerName":"MyAwesomeCustomer1"_x000D_
  },_x000D_
  {  _x000D_
     "customerId":2,_x000D_
     "address":"Via Roma 10, Roma (RM)",_x000D_
     "customerName":"MyAwesomeCustomer2"_x000D_
  }_x000D_
   ]_x000D_
};_x000D_
   _x000D_
function loadMarkerTimeout(timeout) {_x000D_
  setTimeout(loadMarker, timeout)_x000D_
}_x000D_
_x000D_
function loadMarker() { _x000D_
  map.setZoom(6);_x000D_
 _x000D_
  $.ajax({_x000D_
    url: '/echo/html/',_x000D_
    type: "POST",_x000D_
    data: jsonData,_x000D_
    cache: false,_x000D_
    success:function(result){_x000D_
_x000D_
      var res=JSON.parse(result);_x000D_
      if(res.status == 'success') {_x000D_
        resNumber = res.results.length;_x000D_
        //Call the geoCoder function_x000D_
        getGeoCodeFor(map, res.results);_x000D_
      }_x000D_
    }//success_x000D_
  });//ajax_x000D_
  _x000D_
};//loadMarker()_x000D_
_x000D_
$().ready(function(e) {_x000D_
  loadMarker();_x000D_
});_x000D_
_x000D_
//Geocoder function_x000D_
function getGeoCodeFor(maps, addresses) {_x000D_
  $.each(addresses, function(i,e){    _x000D_
    GMaps.geocode({_x000D_
      address: e.address,_x000D_
      callback: function(results, status) {_x000D_
        geocode_count++;  _x000D_
        _x000D_
        console.log('Id: '+e.customerId+' | Status: '+status);_x000D_
        _x000D_
        if (status == 'OK') {  _x000D_
_x000D_
          //if the element is alreay in the array, remove it_x000D_
          lost_addresses = jQuery.grep(lost_addresses, function(value) {_x000D_
            return value != e;_x000D_
          });_x000D_
_x000D_
_x000D_
          latlng = results[0].geometry.location;_x000D_
          map.addMarker({_x000D_
            lat: latlng.lat(),_x000D_
            lng: latlng.lng(),_x000D_
            title: e.customerName,_x000D_
          });//addMarker_x000D_
        } else if (status == 'ZERO_RESULTS') {_x000D_
          //alert('Sorry, no results found');_x000D_
        } else if(status == 'OVER_QUERY_LIMIT') {_x000D_
_x000D_
          //if the element is not in the losts_addresses array, add it! _x000D_
          if( jQuery.inArray(e,lost_addresses) == -1) {_x000D_
            lost_addresses.push(e);_x000D_
          }_x000D_
_x000D_
        } _x000D_
_x000D_
        if(geocode_count == addresses.length) {_x000D_
          //set counter == 0 so it wont's stop next round_x000D_
          geocode_count = 0;_x000D_
_x000D_
          setTimeout(function() {_x000D_
            getGeoCodeFor(maps, lost_addresses);_x000D_
          }, 2500);_x000D_
        }_x000D_
      }//callback_x000D_
    });//GeoCode_x000D_
  });//each_x000D_
};//getGeoCodeFor()
_x000D_
#gmap_marker {_x000D_
  min-height:250px;_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
  position: relative; _x000D_
  overflow: hidden;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.24/gmaps.min.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
<div id="gmap_marker"></div> <!-- /#gmap_marker -->
_x000D_
_x000D_
_x000D_

How can I make the computer beep in C#?

In .Net 2.0, you can use Console.Beep().

// Default beep
Console.Beep();

You can also specify the frequency and length of the beep in milliseconds.

// Beep at 5000 Hz for 1 second
Console.Beep(5000, 1000);

For more information refer http://msdn.microsoft.com/en-us/library/8hftfeyw%28v=vs.110%29.aspx

Best way of invoking getter by reflection

I think this should point you towards the right direction:

import java.beans.*

for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
  if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
    System.out.println(pd.getReadMethod().invoke(foo));
}

Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for

// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);

However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:

Object value = PropertyUtils.getProperty(person, "name");

BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

Sum of Numbers C++

You can try:

int sum = startingNumber; 
for (int i=0; i < positiveInteger; i++) {     
    sum += i;
}
cout << sum;

But much easier is to note that the sum 1+2+...+n = n*(n+1) / 2, so you do not need a loop at all, just use the formula n*(n+1)/2.

PHP Accessing Parent Class Variable

class A {
    private $aa;
    protected $bb = 'parent bb';

    function __construct($arg) {
       //do something..
    }

    private function parentmethod($arg2) {
       //do something..
    }
}

class B extends A {
    function __construct($arg) {
        parent::__construct($arg);
    }
    function childfunction() {
        echo parent::$this->bb; //works by M
    }
}

$test = new B($some);
$test->childfunction();`

How to get an absolute file path in Python

>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

Also works if it is already an absolute path:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

How should I store GUID in MySQL tables?

Adding to the answer by ThaBadDawg, use these handy functions (thanks to a wiser collegue of mine) to get from 36 length string back to a byte array of 16.

DELIMITER $$

CREATE FUNCTION `GuidToBinary`(
    $Data VARCHAR(36)
) RETURNS binary(16)
DETERMINISTIC
NO SQL
BEGIN
    DECLARE $Result BINARY(16) DEFAULT NULL;
    IF $Data IS NOT NULL THEN
        SET $Data = REPLACE($Data,'-','');
        SET $Result =
            CONCAT( UNHEX(SUBSTRING($Data,7,2)), UNHEX(SUBSTRING($Data,5,2)),
                    UNHEX(SUBSTRING($Data,3,2)), UNHEX(SUBSTRING($Data,1,2)),
                    UNHEX(SUBSTRING($Data,11,2)),UNHEX(SUBSTRING($Data,9,2)),
                    UNHEX(SUBSTRING($Data,15,2)),UNHEX(SUBSTRING($Data,13,2)),
                    UNHEX(SUBSTRING($Data,17,16)));
    END IF;
    RETURN $Result;
END

$$

CREATE FUNCTION `ToGuid`(
    $Data BINARY(16)
) RETURNS char(36) CHARSET utf8
DETERMINISTIC
NO SQL
BEGIN
    DECLARE $Result CHAR(36) DEFAULT NULL;
    IF $Data IS NOT NULL THEN
        SET $Result =
            CONCAT(
                HEX(SUBSTRING($Data,4,1)), HEX(SUBSTRING($Data,3,1)),
                HEX(SUBSTRING($Data,2,1)), HEX(SUBSTRING($Data,1,1)), '-', 
                HEX(SUBSTRING($Data,6,1)), HEX(SUBSTRING($Data,5,1)), '-',
                HEX(SUBSTRING($Data,8,1)), HEX(SUBSTRING($Data,7,1)), '-',
                HEX(SUBSTRING($Data,9,2)), '-', HEX(SUBSTRING($Data,11,6)));
    END IF;
    RETURN $Result;
END
$$

CHAR(16) is actually a BINARY(16), choose your preferred flavour

To follow the code better, take the example given the digit-ordered GUID below. (Illegal characters are used for illustrative purposes - each place a unique character.) The functions will transform the byte ordering to achieve a bit order for superior index clustering. The reordered guid is shown below the example.

12345678-9ABC-DEFG-HIJK-LMNOPQRSTUVW
78563412-BC9A-FGDE-HIJK-LMNOPQRSTUVW

Dashes removed:

123456789ABCDEFGHIJKLMNOPQRSTUVW
78563412BC9AFGDEHIJKLMNOPQRSTUVW

error: invalid type argument of ‘unary *’ (have ‘int’)

I have reformatted your code.

The error was situated in this line :

printf("%d", (**c));

To fix it, change to :

printf("%d", (*c));

The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.

In addition, the () was optional.

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int *c = NULL;

    a = &b;
    c = &a;

    printf("%d", *c);

    return 0;
} 

EDIT :

The line :

c = &a;

must be replaced by :

c = a;

It means that the value of the pointer 'c' equals the value of the pointer 'a'. So, 'c' and 'a' points to the same address ('b'). The output is :

10

EDIT 2:

If you want to use a double * :

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int **c = NULL;

    a = &b;
    c = &a;

    printf("%d", **c);

    return 0;
} 

Output:

10

Passing multiple variables to another page in url

Use the ampersand & to glue variables together:

$url = "http://localhost/main.php?email=$email_address&event_id=$event_id";
//                               ^ start of vars      ^next var

Cannot catch toolbar home button click event

For anyone looking for a Xamarin implementation (since events are done differently in C#), I simply created this NavClickHandler class as follows:

public class NavClickHandler : Java.Lang.Object, View.IOnClickListener
{
    private Activity mActivity;
    public NavClickHandler(Activity activity)
    {
        this.mActivity = activity;
    }
    public void OnClick(View v)
    {
        DrawerLayout drawer = (DrawerLayout)mActivity.FindViewById(Resource.Id.drawer_layout);
        if (drawer.IsDrawerOpen(GravityCompat.Start))
        {
            drawer.CloseDrawer(GravityCompat.Start);
        }
        else
        {
            drawer.OpenDrawer(GravityCompat.Start);
        }
    }
}

Then, assigned a custom hamburger menu button like this:

        SupportActionBar.SetDisplayHomeAsUpEnabled(true);
        SupportActionBar.SetDefaultDisplayHomeAsUpEnabled(false);
        this.drawerToggle.DrawerIndicatorEnabled = false;
        this.drawerToggle.SetHomeAsUpIndicator(Resource.Drawable.MenuButton);

And finally, assigned the drawer menu toggler a ToolbarNavigationClickListener of the class type I created earlier:

        this.drawerToggle.ToolbarNavigationClickListener = new NavClickHandler(this);

And then you've got a custom menu button, with click events handled.

PHP json_encode encoding numbers as strings

Casting the values to an int or float seems to fix it. For example:

$coordinates => array( 
    (float) $ap->latitude,
    (float) $ap->longitude 
);

Maven fails to find local artifact

Maven remembers when it didn't find something. The key is "resolution will not be reattempted until the update interval of internal has elapsed or updates are forced ->"

The quick solution is to delete your local "repository" subdirectory for the problem artifact - assuming you have fixed the problem with it. :)

mvn -U will force update from remote repository - again, assuming you have now populated remote with said artifact.

Python List & for-each access (Find/Replace in built-in list)

Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.

As noted in the comments, when you loop over a list with something like for member in my_list the member variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:

my_list = [1,2,3]
for member in my_list:
    member = 42
print my_list

Output:

[1, 2, 3]

If you want to change a list containing immutable types, you need to do something like:

my_list = [1,2,3]
for ndx, member in enumerate(my_list):
    my_list[ndx] += 42
print my_list

Output:

[43, 44, 45]

If your list contains mutable objects, you can modify the current member object directly:

class C:
    def __init__(self, n):
        self.num = n
    def __repr__(self):
        return str(self.num)

my_list = [C(i) for i in xrange(3)]
for member in my_list:
    member.num += 42
print my_list

[42, 43, 44]

Note that you are still not changing the list, simply modifying the objects in the list.

You might benefit from reading Naming and Binding.

How to pass optional parameters while omitting some other optional parameters?

you can use optional variable by ? or if you have multiple optional variable by ..., example:

function details(name: string, country="CA", address?: string, ...hobbies: string) {
    // ...
}

In the above:

  • name is required
  • country is required and has a default value
  • address is optional
  • hobbies is an array of optional params

How to POST the data from a modal form of Bootstrap?

You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form.

You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.

<form asp-action="AddUsersToRole" method="POST" class="mb-3">

    @await Html.PartialAsync("~/Views/Users/_SelectList.cshtml", Model.Users)

    <div class="modal fade" id="role-select-modal" tabindex="-1" role="dialog" aria-labelledby="role-select-modal" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Select a Role</h5>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add Users to Role</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

</form>

You can post (or GET) your form data to any URL. By default it is the serving page URL, but you can change it by setting the form action. You do not have to use ajax.

Mozilla documentation on form action

Undefined reference to vtable

I tried all the detailed steps by JaMIT and still got stumped by this error. After a good amount of head-banging, I figured it out. I was careless. You should be able to reproduce this painful-to-look-at error w/ the following sample code.

[jaswantp@jaswant-arch build]$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /build/gcc/src/gcc/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++,d --with-isl --with-linker-hash-style=gnu --with-system-zlib --enable-__cxa_atexit --enable-cet=auto --enable-checking=release --enable-clocale=gnu --enable-default-pie --enable-default-ssp --enable-gnu-indirect-function --enable-gnu-unique-object --enable-install-libiberty --enable-linker-build-id --enable-lto --enable-multilib --enable-plugin --enable-shared --enable-threads=posix --disable-libssp --disable-libstdcxx-pch --disable-libunwind-exceptions --disable-werror gdc_include_dir=/usr/include/dlang/gdc
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 10.2.0 (GCC) 

// CelesetialBody.h
class CelestialBody{
public:
    virtual void Print();
protected:
    CelestialBody();
    virtual ~CelestialBody();
};
// CelestialBody.cpp
#include "CelestialBody.h"

CelestialBody::CelestialBody() {}

CelestialBody::~CelestialBody() = default;

void CelestialBody::Print() {}
// Planet.h
#include "CelestialBody.h"

class Planet : public CelestialBody
{
public:
    void Print() override;
protected:
    Planet();
    ~Planet() override;
};
// Planet.cpp
#include "Planet.h"

Planet::Planet() {}
Planet::~Planet() {}

void Print() {} // Deliberately forgot to prefix `Planet::`
# CMakeLists.txt
cmake_minimum_required(VERSION 3.12)
project (space_engine)
add_library (CelestialBody SHARED CelestialBody.cpp)
add_library (Planet SHARED Planet.cpp)
target_include_directories (CelestialBody PRIVATE ${CMAKE_CURRENT_LIST_DIR})  
target_include_directories (Planet PRIVATE ${CMAKE_CURRENT_LIST_DIR})    
target_link_libraries (Planet PUBLIC CelestialBody)

# hardened linker flags to catch undefined symbols
target_link_options(Planet 
    PRIVATE 
    -Wl,--as-needed
    -Wl,--no-undefined
)

And we get our favourite error.

$ mkdir build
$ cd build
$ cmake ..
$ make
[ 50%] Built target CelestialBody
Scanning dependencies of target Planet
[ 75%] Building CXX object CMakeFiles/Planet.dir/Planet.cpp.o
[100%] Linking CXX shared library libPlanet.so
/usr/bin/ld: CMakeFiles/Planet.dir/Planet.cpp.o: in function `Planet::Planet()':
Planet.cpp:(.text+0x1b): undefined reference to `vtable for Planet'
/usr/bin/ld: CMakeFiles/Planet.dir/Planet.cpp.o: in function `Planet::~Planet()':
Planet.cpp:(.text+0x3d): undefined reference to `vtable for Planet'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/Planet.dir/build.make:104: libPlanet.so] Error 1
make[1]: *** [CMakeFiles/Makefile2:97: CMakeFiles/Planet.dir/all] Error 2
make: *** [Makefile:103: all] Error 2

What I've done in Planet.cpp should of course be resolved with this tip

  1. Look at your class definition. Find the first non-inline virtual function that is not pure virtual (not "= 0") and whose definition you provide (not "= default").

from JaMIT's answer. If there is anyone else who tried all the above and nothing worked, maybe you too, like me, carelessly forgot to prefix <ClassName>:: to one or more member functions.

Either I need to get my eyes checked or I need to get some sleep.

How to make an installer for my C# application?

There are several methods, two of which are as follows. Provide a custom installer or a setup project.

Here is how to create a custom installer

[RunInstaller(true)]
public class MyInstaller : Installer
{
    public HelloInstaller()
        : base()
    {
    }

    public override void Commit(IDictionary mySavedState)
    {
        base.Commit(mySavedState);
        System.IO.File.CreateText("Commit.txt");
    }

    public override void Install(IDictionary stateSaver)
    {
        base.Install(stateSaver);
        System.IO.File.CreateText("Install.txt");
    }

    public override void Uninstall(IDictionary savedState)
    {
        base.Uninstall(savedState);
        File.Delete("Commit.txt");
        File.Delete("Install.txt");
    }

    public override void Rollback(IDictionary savedState)
    {
        base.Rollback(savedState);
        File.Delete("Install.txt");
    }
}

To add a setup project

  • Menu file -> New -> Project --> Other Projects Types --> Setup and Deployment

  • Set properties of the project, using the properties window

The article How to create a Setup package by using Visual Studio .NET provides the details.

How do I bottom-align grid elements in bootstrap fluid layout

Well, I didn't like any of those answers, my solution of the same problem was to add this:<div>&nbsp;</div>. So in your scheme it would look like this (more or less), no style changes were necessary in my case:

-row-fluid-------------------------------------
+-span6----------+ +----span6----------+
|                | | +---div---+       |
| content        | | | & nbsp; |       |
| that           | | +---------+       |
| is tall        | | +-----div--------+|   
|                | | |short content   ||
|                | | +----------------+|
+----------------+ +-------------------+
-----------------------------------------------

How to write new line character to a file in Java

Here is a snippet that gets the default newline character for the current platform. Use System.getProperty("os.name") and System.getProperty("os.version"). Example:

public static String getSystemNewline(){
    String eol = null;
    String os = System.getProperty("os.name").toLowerCase();
    if(os.contains("mac"){
        int v = Integer.parseInt(System.getProperty("os.version"));
        eol = (v <= 9 ? "\r" : "\n");
    }
    if(os.contains("nix"))
        eol = "\n";
    if(os.contains("win"))
        eol = "\r\n";

    return eol;
}

Where eol is the newline

How to embed a YouTube channel into a webpage

Seems like the accepted answer does not work anymore. I found the correct method from another post: https://stackoverflow.com/a/46811403/6368026

Now you should use:

http://www.youtube.com/embed/videoseries?list=USERID And the USERID is your youtube user id with 'UU' appended.

For example, if your user id is TlQ5niAIDsLdEHpQKQsupg then you should put UUTlQ5niAIDsLdEHpQKQsupg. If you only have the channel id (which you can find in your channel URL) then just replace the first two characters (UC) with UU.

So in the end you would have an URL like this:

http://www.youtube.com/embed/videoseries?list=UUTlQ5niAIDsLdEHpQKQsupg

nodemon not working: -bash: nodemon: command not found

Just writing what did worked for me - (on Windows machine, installing node locally to the project) if you do not want to install it globally (i.e without -g flag) you have to use

npx nodemon app

where app is your app.js is your program file to launch.

load csv into 2D matrix with numpy for plotting

Pure numpy

numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1)

Check out the loadtxt documentation.

You can also use python's csv module:

import csv
import numpy
reader = csv.reader(open("test.csv", "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype("float")

You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:

result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float")

Added Hint:

You could also use pandas.io.parsers.read_csv and get the associated numpy array which can be faster.

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

Many people have answered the mechanical details already, but it's worth noting: This is a poor design choice, by Java.

Java's asList method is documented as "Returns a fixed-size list...". If you take its result and call (say) the .add method, it throws an UnsupportedOperationException. This is unintuitive behavior! If a method says it returns a List, the standard expectation is that it returns an object which supports the methods of interface List. A developer shouldn't have to memorize which of the umpteen util.List methods create Lists that don't actually support all the List methods.

If they had named the method asImmutableList, it would make sense. Or if they just had the method return an actual List (and copy the backing array), it would make sense. They decided to favor both runtime-performance and short names, at the expense of violating both the Principle of Least Surprise and the good-O.O. practice of avoiding UnsupportedOperationExceptions.

(Also, the designers might have made a interface ImmutableList, to avoid a plethora of UnsupportedOperationExceptions.)

How to create a GUID/UUID in Python

Check this post, helped me a lot. In short, the best option for me was:

import random 
import string 

# defining function for random 
# string id with parameter 
def ran_gen(size, chars=string.ascii_uppercase + string.digits): 
    return ''.join(random.choice(chars) for x in range(size)) 

# function call for random string 
# generation with size 8 and string  
print (ran_gen(8, "AEIOSUMA23")) 

Because I needed just 4-6 random characters instead of bulky GUID.

Why are arrays of references illegal?

I believe the answer is very simple and it has to do with semantic rules of references and how arrays are handled in C++.

In short: References can be thought of as structs which don't have a default constructor, so all the same rules apply.

1) Semantically, references don't have a default value. References can only be created by referencing something. References don't have a value to represent the absence of a reference.

2) When allocating an array of size X, program creates a collection of default-initialized objects. Since reference doesn't have a default value, creating such an array is semantically illegal.

This rule also applies to structs/classes which don't have a default constructor. The following code sample doesn't compile:

struct Object
{
    Object(int value) { }
};

Object objects[1]; // Error: no appropriate default constructor available

Is it possible for UIStackView to scroll?

Horizontal Scrolling (UIStackView within UIScrollView)

For horizontal scrolling. First, create a UIStackView and a UIScrollView and add them to your view in the following way:

let scrollView = UIScrollView()
let stackView = UIStackView()

scrollView.addSubview(stackView)
view.addSubview(scrollView)

Remembering to set the translatesAutoresizingMaskIntoConstraints to false on the UIStackView and the UIScrollView:

stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false

To get everything working the trailing, leading, top and bottom anchors of the UIStackView should be equal to the UIScrollView anchors:

stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true

But the width anchor of the UIStackView must the equal to or greater than the width of the UIScrollView anchor:

stackView.widthAnchor.constraint(greaterThanOrEqualTo: scrollView.widthAnchor).isActive = true

Now anchor your UIScrollView, for example:

scrollView.heightAnchor.constraint(equalToConstant: 80).isActive = true
scrollView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

scrollView.bottomAnchor.constraint(equalTo:view.safeAreaLayoutGuide.bottomAnchor).isActive = true
scrollView.leadingAnchor.constraint(equalTo:view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo:view.trailingAnchor).isActive = true 

Next, I would suggest trying the following settings for the UIStackView alignment and distribution:

topicStackView.axis = .horizontal
topicStackView.distribution = .equalCentering
topicStackView.alignment = .center

topicStackView.spacing = 10

Finally you'll need to use the addArrangedSubview: method to add subviews to your UIStackView.

Text Insets

One additional feature that you might find useful is that because the UIStackView is held within a UIScrollView you now have access to text insets to make things look a bit prettier.

let inset:CGFloat = 20
scrollView.contentInset.left = inset
scrollView.contentInset.right = inset

// remember if you're using insets then reduce the width of your stack view to match
stackView.widthAnchor.constraint(greaterThanOrEqualTo: topicScrollView.widthAnchor, constant: -inset*2).isActive = true

delete image from folder PHP

You can try this code. This is Simple PHP Image Deleting code from the server.

<form method="post">
<input type="text" name="photoname"> // You can type your image name here...
<input type="submit" name="submit" value="Delete">
</form>

<?php
if (isset($_POST['submit'])) 
{
$photoname = $_POST['photoname'];
if (!unlink($photoname))
  {
  echo ("Error deleting $photoname");
  }
else
  {
  echo ("Deleted $photoname");
  }
}
?>

jQuery removing '-' character from string

$mylabel.text( $mylabel.text().replace('-', '') );

Since text() gets the value, and text( "someValue" ) sets the value, you just place one inside the other.

Would be the equivalent of doing:

var newValue = $mylabel.text().replace('-', '');
$mylabel.text( newValue );

EDIT:

I hope I understood the question correctly. I'm assuming $mylabel is referencing a DOM element in a jQuery object, and the string is in the content of the element.

If the string is in some other variable not part of the DOM, then you would likely want to call the .replace() function against that variable before you insert it into the DOM.

Like this:

var someVariable = "-123456";
$mylabel.text( someVariable.replace('-', '') );

or a more verbose version:

var someVariable = "-123456";
someVariable = someVariable.replace('-', '');
$mylabel.text( someVariable );

Request format is unrecognized for URL unexpectedly ending in

For the record I was getting this error when I moved an old app from one server to another. I added the <add name="HttpGet"/> <add name="HttpPost"/> elements to the web.config, which changed the error to:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at BitMeter2.DataBuffer.incrementCurrent(Int64 val)
   at BitMeter2.DataBuffer.WindOn(Int64 count, Int64 amount)
   at BitMeter2.DataHistory.windOnBuffer(DataBuffer buffer, Int64 totalAmount, Int32 increments)
   at BitMeter2.DataHistory.NewData(Int64 downloadValue, Int64 uploadValue)
   at BitMeter2.frmMain.tickProcessing(Boolean fromTimerEvent)

In order to fix this error I had to add the ScriptHandlerFactory lines to web.config:

  <system.webServer>
    <handlers>
      <remove name="ScriptHandlerFactory" />
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </handlers>
  </system.webServer>

Why it worked without these lines on one web server and not the other I don't know.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Select Into functionality only works for PL/SQL Block, when you use Execute immediate , oracle interprets v_query_str as a SQL Query string so you can not use into .will get keyword missing Exception. in example 2 ,we are using begin end; so it became pl/sql block and its legal.

Convert Json string to Json object in Swift 4

Using JSONSerialization always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable in Swift 4. If you wield a [String:Any] in front of a simple struct it will ... hurt. Check out this in a Playground:

import Cocoa

let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!

struct Form: Codable {
    let id: Int
    let name: String
    let description: String?

    private enum CodingKeys: String, CodingKey {
        case id = "form_id"
        case name = "form_name"
        case description = "form_desc"
    }
}

do {
    let f = try JSONDecoder().decode([Form].self, from: data)
    print(f)
    print(f[0])
} catch {
    print(error)
}

With minimal effort handling this will feel a whole lot more comfortable. And you are given a lot more information if your JSON does not parse properly.

How do I build an import library (.lib) AND a DLL in Visual C++?

Does your DLL project have any actual exports? If there are no exports, the linker will not generate an import library .lib file.

In the non-Express version of VS, the import libray name is specfied in the project settings here:

Configuration Properties/Linker/Advanced/Import Library

I assume it's the same in Express (if it even provides the ability to configure the name).

How to get the browser language using JavaScript

The "JavaScript" way:

var lang = navigator.language || navigator.userLanguage; //no ?s necessary

Really you should be doing language detection on the server, but if it's absolutely necessary to know/use via JavaScript, it can be gotten.