Programs & Examples On #Registerhotkey

Replace part of a string with another string

If all strings are std::string, you'll find strange problems with the cutoff of characters if using sizeof() because it's meant for C strings, not C++ strings. The fix is to use the .size() class method of std::string.

sHaystack.replace(sHaystack.find(sNeedle), sNeedle.size(), sReplace);

That replaces sHaystack inline -- no need to do an = assignment back on that.

Example usage:

std::string sHaystack = "This is %XXX% test.";
std::string sNeedle = "%XXX%";
std::string sReplace = "my special";
sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
std::cout << sHaystack << std::endl;

How can I display a JavaScript object?

If you would like to see data in tabular format you can use

console.table(obj);

Table can be sorted if you click on the table column.

You can also select what columns to show:

console.table(obj, ['firstName', 'lastName']);

You can find more information about console.table here

Project vs Repository in GitHub

The conceptual difference in my understanding it that a project can contain many repo's and that are independent of each other, while simultaneously a repo may contain many projects. Repo's being just a storage place for code while a project being a collection of tasks for a certain feature.

Does that make sense? A large repo can have many projects being worked on by different people at the same time (lots of difference features being added to a monolith), a large project may have many small repos that are separate but part of the same project that interact with each other - microservices? Its a personal take on what you want to do. I think that repo (storage) vs project (tasks) is the main difference - if i am wrong please let me know / explain! Thanks.

How can I adjust DIV width to contents

I'd like to add to the other answers this pretty new solution:

If you don't want the element to become inline-block, you can do this:

.parent{
  width: min-content;
}

The support is increasing fast, so when edge decides to implement it, it will be really great: http://caniuse.com/#search=intrinsic

How can I create an object and add attributes to it?

Try the code below:

$ python
>>> class Container(object):
...     pass 
...
>>> x = Container()
>>> x.a = 10
>>> x.b = 20
>>> x.banana = 100
>>> x.a, x.b, x.banana
(10, 20, 100)
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', 
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',     '__sizeof__', 
'__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'banana']

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid

In my case I had .Net core SDK 3.1.403 was installed. So I installed the corresponding .Net Core Windows Server Hosting which is .NET core 3.1.9 - Windows Server Hosting.

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

An unmodifiable map may still change. It is only a view on a modifiable map, and changes in the backing map will be visible through the unmodifiable map. The unmodifiable map only prevents modifications for those who only have the reference to the unmodifiable view:

Map<String, String> realMap = new HashMap<String, String>();
realMap.put("A", "B");

Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap);

// This is not possible: It would throw an 
// UnsupportedOperationException
//unmodifiableMap.put("C", "D");

// This is still possible:
realMap.put("E", "F");

// The change in the "realMap" is now also visible
// in the "unmodifiableMap". So the unmodifiableMap
// has changed after it has been created.
unmodifiableMap.get("E"); // Will return "F". 

In contrast to that, the ImmutableMap of Guava is really immutable: It is a true copy of a given map, and nobody may modify this ImmutableMap in any way.

Update:

As pointed out in a comment, an immutable map can also be created with the standard API using

Map<String, String> immutableMap = 
    Collections.unmodifiableMap(new LinkedHashMap<String, String>(realMap)); 

This will create an unmodifiable view on a true copy of the given map, and thus nicely emulates the characteristics of the ImmutableMap without having to add the dependency to Guava.

How do I connect to this localhost from another computer on the same network?

This is a side note if one still can't access localhost from another devices after following through the step above. This might be due to the apache ports.conf has been configured to serve locally (127.0.0.1) and not to outside.

check the following, (for ubuntu apache2)

  $ cat /etc/apache2/ports.conf

if the following is set,

NameVirtualHost *:80  
Listen 127.0.0.1:80  

then change it back to default value

NameVirtualHost *:80  
Listen 80  

Why would one omit the close tag?

It isn't a tag…

But if you have it, you risk having white space after it.

If you then use it as an include at the top of a document, you could end up inserting white space (i.e. content) before you attempt to send HTTP headers … which isn't allowed.

mysql said: Cannot connect: invalid settings. xampp

I also faced the same problem it was because another mysql service was running and in parallel mysql in xampp i was trying to run. So you may check that out if other solutions don't work out. You can stop that by the following command:

sudo service mysql stop

May help few users.

Is it possible to make input fields read-only through CSS?

With CSS only? This is sort of possible on text inputs by using user-select:none:

.print {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;          
}

JSFiddle example.

It's well worth noting that this will not work in browsers which do not support CSS3 or support the user-select property. The readonly property should be ideally given to the input markup you wish to be made readonly, but this does work as a hacky CSS alternative.

With JavaScript:

document.getElementById("myReadonlyInput").setAttribute("readonly", "true");

Edit: The CSS method no longer works in Chrome (29). The -webkit-user-select property now appears to be ignored on input elements.

Can’t delete docker image with dependent child images

Expanding on the answer provided by @Nguyen - this function can be added to your .bashrc etc and then called from the commandline to help clean up any image has dependent child images errors...

You can run the function as yourself, and if a docker ps fails, then it will run the docker command with sudo and prompt you for your password.

Does NOT delete images for any running containers!

docker_rmi_dependants ()                                                                                                                                                         
{ 
  DOCKER=docker
  [ docker ps >/dev/null 2>&1 ] || DOCKER="sudo docker"

  echo "Docker: ${DOCKER}"

  for n in $(${DOCKER} images | awk '$2 == "<none>" {print $3}');
  do  
    echo "ImageID: $n";
    ${DOCKER} inspect --format='{{.Id}} {{.Parent}}' $(${DOCKER} images --filter since=$n -q);
  done;

  ${DOCKER} rmi $(${DOCKER} images | awk '$2 == "<none>" {print $3}')
}

I also have this in my .bashrc file...

docker_rm_dangling ()  
{ 
  DOCKER=docker
  [ docker ps >/dev/null 2>&1 ] || DOCKER="sudo docker"

  echo "Docker: ${DOCKER}"

  ${DOCKER} images -f dangling=true 2>&1 > /dev/null && YES=$?;                                                                                                                  
  if [ $YES -eq 1 ]; then
    read -t 30 -p "Press ENTER to remove, or CTRL-C to quit.";
    ${DOCKER} rmi $(${DOCKER} images -f dangling=true -q);
  else
    echo "Nothing to do... all groovy!";
  fi  
}

Works with:

$ docker --version 
Docker version 17.05.0-ce, build 89658be

Search and replace in bash using regular expressions

Use [[:digit:]] (note the double brackets) as the pattern:

$ hello=ho02123ware38384you443d34o3434ingtod38384day
$ echo ${hello//[[:digit:]]/}
howareyoudoingtodday

Just wanted to summarize the answers (especially @nickl-'s https://stackoverflow.com/a/22261334/2916086).

Print very long string completely in pandas dataframe

I have created a small utility function, this works well for me

def display_text_max_col_width(df, width):
    with pd.option_context('display.max_colwidth', width):
        print(df)

display_text_max_col_width(train_df["Description"], 800)

I can change length of the width as per my requirement, without setting any option permanently.

Laravel 5: Display HTML with Blade

If you use the Bootstrap Collapse class sometimes {!! $text !!} is not worked for me but {{ html_entity_decode($text) }} is worked for me.

Howto: Clean a mysql InnoDB storage engine?

Here is a more complete answer with regard to InnoDB. It is a bit of a lengthy process, but can be worth the effort.

Keep in mind that /var/lib/mysql/ibdata1 is the busiest file in the InnoDB infrastructure. It normally houses six types of information:

InnoDB Architecture

InnoDB Architecture

Many people create multiple ibdata files hoping for better disk-space management and performance, however that belief is mistaken.

Can I run OPTIMIZE TABLE ?

Unfortunately, running OPTIMIZE TABLE against an InnoDB table stored in the shared table-space file ibdata1 does two things:

  • Makes the table’s data and indexes contiguous inside ibdata1
  • Makes ibdata1 grow because the contiguous data and index pages are appended to ibdata1

You can however, segregate Table Data and Table Indexes from ibdata1 and manage them independently.

Can I run OPTIMIZE TABLE with innodb_file_per_table ?

Suppose you were to add innodb_file_per_table to /etc/my.cnf (my.ini). Can you then just run OPTIMIZE TABLE on all the InnoDB Tables?

Good News : When you run OPTIMIZE TABLE with innodb_file_per_table enabled, this will produce a .ibd file for that table. For example, if you have table mydb.mytable witha datadir of /var/lib/mysql, it will produce the following:

  • /var/lib/mysql/mydb/mytable.frm
  • /var/lib/mysql/mydb/mytable.ibd

The .ibd will contain the Data Pages and Index Pages for that table. Great.

Bad News : All you have done is extract the Data Pages and Index Pages of mydb.mytable from living in ibdata. The data dictionary entry for every table, including mydb.mytable, still remains in the data dictionary (See the Pictorial Representation of ibdata1). YOU CANNOT JUST SIMPLY DELETE ibdata1 AT THIS POINT !!! Please note that ibdata1 has not shrunk at all.

InnoDB Infrastructure Cleanup

To shrink ibdata1 once and for all you must do the following:

  1. Dump (e.g., with mysqldump) all databases into a .sql text file (SQLData.sql is used below)

  2. Drop all databases (except for mysql and information_schema) CAVEAT : As a precaution, please run this script to make absolutely sure you have all user grants in place:

    mkdir /var/lib/mysql_grants
    cp /var/lib/mysql/mysql/* /var/lib/mysql_grants/.
    chown -R mysql:mysql /var/lib/mysql_grants
    
  3. Login to mysql and run SET GLOBAL innodb_fast_shutdown = 0; (This will completely flush all remaining transactional changes from ib_logfile0 and ib_logfile1)

  4. Shutdown MySQL

  5. Add the following lines to /etc/my.cnf (or my.ini on Windows)

    [mysqld]
    innodb_file_per_table
    innodb_flush_method=O_DIRECT
    innodb_log_file_size=1G
    innodb_buffer_pool_size=4G
    

    (Sidenote: Whatever your set for innodb_buffer_pool_size, make sure innodb_log_file_size is 25% of innodb_buffer_pool_size.

    Also: innodb_flush_method=O_DIRECT is not available on Windows)

  6. Delete ibdata* and ib_logfile*, Optionally, you can remove all folders in /var/lib/mysql, except /var/lib/mysql/mysql.

  7. Start MySQL (This will recreate ibdata1 [10MB by default] and ib_logfile0 and ib_logfile1 at 1G each).

  8. Import SQLData.sql

Now, ibdata1 will still grow but only contain table metadata because each InnoDB table will exist outside of ibdata1. ibdata1 will no longer contain InnoDB data and indexes for other tables.

For example, suppose you have an InnoDB table named mydb.mytable. If you look in /var/lib/mysql/mydb, you will see two files representing the table:

  • mytable.frm (Storage Engine Header)
  • mytable.ibd (Table Data and Indexes)

With the innodb_file_per_table option in /etc/my.cnf, you can run OPTIMIZE TABLE mydb.mytable and the file /var/lib/mysql/mydb/mytable.ibd will actually shrink.

I have done this many times in my career as a MySQL DBA. In fact, the first time I did this, I shrank a 50GB ibdata1 file down to only 500MB!

Give it a try. If you have further questions on this, just ask. Trust me; this will work in the short term as well as over the long haul.

CAVEAT

At Step 6, if mysql cannot restart because of the mysql schema begin dropped, look back at Step 2. You made the physical copy of the mysql schema. You can restore it as follows:

mkdir /var/lib/mysql/mysql
cp /var/lib/mysql_grants/* /var/lib/mysql/mysql
chown -R mysql:mysql /var/lib/mysql/mysql

Go back to Step 6 and continue

UPDATE 2013-06-04 11:13 EDT

With regard to setting innodb_log_file_size to 25% of innodb_buffer_pool_size in Step 5, that's blanket rule is rather old school.

Back on July 03, 2006, Percona had a nice article why to choose a proper innodb_log_file_size. Later, on Nov 21, 2008, Percona followed up with another article on how to calculate the proper size based on peak workload keeping one hour's worth of changes.

I have since written posts in the DBA StackExchange about calculating the log size and where I referenced those two Percona articles.

Personally, I would still go with the 25% rule for an initial setup. Then, as the workload can more accurate be determined over time in production, you could resize the logs during a maintenance cycle in just minutes.

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

Ran into this same issue, Bind Address back and forth to no avail. Solution for me was flushing privileges.

mysql> FLUSH PRIVILEGES;

fe_sendauth: no password supplied

After making changes to the pg_hba.conf or postgresql.conf files, the cluster needs to be reloaded to pick up the changes.

From the command line: pg_ctl reload

From within a db (as superuser): select pg_reload_conf();

From PGAdmin: right-click db name, select "Reload Configuration"

Note: the reload is not sufficient for changes like enabling archiving, changing shared_buffers, etc -- those require a cluster restart.

How to export data from Spark SQL to CSV

Since Spark 2.X spark-csv is integrated as native datasource. Therefore, the necessary statement simplifies to (windows)

df.write
  .option("header", "true")
  .csv("file:///C:/out.csv")

or UNIX

df.write
  .option("header", "true")
  .csv("/var/out.csv")

Notice: as the comments say, it is creating the directory by that name with the partitions in it, not a standard CSV file. This, however, is most likely what you want since otherwise your either crashing your driver (out of RAM) or you could be working with a non distributed environment.

How to create JSON object using jQuery

Nested JSON object

var data = {
        view:{
            type: 'success', note:'Updated successfully',
        },
    };

You can parse this data.view.type and data.view.note

JSON Object and inside Array

var data = {
          view: [ 
                {type: 'success', note:'updated successfully'}
          ],  
     };

You can parse this data.view[0].type and data.view[0].note

Bring a window to the front in WPF

I know this question is rather old, but I've just come across this precise scenario and wanted to share the solution I've implemented.

As mentioned in comments on this page, several of the solutions proposed do not work on XP, which I need to support in my scenario. While I agree with the sentiment by @Matthew Xavier that generally this is a bad UX practice, there are times where it's entirely a plausable UX.

The solution to bringing a WPF window to the top was actually provided to me by the same code I'm using to provide the global hotkey. A blog article by Joseph Cooney contains a link to his code samples that contains the original code.

I've cleaned up and modified the code a little, and implemented it as an extension method to System.Windows.Window. I've tested this on XP 32 bit and Win7 64 bit, both of which work correctly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interop;
using System.Runtime.InteropServices;

namespace System.Windows
{
    public static class SystemWindows
    {
        #region Constants

        const UInt32 SWP_NOSIZE = 0x0001;
        const UInt32 SWP_NOMOVE = 0x0002;
        const UInt32 SWP_SHOWWINDOW = 0x0040;

        #endregion

        /// <summary>
        /// Activate a window from anywhere by attaching to the foreground window
        /// </summary>
        public static void GlobalActivate(this Window w)
        {
            //Get the process ID for this window's thread
            var interopHelper = new WindowInteropHelper(w);
            var thisWindowThreadId = GetWindowThreadProcessId(interopHelper.Handle, IntPtr.Zero);

            //Get the process ID for the foreground window's thread
            var currentForegroundWindow = GetForegroundWindow();
            var currentForegroundWindowThreadId = GetWindowThreadProcessId(currentForegroundWindow, IntPtr.Zero);

            //Attach this window's thread to the current window's thread
            AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, true);

            //Set the window position
            SetWindowPos(interopHelper.Handle, new IntPtr(0), 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);

            //Detach this window's thread from the current window's thread
            AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, false);

            //Show and activate the window
            if (w.WindowState == WindowState.Minimized) w.WindowState = WindowState.Normal;
            w.Show();
            w.Activate();
        }

        #region Imports

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

        [DllImport("user32.dll")]
        private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

        [DllImport("user32.dll")]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        #endregion
    }
}

I hope this code helps others who encounter this problem.

How to obtain the last path segment of a URI

I'm using the following in a utility class:

public static String lastNUriPathPartsOf(final String uri, final int n, final String... ellipsis)
  throws URISyntaxException {
    return lastNUriPathPartsOf(new URI(uri), n, ellipsis);
}

public static String lastNUriPathPartsOf(final URI uri, final int n, final String... ellipsis) {
    return uri.toString().contains("/")
        ? (ellipsis.length == 0 ? "..." : ellipsis[0])
          + uri.toString().substring(StringUtils.lastOrdinalIndexOf(uri.toString(), "/", n))
        : uri.toString();
}

Is it possible to implement a Python for range loop without an iterator variable?

If you really want to avoid putting something with a name (either an iteration variable as in the OP, or unwanted list or unwanted generator returning true the wanted amount of time) you could do it if you really wanted:

for type('', (), {}).x in range(somenumber):
    dosomething()

The trick that's used is to create an anonymous class type('', (), {}) which results in a class with empty name, but NB that it is not inserted in the local or global namespace (even if a nonempty name was supplied). Then you use a member of that class as iteration variable which is unreachable since the class it's a member of is unreachable.

Difference between r+ and w+ in fopen()

There are 2 differences, unlike r+, w+ will:

  • create the file if it does not already exist
  • first truncate it, i.e., will delete its contents

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

How to list files in a directory in a C program?

Here is a complete program how to recursively list folder's contents:

#include <dirent.h> 
#include <stdio.h> 
#include <string.h>

#define NORMAL_COLOR  "\x1B[0m"
#define GREEN  "\x1B[32m"
#define BLUE  "\x1B[34m"



/* let us make a recursive function to print the content of a given folder */

void show_dir_content(char * path)
{
  DIR * d = opendir(path); // open the path
  if(d==NULL) return; // if was not able return
  struct dirent * dir; // for the directory entries
  while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
    {
      if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
        printf("%s%s\n",BLUE, dir->d_name);
      else
      if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
      {
        printf("%s%s\n",GREEN, dir->d_name); // print its name in green
        char d_path[255]; // here I am using sprintf which is safer than strcat
        sprintf(d_path, "%s/%s", path, dir->d_name);
        show_dir_content(d_path); // recall with the new path
      }
    }
    closedir(d); // finally close the directory
}

int main(int argc, char **argv)
{

  printf("%s\n", NORMAL_COLOR);

    show_dir_content(argv[1]);

  printf("%s\n", NORMAL_COLOR);
  return(0);
}

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I had this error, I follwed below three steps to solve,

1). check proxy settings in settings.xml refer,

2). .m2 diretory to release cached files causing problems

3) Point your eclipse to correct JDK installation. Refer No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? to know how

Adding an onclick event to a div element

Its possible, we can specify onclick event in

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="thumb0" class="thumbs" onclick="fun1('rad1')" style="height:250px; width:100%; background-color:yellow;";></div>
<div id="rad1" style="height:250px; width:100%;background-color:red;" onclick="fun2('thumb0')">hello world</div>????????????????????????????????
<script>
function fun1(i) {
    document.getElementById(i).style.visibility='hidden';
}
function fun2(i) {
    document.getElementById(i).style.visibility='hidden';
}
</script>
</body>
</html>

mvn command not found in OSX Mavrerick

I got same problem, I tried all above, noting solved my problem. Luckely, I solved the problem this way:

echo $SHELL

Output

/bin/zsh
OR 
/bin/bash

If it showing "bash" in output. You have to add env properties in .bashrc file (.bash_profile i did not tried, you can try) or else
It is showing 'zsh' in output. You have to add env properties in .zshrc file, if not exist already you create one no issue.

HTML/CSS--Creating a banner/header

For the image that is not showing up. Open the image in the Image editor and check the type you are probably name it as "gif" but its saved in a different format that's one reason that the browser is unable to render it and it is not showing.
For the image stretching issue please specify the actual width and height dimensions in #banner instead of width: 100%; height: 200px that you have specified.

How to rename files and folder in Amazon S3?

aws s3 cp s3://source_folder/ s3://destination_folder/ --recursive
aws s3 rm s3://source_folder --recursive

What is Vim recording and how can it be disabled?

You start recording by q<letter> and you can end it by typing q again.

Recording is a really useful feature of Vim.

It records everything you type. You can then replay it simply by typing @<letter>. Record search, movement, replacement...

One of the best feature of Vim IMHO.

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

I faced the same problem. Updating bash_profile with the following lines, solved the problem for me:

export JAVA_HOME='/usr/'

export PATH=${JAVA_HOME}/bin:$PATH

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;
    console.log(e.touches);
});

I know it been asked a long time ago, but I thought a concrete example might help.

Change location of log4j.properties

You must use log4j.configuration property like this:

java -Dlog4j.configuration=file:/path/to/log4j.properties myApp

If the file is under the class-path (inside ./src/main/resources/ folder), you can omit the file:// protocol:

java -Dlog4j.configuration=path/to/log4j.properties myApp

Use jQuery to navigate away from page

Other answers rightly point out that there is no need to use jQuery in order to navigate to another URL; that's why there's no jQuery function which does so!

If you're asking how to click a link via jQuery then assuming you have markup which looks like:

<a id="my-link" href="/relative/path.html">Click Me!</a>

You could click() it by executing:

$('#my-link').click();

Breadth First Vs Depth First

I think it would be interesting to write both of them in a way that only by switching some lines of code would give you one algorithm or the other, so that you will see that your dillema is not so strong as it seems to be at first.

I personally like the interpretation of BFS as flooding a landscape: the low altitude areas will be flooded first, and only then the high altitude areas would follow. If you imagine the landscape altitudes as isolines as we see in geography books, its easy to see that BFS fills all area under the same isoline at the same time, just as this would be with physics. Thus, interpreting altitudes as distance or scaled cost gives a pretty intuitive idea of the algorithm.

With this in mind, you can easily adapt the idea behind breadth first search to find the minimum spanning tree easily, shortest path, and also many other minimization algorithms.

I didnt see any intuitive interpretation of DFS yet (only the standard one about the maze, but it isnt as powerful as the BFS one and flooding), so for me it seems that BFS seems to correlate better with physical phenomena as described above, while DFS correlates better with choices dillema on rational systems (ie people or computers deciding which move to make on a chess game or going out of a maze).

So, for me the difference between lies on which natural phenomenon best matches their propagation model (transversing) in real life.

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

If you're using npm >=1.0, you can use npm link <global-package> to create a local link to a package already installed globally. (Caveat: The OS must support symlinks.)

However, this doesn't come without its problems.

npm link is a development tool. It's awesome for managing packages on your local development box. But deploying with npm link is basically asking for problems, since it makes it super easy to update things without realizing it.

As an alternative, you can install the packages locally as well as globally.

For additional information, see

jQuery Array of all selected checkboxes (by class)

You can use the :checkbox and :checked pseudo-selectors and the .class selector, with that you will make sure that you are getting the right elements, only checked checkboxes with the class you specify.

Then you can easily use the Traversing/map method to get an array of values:

var values = $('input:checkbox:checked.group1').map(function () {
  return this.value;
}).get(); // ["18", "55", "10"]

Calling UserForm_Initialize() in a Module

From a module:

UserFormName.UserForm_Initialize

Just make sure that in your userform, you update the sub like so:

Public Sub UserForm_Initialize() so it can be called from outside the form.

Alternately, if the Userform hasn't been loaded:

UserFormName.Show will end up calling UserForm_Initialize because it loads the form.

How to change Toolbar home icon color

I solved it by editing styles.xml:

<style name="ToolbarColoredBackArrow" parent="AppTheme">
    <item name="android:textColorSecondary">INSERT_COLOR_HERE</item>
</style>

...then referencing the style in the Toolbar definition in the activity:

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

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        app:theme="@style/ToolbarColoredBackArrow"
        app:popupTheme="@style/AppTheme"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"/>

How to read data From *.CSV file using javascript?

Don't split on commas -- it won't work for most CSV files, and this question has wayyyy too many views for the asker's kind of input data to apply to everyone. Parsing CSV is kind of scary since there's no truly official standard, and lots of delimited text writers don't consider edge cases.

This question is old, but I believe there's a better solution now that Papa Parse is available. It's a library I wrote, with help from contributors, that parses CSV text or files. It's the only JS library I know of that supports files gigabytes in size. It also handles malformed input gracefully.

1 GB file parsed in 1 minute: Parsed 1 GB file in 1 minute

(Update: With Papa Parse 4, the same file took only about 30 seconds in Firefox. Papa Parse 4 is now the fastest known CSV parser for the browser.)

Parsing text is very easy:

var data = Papa.parse(csvString);

Parsing files is also easy:

Papa.parse(file, {
    complete: function(results) {
        console.log(results);
    }
});

Streaming files is similar (here's an example that streams a remote file):

Papa.parse("http://example.com/bigfoo.csv", {
    download: true,
    step: function(row) {
        console.log("Row:", row.data);
    },
    complete: function() {
        console.log("All done!");
    }
});

If your web page locks up during parsing, Papa can use web workers to keep your web site reactive.

Papa can auto-detect delimiters and match values up with header columns, if a header row is present. It can also turn numeric values into actual number types. It appropriately parses line breaks and quotes and other weird situations, and even handles malformed input as robustly as possible. I've drawn on inspiration from existing libraries to make Papa, so props to other JS implementations.

Matplotlib scatter plot with different text at each data point

In case anyone is trying to apply the above solutions to a .scatter() instead of a .subplot(),

I tried running the following code

y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.scatter(z, y)

for i, txt in enumerate(n):
    ax.annotate(txt, (z[i], y[i]))

But ran into errors stating "cannot unpack non-iterable PathCollection object", with the error specifically pointing at codeline fig, ax = plt.scatter(z, y)

I eventually solved the error using the following code

plt.scatter(z, y)

for i, txt in enumerate(n):
    plt.annotate(txt, (z[i], y[i]))

I didn't expect there to be a difference between .scatter() and .subplot() I should have known better.

how to install tensorflow on anaconda python 3.6

Uninstall Python 3.7 for Windows, and only install Python 3.6.0 then you will have no problem or receive the error message:

import tensorflow as tf ModuleNotFoundError: No module named 'tensorflow'

How to switch between frames in Selenium WebDriver using Java

WebDriver's driver.switchTo().frame() method takes one of the three possible arguments:

  • A number.

    Select a frame by its (zero-based) index. That is, if a page has three frames, the first frame would be at index 0, the second at index 1 and the third at index 2. Once the frame has been selected, all subsequent calls on the WebDriver interface are made to that frame.

  • A name or ID.

    Select a frame by its name or ID. Frames located by matching name attributes are always given precedence over those matched by ID.

  • A previously found WebElement.

    Select a frame using its previously located WebElement.

Get the frame by it's id/name or locate it by driver.findElement() and you'll be good.

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

I was having the same issue and fixed it by changing the default program to open .ps1 files to PowerShell. It was set to Notepad.

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

I have fixed the by this way:

Create a folder in your resource directory name "drawable-nodpi" and then move yours all resources in this directory from others drawable directory.

Now clean your project and then rebuilt. Run again hopefully it will work this time without any resource not found exception.

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

How to access to the parent object in c#

Why not change the constructor on Production to let you pass in a reference at construction time:

public class Meter
{
   private int _powerRating = 0; 
   private Production _production;

   public Meter()
   {
      _production = new Production(this);
   }
}

In the Production constructor you can assign this to a private field or a property. Then Production will always have access to is parent.

Select unique or distinct values from a list in UNIX shell script

./script.sh | sort -u

This is the same as monoxide's answer, but a bit more concise.

List of remotes for a Git repository?

None of those methods work the way the questioner is asking for and which I've often had a need for as well. eg:

$ git remote
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@bserver
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@server:/home/user
fatal: Not a git repository (or any of the parent directories): .git
$ git ls-remote
fatal: No remote configured to list refs from.
$ git ls-remote user@server:/home/user
fatal: '/home/user' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

The whole point of doing this is that you do not have any information except the remote user and server and want to find out what you have access to.

The majority of the answers assume you are querying from within a git working set. The questioner is assuming you are not.

As a practical example, assume there was a repository foo.git on the server. Someone in their wisdom decides they need to change it to foo2.git. It would really be nice to do a list of a git directory on the server. And yes, I see the problems for git. It would still be nice to have though.

Error: [$injector:unpr] Unknown provider: $routeProvider

It looks like you forgot to include the ngRoute module in your dependency for myApp.

In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.

'use strict';

angular.module('myApp', ['ngRoute']).
    config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);

How to group by month from Date field using sql

Try the Following Code

SELECT  Closing_Date = DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0), 
        Category,  
        COUNT(Status) TotalCount 
FROM    MyTable
WHERE   Closing_Date >= '2012-02-01' 
AND     Closing_Date <= '2012-12-31'
AND     Defect_Status1 IS NOT NULL
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0), Category;

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

How to find the Number of CPU Cores via .NET/C#?

Environment.ProcessorCount should give you the number of cores on the local machine.

Check If array is null or not in php

Right code of two ppl before ^_^

/* return true if values of array are empty
*/
function is_array_empty($arr){
   if(is_array($arr)){
      foreach($arr as $value){
         if(!empty($value)){
            return false;
         }
      }
   }
   return true;
}

What is Java EE?

It's meaning changes all the time. It used to mean Servlets and JSP and EJBs. Now-a-days it probably means Spring and Hibernate etc.

Really what they are looking for is experience and understanding of the Java ecosystem, Servlet containers, JMS, JMX, Hibernate etc. and how they all fit together.

Testing and source control would be an important skills too.

What happens to a declared, uninitialized variable in C? Does it have a value?

It depends on the storage duration of the variable. A variable with static storage duration is always implicitly initialized with zero.

As for automatic (local) variables, an uninitialized variable has indeterminate value. Indeterminate value, among other things, mean that whatever "value" you might "see" in that variable is not only unpredictable, it is not even guaranteed to be stable. For example, in practice (i.e. ignoring the UB for a second) this code

int num;
int a = num;
int b = num;

does not guarantee that variables a and b will receive identical values. Interestingly, this is not some pedantic theoretical concept, this readily happens in practice as consequence of optimization.

So in general, the popular answer that "it is initialized with whatever garbage was in memory" is not even remotely correct. Uninitialized variable's behavior is different from that of a variable initialized with garbage.

How to get disk capacity and free space of remote computer

Just found Get-Volume command, which returns SizeRemaining, so something like (Get-Volume -DriveLetter C).SizeRemaining / (1e+9) can be used to see remained Gb for disk C. Seems works faster than Get-WmiObject Win32_LogicalDisk.

Is it possible to change the package name of an Android app on Google Play?

Nope, you cannot just change it, you would have to upload a new package as a new app. Have a look at the Google's app Talk, its name was changed to Hangouts, but the package name is still com.google.android.talk. Because it is not doable :) Cheers.

How to extract img src, title and alt from html using php?

Here is THE solution, in PHP:

Just download QueryPath, and then do as follows:

$doc= qp($myHtmlDoc);

foreach($doc->xpath('//img') as $img) {

   $src= $img->attr('src');
   $title= $img->attr('title');
   $alt= $img->attr('alt');

}

That's it, you're done !

How to remove all null elements from a ArrayList or String Array?

There is an easy way of removing all the null values from collection.You have to pass a collection containing null as a parameter to removeAll() method

List s1=new ArrayList();
s1.add(null);

yourCollection.removeAll(s1);

Restart android machine

Have you tried simply 'reboot' with adb?

  adb reboot

Also you can run complete shell scripts (e.g. to reboot your emulator) via adb:

 adb shell <command>

The official docs can be found here.

Tracking the script execution time in PHP

You may only want to know the execution time of parts of your script. The most flexible way to time parts or an entire script is to create 3 simple functions (procedural code given here but you could turn it into a class by putting class timer{} around it and making a couple of tweaks). This code works, just copy and paste and run:

$tstart = 0;
$tend = 0;

function timer_starts()
{
global $tstart;

$tstart=microtime(true); ;

}

function timer_ends()
{
global $tend;

$tend=microtime(true); ;

}

function timer_calc()
{
global $tstart,$tend;

return (round($tend - $tstart,2));
}

timer_starts();
file_get_contents('http://google.com');
timer_ends();
print('It took '.timer_calc().' seconds to retrieve the google page');

Common HTTPclient and proxy

For httpclient 4.1.x you can set the proxy like this (taken from this example):

    HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        HttpHost target = new HttpHost("issues.apache.org", 443, "https");
        HttpGet req = new HttpGet("/");

        System.out.println("executing request to " + target + " via " + proxy);
        HttpResponse rsp = httpclient.execute(target, req);
        ...
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

Change text (html) with .animate

See Davion's anwser in this post: https://stackoverflow.com/a/26429849/1804068

HTML:

<div class="parent">
    <span id="mySpan">Something in English</span>
</div>

JQUERY

$('#mySpan').animate({'opacity': 0}, 400, function(){
        $(this).html('Something in Spanish').animate({'opacity': 1}, 400);    
    });

Live example

What is a StackOverflowError?

Like you say, you need to show some code. :-)

A stack overflow error usually happens when your function calls nest too deeply. See the Stack Overflow Code Golf thread for some examples of how this happens (though in the case of that question, the answers intentionally cause stack overflow).

Generate HTML table from 2D JavaScript array

I know this is an old question, but for those perusing the web like me, here's another solution:

Use replace() on the commas and create a set of characters to determine the end of a row. I just add -- to end of the internal arrays. That way you don't have to run a for function.

Here's a JSFiddle: https://jsfiddle.net/0rpb22pt/2/

First, you have to get a table inside your HTML and give it an id:

<table id="thisTable"><tr><td>Click me</td></tr></table>

Here's your array edited for this method:

thisArray=[["row 1, cell 1__", "row 2, cell 2--"], ["row 2, cell 1__", "row 2, cell 2"]];

Notice the added -- at the end of each array.

Because you also have commas inside of arrays, you have to differentiate them somehow so you don't end up messing up your table- adding __ after cells (besides the last one in a row) works. If you didn't have commas in your cell, this step wouldn't be necessary though.

Now here's your function:

function tryit(){
  document
    .getElementById("thisTable")
    .innerHTML="<tr><td>"+String(thisArray)
    .replace(/--,/g,"</td></tr><tr><td>")
    .replace(/__,/g,"</td><td>");
}

It works like this:

  1. Call your table and get to setting the innerHTML. document.getElementById("thisTable").innerHTML
  2. Start by adding HTML tags to start a row and data. "<tr><td>"
  3. Add thisArray as a String(). +String(thisArray)
  4. Replace every -- that ends up before a new row with the closing and opening of data and row. .replace(/--,/g,"</td></tr><tr><td>")
  5. Other commas signify separate data within rows. So replace all commas the closing and opening of data. In this case not all commas are between rows because the cells have commas, so we had to differentiate those with __: .replace(/__,/g,"</td><td>"). Normally you'd just do .replace(/,/g,"</td><td>").

As long as you don't mind adding some stray characters into your array, it takes up a lot less code and is simple to implement.

How to split csv whose columns may contain ,

I see that if you paste csv delimited text in Excel and do a "Text to Columns", it asks you for a "text qualifier". It's defaulted to a double quote so that it treats text within double quotes as literal. I imagine that Excel implements this by going one character at a time, if it encounters a "text qualifier", it keeps going to the next "qualifier". You can probably implement this yourself with a for loop and a boolean to denote if you're inside literal text.

public string[] CsvParser(string csvText)
{
    List<string> tokens = new List<string>();

    int last = -1;
    int current = 0;
    bool inText = false;

    while(current < csvText.Length)
    {
        switch(csvText[current])
        {
            case '"':
                inText = !inText; break;
            case ',':
                if (!inText) 
                {
                    tokens.Add(csvText.Substring(last + 1, (current - last)).Trim(' ', ',')); 
                    last = current;
                }
                break;
            default:
                break;
        }
        current++;
    }

    if (last != csvText.Length - 1) 
    {
        tokens.Add(csvText.Substring(last+1).Trim());
    }

    return tokens.ToArray();
}

How to add comments into a Xaml file in WPF?

Found a nice solution by Laurent Bugnion, it can look something like this:

<UserControl xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:comment="Tag to add comments"
             mc:Ignorable="d comment" d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Button Width="100"
                comment:Width="example comment on Width, will be ignored......">
        </Button>
    </Grid>
</UserControl>

Here's the link: http://blog.galasoft.ch/posts/2010/02/quick-tip-commenting-out-properties-in-xaml/

A commenter on the link provided extra characters for the ignore prefix in lieu of highlighting:

mc:Ignorable=”ØignoreØ”

ES6 class variable alternatives

As Benjamin said in his answer, TC39 explicitly decided not to include this feature at least for ES2015. However, the consensus seems to be that they will add it in ES2016.

The syntax hasn't been decided yet, but there's a preliminary proposal for ES2016 that will allow you to declare static properties on a class.

Thanks to the magic of babel, you can use this today. Enable the class properties transform according to these instructions and you're good to go. Here's an example of the syntax:

class foo {
  static myProp = 'bar'
  someFunction() {
    console.log(this.myProp)
  }
}

This proposal is in a very early state, so be prepared to tweak your syntax as time goes on.

Call static methods from regular ES6 class methods

I stumbled over this thread searching for answer to similar case. Basically all answers are found, but it's still hard to extract the essentials from them.

Kinds of Access

Assume a class Foo probably derived from some other class(es) with probably more classes derived from it.

Then accessing

  • from static method/getter of Foo
    • some probably overridden static method/getter:
      • this.method()
      • this.property
    • some probably overridden instance method/getter:
      • impossible by design
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • impossible by design
  • from instance method/getter of Foo
    • some probably overridden static method/getter:
      • this.constructor.method()
      • this.constructor.property
    • some probably overridden instance method/getter:
      • this.method()
      • this.property
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • not possible by intention unless using some workaround:
        • Foo.prototype.method.call( this )
        • Object.getOwnPropertyDescriptor( Foo.prototype,"property" ).get.call(this);

Keep in mind that using this isn't working this way when using arrow functions or invoking methods/getters explicitly bound to custom value.

Background

  • When in context of an instance's method or getter
    • this is referring to current instance.
    • super is basically referring to same instance, but somewhat addressing methods and getters written in context of some class current one is extending (by using the prototype of Foo's prototype).
    • definition of instance's class used on creating it is available per this.constructor.
  • When in context of a static method or getter there is no "current instance" by intention and so
    • this is available to refer to the definition of current class directly.
    • super is not referring to some instance either, but to static methods and getters written in context of some class current one is extending.

Conclusion

Try this code:

_x000D_
_x000D_
class A {_x000D_
  constructor( input ) {_x000D_
    this.loose = this.constructor.getResult( input );_x000D_
    this.tight = A.getResult( input );_x000D_
    console.log( this.scaledProperty, Object.getOwnPropertyDescriptor( A.prototype, "scaledProperty" ).get.call( this ) );_x000D_
  }_x000D_
_x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 100;_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return input * this.scale;_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 2;_x000D_
  }_x000D_
}_x000D_
_x000D_
class B extends A {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
    this.tight = B.getResult( input ) + " (of B)";_x000D_
  }_x000D_
  _x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 10000;_x000D_
  }_x000D_
_x000D_
  static get scale() {_x000D_
    return 4;_x000D_
  }_x000D_
}_x000D_
_x000D_
class C extends B {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 5;_x000D_
  }_x000D_
}_x000D_
_x000D_
class D extends C {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return super.getResult( input ) + " (overridden)";_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 10;_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
let instanceA = new A( 4 );_x000D_
console.log( "A.loose", instanceA.loose );_x000D_
console.log( "A.tight", instanceA.tight );_x000D_
_x000D_
let instanceB = new B( 4 );_x000D_
console.log( "B.loose", instanceB.loose );_x000D_
console.log( "B.tight", instanceB.tight );_x000D_
_x000D_
let instanceC = new C( 4 );_x000D_
console.log( "C.loose", instanceC.loose );_x000D_
console.log( "C.tight", instanceC.tight );_x000D_
_x000D_
let instanceD = new D( 4 );_x000D_
console.log( "D.loose", instanceD.loose );_x000D_
console.log( "D.tight", instanceD.tight );
_x000D_
_x000D_
_x000D_

Fastest way to remove first char in a String

You could profile it, if you really cared. Write a loop of many iterations and see what happens. Chances are, however, that this is not the bottleneck in your application, and TrimStart seems the most semantically correct. Strive to write code readably before optimizing.

What is a superfast way to read large files line-by-line in VBA?

With that code you load the file in memory (as a big string) and then you read that string line by line.

By using Mid$() and InStr() you actually read the "file" twice but since it's in memory, there is no problem.
I don't know if VB's String has a length limit (probably not) but if the text files are hundreds of megabyte in size it's likely to see a performance drop, due to virtual memory usage.

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

Uninstall homebrew:

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

Then reinstall

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

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

How to get folder path for ClickOnce application

I'm using Assembly.GetExecutingAssembly().Location to get the path to a ClickOnce deployed application in .Net 4.5.1.

However, you shouldn't write to any folder where your application is deployed to ever, regardless of deployment method (xcopy, ClickOnce, InstallShield, anything) because those are usually read only for applications, especially in newer Windows versions and server environments.

An app must always write to the folders reserved for such purposes. You can get the folders you need starting from Environment.SpecialFolder Enumeration. The MSDN page explains what each folder is for: http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx

I.e. for data, logs and other files one can use ApplicationData (roaming), LocalApplicationData (local) or CommonApplicationData. For temporary files use Path.GetTempPath or Path.GetTempFileName.

The above work on servers and desktops too.

EDIT: Assembly.GetExecutingAssembly() is called in main executable.

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

I ran into this myself when I wanted to make a thor command under Windows.

To avoid having that message output everytime I ran my thor application I temporarily muted warnings while loading thor:

begin
  original_verbose = $VERBOSE
  $VERBOSE = nil
  require "thor"
ensure
  $VERBOSE = original_verbose
end

That saved me from having to edit third party source files.

Why does Eclipse complain about @Override on interface methods?

Using the @Override annotation on methods that implement those declared by an interface is only valid from Java 6 onward. It's an error in Java 5.

Make sure that your IDE projects are setup to use a Java 6 JRE, and that the "source compatibility" is set to 1.6 or greater:

  1. Open the Window > Preferences dialog
  2. Browse to Java > Compiler.
  3. There, set the "Compiler compliance level" to 1.6.

Remember that Eclipse can override these global settings for a specific project, so check those too.


Update:

The error under Java 5 isn't just with Eclipse; using javac directly from the command line will give you the same error. It is not valid Java 5 source code.

However, you can specify the -target 1.5 option to JDK 6's javac, which will produce a Java 5 version class file from the Java 6 source code.

How to add jQuery code into HTML Page

Before the closing body tag add this (reference to jQuery library). Other hosted libraries can be found here

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

And this

<script>
  //paste your code here
</script>

It should look something like this

<body>
 ........
 ........
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script> Your code </script>
</body>

Retrieving Dictionary Value Best Practices

TryGetValue is slightly faster, because FindEntry will only be called once.

How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

FYI: It's not actually catching an error.

It's calling:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

How to remove the character at a given index from a string in C?

Try this :

void removeChar(char *str, char garbage) {

    char *src, *dst;
    for (src = dst = str; *src != '\0'; src++) {
        *dst = *src;
        if (*dst != garbage) dst++;
    }
    *dst = '\0';
}

Test program:

int main(void) {
    char* str = malloc(strlen("abcdef")+1);
    strcpy(str, "abcdef");
    removeChar(str, 'b');
    printf("%s", str);
    free(str);
    return 0;
}

Result:

>>acdef

HTML image not showing in Gmail

Google only allows images which are coming from trusted source .

So I solved this issue by hosting my images in google drive and using its url as source for my images.

Example: with: http://drive.google.com/uc?export=view&id=FILEID'>

to form URL please refer here.

Convert from enum ordinal to enum type

You could use a static lookup table:

public enum Suit {
  spades, hearts, diamonds, clubs;

  private static final Map<Integer, Suit> lookup = new HashMap<Integer, Suit>();

  static{
    int ordinal = 0;
    for (Suit suit : EnumSet.allOf(Suit.class)) {
      lookup.put(ordinal, suit);
      ordinal+= 1;
    }
  }

  public Suit fromOrdinal(int ordinal) {
    return lookup.get(ordinal);
  }
}

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

As others have said this can be caused when you've not installed an app that is listed in INSTALLED_APPS.

In my case, manage.py was attempting to log the exception, which led to an attempt to render it which failed due to the app not being initialized yet. By commenting out the except clause in manage.py the exception was displayed without special rendering, avoiding the confusing error.

# Temporarily commenting out the log statement.
#try:
    execute_from_command_line(sys.argv)
#except Exception as e:
#    log.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
#    raise e

How to parse a JSON Input stream

I would suggest you have to use a Reader to convert your InputStream in.

BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); 
StringBuilder responseStrBuilder = new StringBuilder();

String inputStr;
while ((inputStr = streamReader.readLine()) != null)
    responseStrBuilder.append(inputStr);
new JSONObject(responseStrBuilder.toString());

I tried in.toString() but it returns:

getClass().getName() + '@' + Integer.toHexString(hashCode())

(like documentation says it derives to toString from Object)

Right query to get the current number of connections in a PostgreSQL DB

Number of TCP connections will help you. Remember that it is not for a particular database

netstat -a -n | find /c "127.0.0.1:13306"

Pretty-print an entire Pandas Series / DataFrame

If you are using Ipython Notebook (Jupyter). You can use HTML

from IPython.core.display import HTML
display(HTML(df.to_html()))

Invalid default value for 'dateAdded'

I have mysql version 5.6.27 on my LEMP and CURRENT_TIMESTAMP as default value works fine.

Boolean vs tinyint(1) for boolean values in MySQL

My experience when using Dapper to connect to MySQL is that it does matter. I changed a non nullable bit(1) to a nullable tinyint(1) by using the following script:

ALTER TABLE TableName MODIFY Setting BOOLEAN null;

Then Dapper started throwing Exceptions. I tried to look at the difference before and after the script. And noticed the bit(1) had changed to tinyint(1).

I then ran:

ALTER TABLE TableName CHANGE COLUMN Setting Setting BIT(1) NULL DEFAULT NULL;

Which solved the problem.

WPF MVVM: How to close a window

I also had to deal with this problem, so here my solution. It works great for me.

1. Create class DelegateCommand

    public class DelegateCommand<T> : ICommand
{
    private Predicate<T> _canExecuteMethod;
    private readonly Action<T> _executeMethod;
    public event EventHandler CanExecuteChanged;

    public DelegateCommand(Action<T> executeMethod) : this(executeMethod, null)
    {
    }
    public DelegateCommand(Action<T> executeMethod, Predicate<T> canExecuteMethod)
    {
        this._canExecuteMethod = canExecuteMethod;
        this._executeMethod = executeMethod ?? throw new ArgumentNullException(nameof(executeMethod), "Command is not specified."); 
    }


    public void RaiseCanExecuteChanged()
    {
        if (this.CanExecuteChanged != null)
            CanExecuteChanged(this, null);
    }
    public bool CanExecute(object parameter)
    {
        return _canExecuteMethod == null || _canExecuteMethod((T)parameter) == true;
    }

    public void Execute(object parameter)
    {
        _executeMethod((T)parameter);
    }
}

2. Define your command

        public DelegateCommand<Window> CloseWindowCommand { get; private set; }


    public MyViewModel()//ctor of your viewmodel
    {
        //do something

        CloseWindowCommand = new DelegateCommand<Window>(CloseWindow);


    }
        public void CloseWindow(Window win) // this method is also in your viewmodel
    {
        //do something
        win?.Close();
    }

3. Bind your command in the view

public MyView(Window win) //ctor of your view, window as parameter
    {
        InitializeComponent();
        MyButton.CommandParameter = win;
        MyButton.Command = ((MyViewModel)this.DataContext).CloseWindowCommand;
    }

4. And now the window

  Window win = new Window()
        {
            Title = "My Window",
            Height = 800,
            Width = 800,
            WindowStartupLocation = WindowStartupLocation.CenterScreen,

        };
        win.Content = new MyView(win);
        win.ShowDialog();

so thats it, you can also bind the command in the xaml file and find the window with FindAncestor and bind it to the command parameter.

gitignore all files of extension in directory

To ignore untracked files just go to .git/info/exclude. Exclude is a file with a list of ignored extensions or files.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

How to read input with multiple lines in Java

Use BufferedReader, you can make it read from standard input like this:

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line;

while ((line = stdin.readLine()) != null && line.length()!= 0) {
    String[] input = line.split(" ");
    if (input.length == 2) {
        System.out.println(calculateAnswer(input[0], input[1]));
    }
}

Xcode doesn't see my iOS device but iTunes does

In my case I did next steps

  1. Quit XCode
  2. Disconnect device
  3. In your terminal sudo launchctl stop com.apple.usbmuxd
  4. Relaunch Xcode
  5. Connect device

How to configure PostgreSQL to accept all incoming connections

0.0.0.0/0 for all IPv4 addresses

::0/0 for all IPv6 addresses

all to match any IP address

samehost to match any of the server's own IP addresses

samenet to match any address in any subnet that the server is directly connected to.

e.g.

host    all             all             0.0.0.0/0            md5

How to do a PUT request with curl?

I am late to this thread, but I too had a similar requirement. Since my script was constructing the request for curl dynamically, I wanted a similar structure of the command across GET, POST and PUT.

Here is what works for me

For PUT request:

curl --request PUT --url http://localhost:8080/put --header 'content-type: application/x-www-form-urlencoded' --data 'bar=baz&foo=foo1'

For POST request:

curl --request POST --url http://localhost:8080/post --header 'content-type: application/x-www-form-urlencoded' --data 'bar=baz&foo=foo1'

For GET request:

curl --request GET --url 'http://localhost:8080/get?foo=bar&foz=baz'

showDialog deprecated. What's the alternative?

This code worked for me. Easy fix but probably not a preferred way.

public void onClick (View v) {
    createdDialog(0).show(); // Instead of showDialog(0);
}

protected Dialog createdDialog(int id) {
    // Your code
}

Open web in new tab Selenium + Python

The other solutions do not work for chrome driver v83.

Instead, it works as follows, suppose there is only 1 opening tab:

driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
driver.get("https://www.example.com")

If there are already more than 1 opening tabs, you should first get the index of the last newly-created tab and switch to the tab before calling the url (Credit to tylerl) :

driver.execute_script("window.open('');")
driver.switch_to.window(len(driver.window_handles)-1)
driver.get("https://www.example.com")

Compiling C++11 with g++

If you want to keep the GNU compiler extensions, use -std=gnu++0x rather than -std=c++0x. Here's a quote from the man page:

The compiler can accept several base standards, such as c89 or c++98, and GNU dialects of those standards, such as gnu89 or gnu++98. By specifying a base standard, the compiler will accept all programs following that standard and those using GNU extensions that do not contradict it. For example, -std=c89 turns off certain features of GCC that are incompatible with ISO C90, such as the "asm" and "typeof" keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a "?:" expression. On the other hand, by specifying a GNU dialect of a standard, all features the compiler support are enabled, even when those features change the meaning of the base standard and some strict-conforming programs may be rejected. The particular standard is used by -pedantic to identify which features are GNU extensions given that version of the standard. For example-std=gnu89 -pedantic would warn about C++ style // comments, while -std=gnu99 -pedantic would not.

Tracking changes in Windows registry

I concur with Franci, all Sysinternals utilities are worth taking a look (Autoruns is a must too), and Process Monitor, which replaces the good old Filemon and Regmon is precious.

Beside the usage you want, it is very useful to see why a process fails (like trying to access a file or a registry key that doesn't exist), etc.

How to disable text selection highlighting

Though this pseudo-element was in drafts of CSS Selectors Level 3, it was removed during the Candidate Recommendation phase, as it appeared that its behavior was under-specified, especially with nested elements, and interoperability wasn't achieved.

It's being discussed in How ::selection works on nested elements.

Despite it is being implemented in browsers, you can make an illusion of text not being selected by using the same color and background color on selection as of the tab design (in your case).

Normal CSS Design

p { color: white;  background: black; }

On selection

p::-moz-selection { color: white;  background: black; }
p::selection      { color: white;  background: black; }

Disallowing users to select the text will raise usability issues.

How to get a JavaScript object's class?

To get the "pseudo class", you can get the constructor function, by

obj.constructor

assuming the constructor is set correctly when you do the inheritance -- which is by something like:

Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;

and these two lines, together with:

var woofie = new Dog()

will make woofie.constructor point to Dog. Note that Dog is a constructor function, and is a Function object. But you can do if (woofie.constructor === Dog) { ... }.

If you want to get the class name as a string, I found the following working well:

http://blog.magnetiq.com/post/514962277/finding-out-class-names-of-javascript-objects

function getObjectClass(obj) {
    if (obj && obj.constructor && obj.constructor.toString) {
        var arr = obj.constructor.toString().match(
            /function\s*(\w+)/);

        if (arr && arr.length == 2) {
            return arr[1];
        }
    }

    return undefined;
}

It gets to the constructor function, converts it to string, and extracts the name of the constructor function.

Note that obj.constructor.name could have worked well, but it is not standard. It is on Chrome and Firefox, but not on IE, including IE 9 or IE 10 RTM.

How to access html form input from asp.net code behind

Simplest way IMO is to include an ID and runat server tag on all your elements.

<div id="MYDIV" runat="server" />

Since it sounds like these are dynamically inserted controls, you might appreciate FindControl().

How to increment a JavaScript variable using a button press event

<script type="text/javascript">
var i=0;

function increase()
{
    i++;
    return false;
}</script><input type="button" onclick="increase();">

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Convert LocalDateTime to LocalDateTime in UTC

There is an even simpler way

LocalDateTime.now(Clock.systemUTC())

How to use environment variables in docker compose

The DOCKER solution:

It looks like docker-compose 1.5+ has enabled variables substitution: https://github.com/docker/compose/releases

The latest Docker Compose allows you to access environment variables from your compose file. So you can source your environment variables, then run Compose like so:

set -a
source .my-env
docker-compose up -d

Then you can reference the variables in docker-compose.yml using ${VARIABLE}, like so:

db:
  image: "postgres:${POSTGRES_VERSION}"

And here is more info from the docs, taken here: https://docs.docker.com/compose/compose-file/#variable-substitution

When you run docker-compose up with this configuration, Compose looks for the POSTGRES_VERSION environment variable in the shell and substitutes its value in. For this example, Compose resolves the image to postgres:9.3 before running the configuration.

If an environment variable is not set, Compose substitutes with an empty string. In the example above, if POSTGRES_VERSION is not set, the value for the image option is postgres:.

Both $VARIABLE and ${VARIABLE} syntax are supported. Extended shell-style features, such as ${VARIABLE-default} and ${VARIABLE/foo/bar}, are not supported.

If you need to put a literal dollar sign in a configuration value, use a double dollar sign ($$).

And I believe this feature was added in this pull request: https://github.com/docker/compose/pull/1765

The BASH solution:

I notice folks have issues with Docker's environment variables support. Instead of dealing with environment variables in Docker, let's go back to basics, like bash! Here is a more flexible method using a bash script and a .env file.

An example .env file:

EXAMPLE_URL=http://example.com
# Note that the variable below is commented out and will not be used:
# EXAMPLE_URL=http://example2.com 
SECRET_KEY=ABDFWEDFSADFWWEFSFSDFM

# You can even define the compose file in an env variable like so:
COMPOSE_CONFIG=my-compose-file.yml
# You can define other compose files, and just comment them out
# when not needed:
# COMPOSE_CONFIG=another-compose-file.yml

then run this bash script in the same directory, which should deploy everything properly:

#!/bin/bash

docker rm -f `docker ps -aq -f name=myproject_*`
set -a
source .env
cat ${COMPOSE_CONFIG} | envsubst | docker-compose -f - -p "myproject" up -d

Just reference your env variables in your compose file with the usual bash syntax (ie ${SECRET_KEY} to insert the SECRET_KEY from the .env file).

Note the COMPOSE_CONFIG is defined in my .env file and used in my bash script, but you can easily just replace {$COMPOSE_CONFIG} with the my-compose-file.yml in the bash script.

Also note that I labeled this deployment by naming all of my containers with the "myproject" prefix. You can use any name you want, but it helps identify your containers so you can easily reference them later. Assuming that your containers are stateless, as they should be, this script will quickly remove and redeploy your containers according to your .env file params and your compose YAML file.

Update Since this answer seems pretty popular, I wrote a blog post that describes my Docker deployment workflow in more depth: http://lukeswart.net/2016/03/lets-deploy-part-1/ This might be helpful when you add more complexity to a deployment configuration, like nginx configs, LetsEncrypt certs, and linked containers.

Open File Dialog, One Filter for Multiple Excel Extensions?

If you want to merge the filters (eg. CSV and Excel files), use this formula:

OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";

Or if you want to see XML or PDF files in one time use this:

of.Filter = @" XML or PDF |*.xml;*.pdf";

How to start new activity on button click

Try this simple method.

startActivity(new Intent(MainActivity.this, SecondActivity.class));

create unique id with javascript

put in your namespace an instance similar to the following one

var myns = {/*.....*/};
myns.uid = new function () {
    var u = 0;
    this.toString = function () {
        return 'myID_' + u++;
    };
};
console.dir([myns.uid, myns.uid, myns.uid]);

Check if starting characters of a string are alphabetical in T-SQL

select * from my_table where my_field Like '[a-z][a-z]%'

PHP page redirect

Using a javascript as a failsafe will ensure the user is redirected (even if the headers have already been sent). Here you go:

// $url should be an absolute url
function redirect($url){
    if (headers_sent()){
      die('<script type="text/javascript">window.location=\''.$url.'\';</script??>');
    }else{
      header('Location: ' . $url);
      die();
    }    
}

If you need to properly handle relative paths, I've written a function for that (but that's outside the scope of the question).

regex match any single character (one character only)

Simple answer

If you want to match single character, put it inside those brackets [ ]

Examples

  • match + ...... [+] or +
  • match a ...... a
  • match & ...... &

...and so on. You can check your regular expresion online on this site: https://regex101.com/

(updated based on comment)

Output of git branch in tree like fashion

It's not quite what you asked for, but

git log --graph --simplify-by-decoration --pretty=format:'%d' --all

does a pretty good job. It shows tags and remote branches as well. This may not be desirable for everyone, but I find it useful. --simplifiy-by-decoration is the big trick here for limiting the refs shown.

I use a similar command to view my log. I've been able to completely replace my gitk usage with it:

git log --graph --oneline --decorate --all

I use it by including these aliases in my ~/.gitconfig file:

[alias]
    l = log --graph --oneline --decorate
    ll = log --graph --oneline --decorate --branches --tags
    lll = log --graph --oneline --decorate --all

Edit: Updated suggested log command/aliases to use simpler option flags.

Notification bar icon turns white in Android 5 Lollipop

This is the code Android uses to display notification icons:

// android_frameworks_base/packages/SystemUI/src/com/android/systemui/
//   statusbar/BaseStatusBar.java

if (entry.targetSdk >= Build.VERSION_CODES.LOLLIPOP) {
    entry.icon.setColorFilter(mContext.getResources().getColor(android.R.color.white));
} else {
    entry.icon.setColorFilter(null);
}

So you need to set the target sdk version to something <21 and the icons will stay colored. This is an ugly workaround but it does what it is expected to do. Anyway, I really suggest following Google's Design Guidelines: "Notification icons must be entirely white."

Here is how you can implement it:

If you are using Gradle/Android Studio to build your apps, use build.gradle:

defaultConfig {
    targetSdkVersion 20
}

Otherwise (Eclipse etc) use AndroidManifest.xml:

<uses-sdk android:minSdkVersion="..." android:targetSdkVersion="20" />

Count the frequency that a value occurs in a dataframe column

@metatoaster has already pointed this out. Go for Counter. It's blazing fast.

import pandas as pd
from collections import Counter
import timeit
import numpy as np

df = pd.DataFrame(np.random.randint(1, 10000, (100, 2)), columns=["NumA", "NumB"])

Timers

%timeit -n 10000 df['NumA'].value_counts()
# 10000 loops, best of 3: 715 µs per loop

%timeit -n 10000 df['NumA'].value_counts().to_dict()
# 10000 loops, best of 3: 796 µs per loop

%timeit -n 10000 Counter(df['NumA'])
# 10000 loops, best of 3: 74 µs per loop

%timeit -n 10000 df.groupby(['NumA']).count()
# 10000 loops, best of 3: 1.29 ms per loop

Cheers!

What is the difference between an Instance and an Object?

Java is an object-oriented programming language (OOP). This means, that everything in Java, except of the primitive types is an object.

Now, Java objects are similar to real-world objects. For example we can create a car object in Java, which will have properties like current speed and color; and behavior like: accelerate and park.

That's Object.

enter image description here

Instance, on the other side, is a uniquely initialized copy of that object that looks like Car car = new Car().

Check it out to learn more about Java classes and object

Notification not showing in Oreo

private void addNotification() {
                NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("Notifications Example")
                .setContentText("This is a test notification");
                Intent notificationIntent = new Intent(this, MainActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
                builder.setContentIntent(contentIntent);
                // Add as notification
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
                {
                NotificationChannel nChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
                nChannel.enableLights(true);
                assert manager != null;
                builder.setChannelId(NOTIFICATION_CHANNEL_ID);
                manager.createNotificationChannel(nChannel);
                }
                assert manager != null;
                manager.notify(0, builder.build());
    }

How do I select an element that has a certain class?

The element.class selector is for styling situations such as this:

<span class="large"> </span>
<p class="large"> </p>

.large {
    font-size:150%; font-weight:bold;
}

p.large {
    color:blue;
}

Both your span and p will be assigned the font-size and font-weight from .large, but the color blue will only be assigned to p.

As others have pointed out, what you're working with is descendant selectors.

How to view Plugin Manager in Notepad++

I changed the plugin folder name. Restart Notepad ++ It works now, a

Array of Matrices in MATLAB

I was doing some volume rendering in octave (matlab clone) and building my 3D arrays (ie an array of 2d slices) using

buffer=zeros(1,512*512*512,"uint16");
vol=reshape(buffer,512,512,512);

Memory consumption seemed to be efficient. (can't say the same for the subsequent speed of computations :^)

Calling an executable program using awk

#!/usr/bin/awk -f

BEGIN {
    command = "ls -lh"

    command |getline
}

Runs "ls -lh" in an awk script

what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?

Given this example url:

http://www.example.com/some-dir/yourpage.php?q=bogus&n=10

$_SERVER['REQUEST_URI'] will give you:

/some-dir/yourpage.php?q=bogus&n=10

Whereas $_GET['q'] will give you:

bogus

In other words, $_SERVER['REQUEST_URI'] will hold the full request path including the querystring. And $_GET['q'] will give you the value of parameter q in the querystring.

How to find the mysql data directory from command line in windows

if you want to find datadir in linux or windows you can do following command

mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"'

if you are interested to find datadir you can use grep & awk command

mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"' | grep 'datadir' | awk '{print $2}'

Get each line from textarea

$content = $_POST['content_name'];
$lines = explode("\n", $content);

foreach( $lines as $index => $line )
{
    $lines[$index] = $line . '<br/>';
}

// $lines contains your lines

How do I clear the std::queue efficiently?

I'd rather not rely on swap() or setting the queue to a newly created queue object, because the queue elements are not properly destroyed. Calling pop()invokes the destructor for the respective element object. This might not be an issue in <int> queues but might very well have side effects on queues containing objects.

Therefore a loop with while(!queue.empty()) queue.pop();seems unfortunately to be the most efficient solution at least for queues containing objects if you want to prevent possible side effects.

Java Long primitive type maximum limit

Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

It will start from -9,223,372,036,854,775,808

Long.MIN_VALUE.

How to crop an image using C#?

Assuming you mean that you want to take an image file (JPEG, BMP, TIFF, etc) and crop it then save it out as a smaller image file, I suggest using a third party tool that has a .NET API. Here are a few of the popular ones that I like:

LeadTools
Accusoft Pegasus Snowbound Imaging SDK

How to create a backup of a single table in a postgres database?

pg_dump -h localhost -p 5432 -U postgres -d mydb -t my_table > backup.sql

You can take the backup of a single table but I would suggest to take the backup of whole database and then restore whichever table you need. It is always good to have backup of whole database.

9 ways to use pg_dump

how to check if string value is in the Enum list?

I know this is an old thread, but here's a slightly different approach using attributes on the Enumerates and then a helper class to find the enumerate that matches.

This way you could have multiple mappings on a single enumerate.

public enum Age
{
    [Metadata("Value", "New_Born")]
    [Metadata("Value", "NewBorn")]
    New_Born = 1,
    [Metadata("Value", "Toddler")]
    Toddler = 2,
    [Metadata("Value", "Preschool")]
    Preschool = 4,
    [Metadata("Value", "Kindergarten")]
    Kindergarten = 8
}

With my helper class like this

public static class MetadataHelper
{
    public static string GetFirstValueFromMetaDataAttribute<T>(this T value, string metaDataDescription)
    {
        return GetValueFromMetaDataAttribute(value, metaDataDescription).FirstOrDefault();
    }

    private static IEnumerable<string> GetValueFromMetaDataAttribute<T>(T value, string metaDataDescription)
    {
        var attribs =
            value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (MetadataAttribute), true);
        return attribs.Any()
            ? (from p in (MetadataAttribute[]) attribs
                where p.Description.ToLower() == metaDataDescription.ToLower()
                select p.MetaData).ToList()
            : new List<string>();
    }

    public static List<T> GetEnumeratesByMetaData<T>(string metadataDescription, string value)
    {
        return
            typeof (T).GetEnumValues().Cast<T>().Where(
                enumerate =>
                    GetValueFromMetaDataAttribute(enumerate, metadataDescription).Any(
                        p => p.ToLower() == value.ToLower())).ToList();
    }

    public static List<T> GetNotEnumeratesByMetaData<T>(string metadataDescription, string value)
    {
        return
            typeof (T).GetEnumValues().Cast<T>().Where(
                enumerate =>
                    GetValueFromMetaDataAttribute(enumerate, metadataDescription).All(
                        p => p.ToLower() != value.ToLower())).ToList();
    }

}

you can then do something like

var enumerates = MetadataHelper.GetEnumeratesByMetaData<Age>("Value", "New_Born");

And for completeness here is the attribute:

 [AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public class MetadataAttribute : Attribute
{
    public MetadataAttribute(string description, string metaData = "")
    {
        Description = description;
        MetaData = metaData;
    }

    public string Description { get; set; }
    public string MetaData { get; set; }
}

html - table row like a link

Thanks for this. You can change the hover icon by assigning a CSS class to the row like:

<tr class="pointer" onclick="document.location = 'links.html';">

and the CSS looks like:

<style>
    .pointer { cursor: pointer; }
</style>

Annotation @Transactional. How to rollback?

Just throw any RuntimeException from a method marked as @Transactional.

By default all RuntimeExceptions rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor() and noRollbackFor() annotation parameters:

@Transactional(rollbackFor=Exception.class)

This will rollback transaction after throwing any exception.

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(R.id.textView1);
   holder.textAddress = (TextView) row.findViewById(R.id.textView2);
   holder.textLocation = (TextView) row.findViewById(R.id.textView3);
   holder.btnEdit = (Button) row.findViewById(R.id.button1);
   holder.btnDelete = (Button) row.findViewById(R.id.button2);
   row.setTag(holder);
  } else {
   holder = (UserHolder) row.getTag();
  }
  User user = data.get(position);
  holder.textName.setText(user.getName());
  holder.textAddress.setText(user.getAddress());
  holder.textLocation.setText(user.getLocation());
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  return row;

 }

 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;
 }
}

Hey Please have a look here-

I have same answer here on my blog ..

How to show Page Loading div until the page has finished loading?

Create a <div> element that contains your loading message, give the <div> an ID, and then when your content has finished loading, hide the <div>:

$("#myElement").css("display", "none");

...or in plain JavaScript:

document.getElementById("myElement").style.display = "none";

Adding a new array element to a JSON object

For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.

'<a href="#" cartBtn pr_id='+e.id+' pr_name_en="'+e.nameEn+'" pr_price="'+e.price+'" pr_image="'+e.image+'" class="btn btn-primary"><i class="fa fa-shopping-cart"></i>Add to cart</a>'

var productArray=[];


$(document).on('click','[cartBtn]',function(e){
  e.preventDefault();
  $(this).html('<i class="fa fa-check"></i>Added to cart');
  console.log('Item added ');
  var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};


  if(localStorage.getObj('product')!==null){
    productArray=localStorage.getObj('product');
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }
  else{
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }


});

Storage.prototype.setObj = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObj = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

After adding JSON object to Array result is (in LocalStorage):

[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]

after this action you can easily send data to server as List in Java

Full code example is here

How do I store a simple cart using localStorage?

Where are static variables stored in C and C++?

Data declared in a compilation unit will go into the .BSS or the .Data of that files output. Initialised data in BSS, uninitalised in DATA.

The difference between static and global data comes in the inclusion of symbol information in the file. Compilers tend to include the symbol information but only mark the global information as such.

The linker respects this information. The symbol information for the static variables is either discarded or mangled so that static variables can still be referenced in some way (with debug or symbol options). In neither case can the compilation units gets affected as the linker resolves local references first.

How to set locale in DatePipe in Angular 2?

I've had a look in date_pipe.ts and it has two bits of info which are of interest. near the top are the following two lines:

// TODO: move to a global configurable location along with other i18n components.
var defaultLocale: string = 'en-US';

Near the bottom is this line:

return DateFormatter.format(value, defaultLocale, pattern);

This suggests to me that the date pipe is currently hard-coded to be 'en-US'.

Please enlighten me if I am wrong.

PLS-00103: Encountered the symbol "CREATE"

Run package declaration and body separately.

PySpark: multiple conditions in when clause

It should be:

$when(((tdata.Age == "" ) & (tdata.Survived == "0")), mean_age_0)

Java collections maintaining insertion order

When you use a HashSet (or a HashMap) data are stored in "buckets" based on the hash of your object. This way your data is easier to access because you don't have to look for this particular data in the whole Set, you just have to look in the right bucket.

This way you can increase performances on specific points.

Each Collection implementation have its particularity to make it better to use in a certain condition. Each of those particularities have a cost. So if you don't really need it (for example the insertion order) you better use an implementation which doesn't offer it and fits better to your requirements.

How to concatenate two MP4 files using FFmpeg?

Merging all mp4 files from current directory

I personnaly like not creating external file that I have to delete afterwards, so my solution was following which includes files numbering listing (like file_1_name, file_2_name, file_10_name, file_20_name, file_100_name, ...)

#!/bin/bash
filesList=""
for file in $(ls -1v *.mp4);do #lists even numbered file
    filesList="${filesList}${file}|"
done
filesList=${filesList%?} # removes trailing pipe
ffmpeg -i "concat:$filesList" -c copy $(date +%Y%m%d_%H%M%S)_merged.mp4

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

if cordova app copy a valid png file to

resources\android\icon.png

and then run

ionic resources --icon

textarea's rows, and cols attribute in CSS

I don't think you can. I always go with height and width.

textarea{
width:400px;
height:100px;
}

the nice thing about doing it the CSS way is that you can completely style it up. Now you can add things like:

textarea{
width:400px;
height:100px;
border:1px solid #000000;
background-color:#CCCCCC;
}

How to change python version in anaconda spyder

If you want to keep python 3, you can follow these directions to create a python 2.7 environment, called py27.

Then you just need to activate py27:

$ conda activate py27

Then you can install spyder on this environment, e.g.:

$ conda install spyder

Then you can start spyder from the command line or navigate to 2.7 version of spyder.exe below the envs directory (e.g. C:\ProgramData\Anaconda3\envs\py27\Scripts)

Python import csv to list

If you are sure there are no commas in your input, other than to separate the category, you can read the file line by line and split on ,, then push the result to List

That said, it looks like you are looking at a CSV file, so you might consider using the modules for it

Most efficient way to find mode in numpy array

Check scipy.stats.mode() (inspired by @tom10's comment):

import numpy as np
from scipy import stats

a = np.array([[1, 3, 4, 2, 2, 7],
              [5, 2, 2, 1, 4, 1],
              [3, 3, 2, 2, 1, 1]])

m = stats.mode(a)
print(m)

Output:

ModeResult(mode=array([[1, 3, 2, 2, 1, 1]]), count=array([[1, 2, 2, 2, 1, 2]]))

As you can see, it returns both the mode as well as the counts. You can select the modes directly via m[0]:

print(m[0])

Output:

[[1 3 2 2 1 1]]

jquery stop child triggering parent event

Better way by using on() with chaining like,

$(document).ready(function(){
    $(".header").on('click',function(){
        $(this).children(".children").toggle();
    }).on('click','a',function(e) {
        e.stopPropagation();
   });
});

Codeigniter unset session

Instead of use set_userdata you should use set_flashdata.

According to CI user guide:

CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: "record 2 deleted").

http://ellislab.com/codeigniter/user-guide/libraries/sessions.html

How to call a function, PostgreSQL

if your function does not want to return anything you should declare it to "return void" and then you can call it like this "perform functionName(parameter...);"

How to apply !important using .css()?

You can achieve this in two ways:

$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");

Is there an easy way to convert Android Application to IPad, IPhone

In the box is working on being able to convert android projects to iOS

https://code.google.com/p/in-the-box/

How to convert string values from a dictionary, into int/float datatypes?

for sub in the_list:
    for key in sub:
        sub[key] = int(sub[key])

Gives it a casting as an int instead of as a string.

Get exit code for command in bash/ksh

There are several things wrong with your script.

Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).

It's good practice to surround your variable references with curly braces, too. Your code might look like:

#!/bin/sh
command="/bin/date -u"          #...Example Only

safeRunCommand() {
   cmnd="$@"                    #...insure whitespace passed and preserved
   $cmnd
   ERROR_CODE=$?                #...so we have it for the command we want
   if [ ${ERROR_CODE} != 0 ]; then
      printf "Error when executing command: '${command}'\n"
      exit ${ERROR_CODE}        #...consider 'return()' here
   fi
}

safeRunCommand $command
command="cp"
safeRunCommand $command

mailto link with HTML body

No. This is not possible at all.

WPF What is the correct way of using SVG files as icons in WPF

Use the SvgImage or the SvgImageConverter extensions, the SvgImageConverter supports binding. See the following link for samples demonstrating both extensions.

https://github.com/ElinamLLC/SharpVectors/tree/master/TutorialSamples/ControlSamplesWpf

Table with fixed header and fixed column on pure css

_x000D_
_x000D_
/* Use overflow:scroll on your container to enable scrolling: */_x000D_
_x000D_
div {_x000D_
  max-width: 400px;_x000D_
  max-height: 150px;_x000D_
  overflow: scroll;_x000D_
}_x000D_
_x000D_
_x000D_
/* Use position: sticky to have it stick to the edge_x000D_
 * and top, right, or left to choose which edge to stick to: */_x000D_
_x000D_
thead th {_x000D_
  position: -webkit-sticky; /* for Safari */_x000D_
  position: sticky;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
tbody th {_x000D_
  position: -webkit-sticky; /* for Safari */_x000D_
  position: sticky;_x000D_
  left: 0;_x000D_
}_x000D_
_x000D_
_x000D_
/* To have the header in the first column stick to the left: */_x000D_
_x000D_
thead th:first-child {_x000D_
  left: 0;_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
_x000D_
/* Just to display it nicely: */_x000D_
_x000D_
thead th {_x000D_
  background: #000;_x000D_
  color: #FFF;_x000D_
}_x000D_
_x000D_
tbody th {_x000D_
  background: #FFF;_x000D_
  border-right: 1px solid #CCC;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
  padding: 0.5em;_x000D_
}
_x000D_
<div>_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th></th>_x000D_
        <th>headheadhead</th>_x000D_
        <th>headheadhead</th>_x000D_
        <th>headheadhead</th>_x000D_
        <th>headheadhead</th>_x000D_
        <th>headheadhead</th>_x000D_
        <th>headheadhead</th>_x000D_
        <th>headheadhead</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <th>head</th>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th>head</th>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th>head</th>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th>head</th>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th>head</th>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th>head</th>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
        <td>body</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

need to fix header footer

Adding a slide effect to bootstrap dropdown

Also it's possible to avoid using JavaScript for drop-down effect, and use CSS3 transition, by adding this small piece of code to your style:

.dropdown .dropdown-menu {
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    -ms-transition: all 0.3s;
    -o-transition: all 0.3s;
    transition: all 0.3s;

    max-height: 0;
    display: block;
    overflow: hidden;
    opacity: 0;
}

.dropdown.open .dropdown-menu { /* For Bootstrap 4, use .dropdown.show instead of .dropdown.open */
    max-height: 300px;
    opacity: 1;
}

The only problem with this way is that you should manually specify max-height. If you set a very big value, your animation will be very quick.

It works like a charm if you know the approximate height of your dropdowns, otherwise you still can use javascript to set a precise max-height value.

Here is small example: DEMO


! There is small bug with padding in this solution, check Jacob Stamm's comment with solution.

What does "O(1) access time" mean?

"Big O notation" is a way to express the speed of algorithms. n is the amount of data the algorithm is working with. O(1) means that, no matter how much data, it will execute in constant time. O(n) means that it is proportional to the amount of data.

Hibernate Criteria for Dates

Why do you use Restrictions.like(...)?

You should use Restrictions.eq(...).

Note you can also use .le, .lt, .ge, .gt on date objects as comparison operators. LIKE operator is not appropriate for this case since LIKE is useful when you want to match results according to partial content of a column. Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.

For example if you have a name column with some people's full name, you can do where name like 'robert %' so that you will return all entries with name starting with 'robert ' (% can replace any character).

In your case you know the full content of the date you're trying to match so you shouldn't use LIKE but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...).

Your date object you got with the code:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);

This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.

This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".

If you want to retrieve all entries of your database from a given day, you will have to use the following code:

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
    String myDate = "17-04-2011";
    // Create date 17-04-2011 - 00h00
    Date minDate = formatter.parse(myDate);
    // Create date 18-04-2011 - 00h00 
    // -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
    Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
    Conjunction and = Restrictions.conjunction();
    // The order date must be >= 17-04-2011 - 00h00
    and.add( Restrictions.ge("orderDate", minDate) );
    // And the order date must be < 18-04-2011 - 00h00
    and.add( Restrictions.lt("orderDate", maxDate) ); 

How can I determine whether a specific file is open in Windows?

There is a program "OpenFiles", seems to be part of windows 7. Seems that it can do what you want. It can list files opened by remote users (through file share) and, after calling "openfiles /Local on" and a system restart, it should be able to show files opened locally. The latter is said to have performance penalties.

How does DHT in torrents work?

With trackerless/DHT torrents, peer IP addresses are stored in the DHT using the BitTorrent infohash as the key. Since all a tracker does, basically, is respond to put/get requests, this functionality corresponds exactly to the interface that a DHT (distributed hash table) provides: it allows you to look up and store IP addresses in the DHT by infohash.

So a "get" request would look up a BT infohash and return a set of IP addresses. A "put" stores an IP address for a given infohash. This corresponds to the "announce" request you would otherwise make to the tracker to receive a dictionary of peer IP addresses.

In a DHT, peers are randomly assigned to store values belonging to a small fraction of the key space; the hashing ensures that keys are distributed randomly across participating peers. The DHT protocol (Kademlia for BitTorrent) ensures that put/get requests are routed efficiently to the peers responsible for maintaining a given key's IP address lists.

How do I join two lines in vi?

Press Shift + 4 ("$") on the first line, then Shift + j ("J").

And if you want help, go into vi, and then press F1.

How do I pass parameters into a PHP script through a webpage?

$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter

If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

<?php
if ($_GET) {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
} else {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
?>

To call from command line chmod 755 /var/www/webroot/index.php and use

/usr/bin/php /var/www/webroot/index.php arg1 arg2

To call from the browser, use

http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2

Why does using an Underscore character in a LIKE filter give me all the results?

As you want to specifically search for a wildcard character you need to escape that

This is done by adding the ESCAPE clause to your LIKE expression. The character that is specified with the ESCAPE clause will "invalidate" the following wildcard character.

You can use any character you like (just not a wildcard character). Most people use a \ because that is what many programming languages also use

So your query would result in:

select * 
from Manager
where managerid LIKE '\_%' escape '\'
and managername like '%\_%' escape '\';

But you can just as well use any other character:

select * 
from Manager
where managerid LIKE '#_%' escape '#'
and managername like '%#_%' escape '#';

Here is an SQLFiddle example: http://sqlfiddle.com/#!6/63e88/4

Markdown to create pages and table of contents?

You can use DocToc to generate the table of contents from command line with:

doctoc /path/to/file

To make links compatible with anchors generated by Bitbucket, run it with the --bitbucket argument.

How to align the text middle of BUTTON

You can use text-align: center; line-height: 65px;

Demo

CSS

.loginBtn {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
    text-align: center;  <--------- Here
    line-height: 65px;   <--------- Here
}

How to cast an Object to an int

If you mean cast a String to int, use Integer.valueOf("123").

You can't cast most other Objects to int though, because they wont have an int value. E.g. an XmlDocument has no int value.

How to reset the use/password of jenkins on windows?

I created a new user with "admin" and new password on the installation steps. But after sometime, i wanted to sign in again and that password was showing incorrect, so i used the initial password again to login.

The initial password can be found in the below location:-

C:\Program Files(x86)\Jenkins\secrets\initialAdminPassword

try this method

How to see indexes for a database or table in MySQL?

SHOW INDEX FROM mytable FROM mydb;

SHOW INDEX FROM mydb.mytable;

See documentation.

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

When you export you use the compatibility system set to MYSQL40. Worked for me.

Get response from PHP file using AJAX

in your PHP file, when you echo your data use json_encode (http://php.net/manual/en/function.json-encode.php)

e.g.

<?php
//plum or data...
$output = array("data","plum");

echo json_encode($output);

?>

in your javascript code, when your ajax completes the json encoded response data can be turned into an js array like this:

 $.ajax({
                type: "POST",
                url: "process.php",
                data: somedata;
                success function(json_data){
                    var data_array = $.parseJSON(json_data);

                    //access your data like this:
                    var plum_or_whatever = data_array['output'];.
                    //continue from here...
                }
            });

Scroll to bottom of div with Vue.js

I had the same need in my app (with complex nested components structure) and I unfortunately did not succeed to make it work.

Finally I used vue-scrollto that works fine !

Removing path and extension from filename in PowerShell

The command below will store in a variable all the file in your folder, matchting the extension ".txt":

$allfiles=Get-ChildItem -Path C:\temp\*" -Include *.txt
foreach ($file in $allfiles) {
    Write-Host $file
    Write-Host $file.name
    Write-Host $file.basename
}

$file gives the file with path, name and extension: c:\temp\myfile.txt

$file.name gives file name & extension: myfile.txt

$file.basename gives only filename: myfile

jQuery UI dialog positioning

Thanks to some answers above, I experimented and ultimately found that all you need to do is edit the "position" attribute in the Modal Dialog's definition:

position:['middle',20],

JQuery had no problems with the "middle" text for the horizontal "X" value and my dialog popped up in the middle, 20px down from the top.

I heart JQuery.

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put

plt.clf()
plt.cla()
plt.close()

after every plt.show()

Prevent wrapping of span or div

As mentioned you can use:

overflow: scroll;

If you only want the scroll bar to appear when necessary, you can use the "auto" option:

overflow: auto;

I don't think you should be using the "float" property with "overflow", but I'd have to try out your example first.

How to show a confirm message before delete?

var txt;
var r = confirm("Press a button!");
if (r == true) {
   txt = "You pressed OK!";
} else {
   txt = "You pressed Cancel!";
}

_x000D_
_x000D_
var txt;_x000D_
var r = confirm("Press a button!");_x000D_
if (r == true) {_x000D_
    txt = "You pressed OK!";_x000D_
} else {_x000D_
    txt = "You pressed Cancel!";_x000D_
}
_x000D_
_x000D_
_x000D_

Reading value from console, interactively

I recommend using Inquirer, since it provides a collection of common interactive command line user interfaces.

const inquirer = require('inquirer');

const questions = [{
  type: 'input',
  name: 'name',
  message: "What's your name?",
}];

const answers = await inquirer.prompt(questions);
console.log(answers);

Twitter Bootstrap Responsive Background-Image inside Div

Mby bootstrap img-responsive class is you looking for.

What is Inversion of Control?

Inversion of Control is a generic principle, while Dependency Injection realises this principle as a design pattern for object graph construction (i.e. configuration controls how the objects are referencing each other, rather than the object itself controlling how to get the reference to another object).

Looking at Inversion of Control as a design pattern, we need to look at what we are inverting. Dependency Injection inverts control of constructing a graph of objects. If told in layman's term, inversion of control implies change in flow of control in the program. Eg. In traditional standalone app, we have main method, from where the control gets passed to other third party libraries(in case, we have used third party library's function), but through inversion of control control gets transferred from third party library code to our code, as we are taking the service of third party library. But there are other aspects that need to be inverted within a program - e.g. invocation of methods and threads to execute the code.

For those interested in more depth on Inversion of Control a paper has been published outlining a more complete picture of Inversion of Control as a design pattern (OfficeFloor: using office patterns to improve software design http://doi.acm.org/10.1145/2739011.2739013 with a free copy available to download from http://www.officefloor.net/about.html).

What is identified is the following relationship:

Inversion of Control (for methods) = Dependency (state) Injection + Continuation Injection + Thread Injection

Summary of above relationship for Inversion of Control available - http://dzone.com/articles/inversion-of-coupling-control

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

My cause of issue seems very uncommon to me, not sure if anybody else gets the error under same condition, I found the cause by diffing previous commits, here you go :

Via my build.gradle I was using these 2 compiler options, and commenting out this line fixed the issue

//compileJava.options.compilerArgs = ['-Xlint:unchecked','-Xlint:deprecation']

How to make EditText not editable through XML in Android?

I tried to do:

textView.setInputType( InputType.TYPE_NULL );

which should work, but for me it did not.

I finished with this code:

textView.setKeyListener(new NumberKeyListener() {
    public int getInputType() {
        return InputType.TYPE_NULL;
    }

    protected char[] getAcceptedChars() {
        return new char[] {};
    }
});

which works perfectly.

jQuery - replace all instances of a character in a string

RegEx is the way to go in most cases.

In some cases, it may be faster to specify more elements or the specific element to perform the replace on:

$(document).ready(function () {
    $('.myclass').each(function () {
        $('img').each(function () {
            $(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
        })
    })
});

This does the replace once on each string, but it does it using a more specific selector.

Bootstrap change carousel height

Thank you! This post is Very Helpful. You may also want to add

object-fit:cover;

To preserve the aspect ration for different window sizes

.carousel .item {
  height: 500px;
}

.item img {
    position: absolute;
    object-fit:cover;
    top: 0;
    left: 0;
    min-height: 500px;
}

For bootstrap 4 and above replace .item with .carousel-item

.carousel .carousel-item {
  height: 500px;
}

.carousel-item img {
    position: absolute;
    object-fit:cover;
    top: 0;
    left: 0;
    min-height: 500px;
}

How do I run a Java program from the command line on Windows?

As of Java 9, the JDK includes jshell, a Java REPL.

Assuming the JDK 9+ bin directory is correctly added to your path, you will be able to simply:

  1. Run jshell File.javaFile.java being your file of course.
  2. A prompt will open, allowing you to call the main method: jshell> File.main(null).
  3. To close the prompt and end the JVM session, use /exit

Full documentation for JShell can be found here.

PHP Accessing Parent Class Variable

With parent::$bb; you try to retrieve the static constant defined with the value of $bb.

Instead, do:

echo $this->bb;

Note: you don't need to call parent::_construct if B is the only class that calls it. Simply don't declare __construct in B class.

Update and left outer join statements

The Left join in this query is pointless:

UPDATE md SET md.status = '3' 
FROM pd_mounting_details AS md 
LEFT OUTER JOIN pd_order_ecolid AS oe ON md.order_data = oe.id

It would update all rows of pd_mounting_details, whether or not a matching row exists in pd_order_ecolid. If you wanted to only update matching rows, it should be an inner join.

If you want to apply some condition based on the join occurring or not, you need to add a WHERE clause and/or a CASE expression in your SET clause.

Sorting Characters Of A C++ String

You have to include sort function which is in algorithm header file which is a standard template library in c++.

Usage: std::sort(str.begin(), str.end());

#include <iostream>
#include <algorithm>  // this header is required for std::sort to work
int main()
{
    std::string s = "dacb";
    std::sort(s.begin(), s.end());
    std::cout << s << std::endl;

    return 0;
}

OUTPUT:

abcd

Create 3D array using Python

If you insist on everything initializing as empty, you need an extra set of brackets on the inside ([[]] instead of [], since this is "a list containing 1 empty list to be duplicated" as opposed to "a list containing nothing to duplicate"):

distance=[[[[]]*n]*n]*n

Adding backslashes without escaping [Python]

Python treats \ in literal string in a special way.
This is so you can type '\n' to mean newline or '\t' to mean tab
Since '\&' doesn't mean anything special to Python, instead of causing an error, the Python lexical analyser implicitly adds the extra \ for you.

Really it is better to use \\& or r'\&' instead of '\&'

The r here means raw string and means that \ isn't treated specially unless it is right before the quote character at the start of the string.

In the interactive console, Python uses repr to display the result, so that is why you see the double '\'. If you print your string or use len(string) you will see that it is really only the 2 characters

Some examples

>>> 'Here\'s a backslash: \\'
"Here's a backslash: \\"
>>> print 'Here\'s a backslash: \\'
Here's a backslash: \
>>> 'Here\'s a backslash: \\. Here\'s a double quote: ".'
'Here\'s a backslash: \\. Here\'s a double quote: ".'
>>> print 'Here\'s a backslash: \\. Here\'s a double quote: ".'
Here's a backslash: \. Here's a double quote ".

To Clarify the point Peter makes in his comment see this link

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences marked as “(Unicode only)” in the table above fall into the category of unrecognized escapes for non-Unicode string literals.

Java code To convert byte to Hexadecimal

I am posting because none of the existing answers explain why their approaches work, which I think is really important for this problem. In some cases, this causes the proposed solution to appear unnecessarily complicated and subtle. To illustrate I will provide a fairly straightforward approach, but I'll provide a bit more detail to help illustrate why it works.

First off, what are we trying to do? We want to convert a byte value (or an array of bytes) to a string which represents a hexadecimal value in ASCII. So step one is to find out exactly what a byte in Java is:

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

What does this mean? A few things: First and most importantly, it means we are working with 8-bits. So for example we can write the number 2 as 0000 0010. However, since it is two's complement, we write a negative 2 like this: 1111 1110. What is also means is that converting to hex is very straightforward. That is, you simply convert each 4 bit segment directly to hex. Note that to make sense of negative numbers in this scheme you will first need to understand two's complement. If you don't already understand two's complement, you can read an excellent explanation, here: http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html


Converting Two's Complement to Hex In General

Once a number is in two's complement it is dead simple to convert it to hex. In general, converting from binary to hex is very straightforward, and as you will see in the next two examples, you can go directly from two's complement to hex.

Examples

Example 1: Convert 2 to Hex.

1) First convert 2 to binary in two's complement:

2 (base 10) = 0000 0010 (base 2)

2) Now convert binary to hex:

0000 = 0x0 in hex
0010 = 0x2 in hex

therefore 2 = 0000 0010 = 0x02. 

Example 2: Convert -2 (in two's complement) to Hex.

1) First convert -2 to binary in two's complement:

-2 (base 10) = 0000 0010 (direct conversion to binary) 
               1111 1101 (invert bits)
               1111 1110 (add 1)
therefore: -2 = 1111 1110 (in two's complement)

2) Now Convert to Hex:

1111 = 0xF in hex
1110 = 0xE in hex

therefore: -2 = 1111 1110 = 0xFE.


Doing this In Java

Now that we've covered the concept, you'll find we can achieve what we want with some simple masking and shifting. The key thing to understand is that the byte you are trying to convert is already in two's complement. You don't do this conversion yourself. I think this is a major point of confusion on this issue. Take for example the follow byte array:

byte[] bytes = new byte[]{-2,2};

We just manually converted them to hex, above, but how can we do it in Java? Here's how:

Step 1: Create a StringBuffer to hold our computation.

StringBuffer buffer = new StringBuffer();

Step 2: Isolate the higher order bits, convert them to hex, and append them to the buffer

Given the binary number 1111 1110, we can isolate the higher order bits by first shifting them over by 4, and then zeroing out the rest of the number. Logically this is simple, however, the implementation details in Java (and many languages) introduce a wrinkle because of sign extension. Essentially, when you shift a byte value, Java first converts your value to an integer, and then performs sign extension. So while you would expect 1111 1110 >> 4 to be 0000 1111, in reality, in Java it is represented as the two's complement 0xFFFFFFFF!

So returning to our example:

1111 1110 >> 4 (shift right 4) = 1111 1111 1111 1111 1111 1111 1111 1111 (32 bit sign-extended number in two's complement)

We can then isolate the bits with a mask:

1111 1111 1111 1111 1111 1111 1111 1111 & 0xF = 0000 0000 0000 0000 0000 0000 0000 1111
therefore: 1111 = 0xF in hex. 

In Java we can do this all in one shot:

Character.forDigit((bytes[0] >> 4) & 0xF, 16);

The forDigit function just maps the number you pass it onto the set of hexadecimal numbers 0-F.

Step 3: Next we need to isolate the lower order bits. Since the bits we want are already in the correct position, we can just mask them out:

1111 1110 & 0xF = 0000 0000 0000 0000 0000 0000 0000 1110 (recall sign extension from before)
therefore: 1110 = 0xE in hex.  

Like before, in Java we can do this all in one shot:

Character.forDigit((bytes[0] & 0xF), 16);

Putting this all together we can do it as a for loop and convert the entire array:

for(int i=0; i < bytes.length; i++){
    buffer.append(Character.forDigit((bytes[i] >> 4) & 0xF, 16));
    buffer.append(Character.forDigit((bytes[i] & 0xF), 16));
}

Hopefully this explanation makes things clearer for those of you wondering exactly what is going on in the many examples you will find on the internet. Hopefully I didn't make any egregious errors, but suggestions and corrections are highly welcome!

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

Function pointer as a member of a C struct

Maybe I am missing something here, but did you allocate any memory for that PString before you accessed it?

PString * initializeString() {
    PString *str;
    str = (PString *) malloc(sizeof(PString));
    str->length = &length;
    return str;
}

How to Change color of Button in Android when Clicked?

you can try this code to solve your problem

<?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>

write this code in your drawable make a new resource and name it what you want and then write the name of this drwable in the button same as we refer to image src in android

What is the difference between single-quoted and double-quoted strings in PHP?

Some might say that I'm a little off-topic, but here it is anyway:

You don't necessarily have to choose because of your string's content between:
echo "It's \"game\" time."; or echo 'It\'s "game" time.';

If you're familiar with the use of the english quotation marks, and the correct character for the apostrophe, you can use either double or single quotes, because it won't matter anymore:
echo "It’s “game” time."; and echo 'It’s “game” time.';

Of course you can also add variables if needed. Just don't forget that they get evaluated only when in double quotes!

TransactionRequiredException Executing an update/delete query

I have also faced same issue when I work with Hibernate and Spring Jpa Data Repository. I forgot to place @Transactional on spring data repository method.

Its working for me after annotating with @Transactional.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

You could create a JsonConverter. See here for an example thats similar to your question.