Programs & Examples On #Hostheaders

how to check and set max_allowed_packet mysql variable

goto cpanel and login as Main Admin or Super Administrator

  1. find SSH/Shell Access ( you will find under the security tab of cpanel )

  2. now give the username and password of Super Administrator as root or whatyougave

    note: do not give any username, cos, it needs permissions
    
  3. once your into console type

    type ' mysql ' and press enter now you find youself in

    mysql> /* and type here like */

    mysql> set global net_buffer_length=1000000;

    Query OK, 0 rows affected (0.00 sec)

    mysql> set global max_allowed_packet=1000000000;

    Query OK, 0 rows affected (0.00 sec)

Now upload and enjoy!!!

What is the difference between 127.0.0.1 and localhost

Wikipedia sums this up well:

On modern computer systems, localhost as a hostname translates to an IPv4 address in the 127.0.0.0/8 (loopback) net block, usually 127.0.0.1, or ::1 in IPv6.

The only difference is that it would be looking up in the DNS for the system what localhost resolves to. This lookup is really, really quick. For instance, to get to stackoverflow.com you typed in that to the address bar (or used a bookmarklet that pointed here). Either way, you got here through a hostname. localhost provides a similar functionality.

How to exit an if clause

Generally speaking, don't. If you are nesting "ifs" and breaking from them, you are doing it wrong.

However, if you must:

if condition_a:
   def condition_a_fun():
       do_stuff()
       if we_wanna_escape:
           return
   condition_a_fun()
if condition_b:
   def condition_b_fun():
       do_more_stuff()
       if we_wanna_get_out_again:
           return
   condition_b_fun()

Note, the functions don't HAVE to be declared in the if statement, they can be declared in advance ;) This would be a better choice, since it will avoid needing to refactor out an ugly if/then later on.

How to set the image from drawable dynamically in android?

Try this:

String uri = "@drawable/myresource";  // where myresource (without the extension) is the file

int imageResource = getResources().getIdentifier(uri, null, getPackageName());

imageview= (ImageView)findViewById(R.id.imageView);
Drawable res = getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);

MySQL DAYOFWEEK() - my week begins with monday

How about subtracting one and changing Sunday

IF(DAYOFWEEK() = 1, 7, DAYOFWEEK() - 1)

Of course you would have to do this for every query.

CMake not able to find OpenSSL library

Please install openssl from below link:
https://code.google.com/p/openssl-for-windows/downloads/list
then set the variables below:

OPENSSL_ROOT_DIR=D:/softwares/visualStudio/openssl-0.9.8k_WIN32
OPENSSL_INCLUDE_DIR=D:/softwares/visualStudio/openssl-0.9.8k_WIN32/include
OPENSSL_LIBRARIES=D:/softwares/visualStudio/openssl-0.9.8k_WIN32/lib

Access images inside public folder in laravel

I have created an Asset helper of my own.

First I defined the asset types and path in app/config/assets.php:

return array(

    /*
    |--------------------------------------------------------------------------
    | Assets paths
    |--------------------------------------------------------------------------
    |
    | Location of all application assets, relative to the public folder,
    | may be used together with absolute paths or with URLs.
    |
    */

    'images' => '/storage/images',
    'css' => '/assets/css',
    'img' => '/assets/img',
    'js' => '/assets/js'
);

Then the actual Asset class:

class Asset
{
    private static function getUrl($type, $file)
    {
        return URL::to(Config::get('assets.' . $type) . '/' . $file);
    }

    public static function css($file)
    {
        return self::getUrl('css', $file);
    }

    public static function img($file)
    {
        return self::getUrl('img', $file);
    }

    public static function js($file)
    {
        return self::getUrl('js', $file);
    }

}

So in my view I can do this to show an image:

{{ HTML::image(Asset::img('logo.png'), "My logo")) }}

Or like this to implement a Java script:

{{ HTML::script(Asset::js('my_script.js')) }}

"query function not defined for Select2 undefined error"

I also had this problem make sure that you don't initialize the select2 twice.

How to add buttons dynamically to my form?

use button array like this.it will create 3 dynamic buttons bcoz h variable has value of 3

private void button1_Click(object sender, EventArgs e)
{
int h =3;


Button[] buttonArray = new Button[8];

for (int i = 0; i <= h-1; i++)
{
   buttonArray[i] = new Button();
   buttonArray[i].Size = new Size(20, 43);
   buttonArray[i].Name= ""+i+"";
   buttonArray[i].Click += button_Click;//function
   buttonArray[i].Location = new Point(40, 20 + (i * 20));
    panel1.Controls.Add(buttonArray[i]);

}  }

How can I create a dynamic button click event on a dynamic button?

The easier one for newbies:

Button button = new Button();
button.Click += new EventHandler(button_Click);

protected void button_Click (object sender, EventArgs e)
{
    Button button = sender as Button;
    // identify which button was clicked and perform necessary actions
}

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

How do I clear all variables in the middle of a Python script?

This is a modified version of Alex's answer. We can save the state of a module's namespace and restore it by using the following 2 methods...

__saved_context__ = {}

def saveContext():
    import sys
    __saved_context__.update(sys.modules[__name__].__dict__)

def restoreContext():
    import sys
    names = sys.modules[__name__].__dict__.keys()
    for n in names:
        if n not in __saved_context__:
            del sys.modules[__name__].__dict__[n]

saveContext()

hello = 'hi there'
print hello             # prints "hi there" on stdout

restoreContext()

print hello             # throws an exception

You can also add a line "clear = restoreContext" before calling saveContext() and clear() will work like matlab's clear.

AngularJS- Login and Authentication in each route and controller

You should check user authentication in two main sites.

  • When users change state, checking it using '$routeChangeStart' callback
  • When a $http request is sent from angular, using an interceptor.

How to create a file in memory for user to download, but not through server?

I'm happily using FileSaver.js. Its compatibility is pretty good (IE10+ and everything else), and it's very simple to use:

var blob = new Blob(["some text"], {
    type: "text/plain;charset=utf-8;",
});
saveAs(blob, "thing.txt");

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Run a command shell in jenkins

Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"

*Don't write bin at the end

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

Remove

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
</dependency> 

slf4j-log4j12 is the log4j binding for slf4j you dont need to add another log4j dependency.

Added
Provide the log4j configuration in log4j.properties and add it to your class path. There are sample configurations here

or you can change your binding to

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.1</version>
</dependency>

if you are configuring slf4j due to some dependencies requiring it.

Converting cv::Mat to IplImage*

Personaly I think it's not the problem caused by type casting but a buffer overflow problem; it is this line

cvCopy(iplimagearray[i], xyz);   

that I think will cause segment fault, I suggest that you confirm the array iplimagearray[i] have enough size of buffer to receive copyed data

Redirect on select option in select box

to make it as globally reuse function using jquery

HTML

<select class="select_location">
   <option value="http://localhost.com/app/page1.html">Page 1</option>
   <option value="http://localhost.com/app/page2.html">Page 2</option>
   <option value="http://localhost.com/app/page3.html">Page 3</option>
</select>

Javascript using jquery

$('.select_location').on('change', function(){
   window.location = $(this).val();
});

now you will able to reuse this function by adding .select_location class to any Select element class

How to correct indentation in IntelliJ

Select Java editor settings for Intellij Settings Select values for Tabsize, Indent & Continuation Intent (I choose 4,4 & 4)

Then Ctrl + Alt + L to format your file (or your selection).

Listing contents of a bucket with boto3

Here is a simple function that returns you the filenames of all files or files with certain types such as 'json', 'jpg'.

def get_file_list_s3(bucket, prefix="", file_extension=None):
            """Return the list of all file paths (prefix + file name) with certain type or all
            Parameters
            ----------
            bucket: str
                The name of the bucket. For example, if your bucket is "s3://my_bucket" then it should be "my_bucket"
            prefix: str
                The full path to the the 'folder' of the files (objects). For example, if your files are in 
                s3://my_bucket/recipes/deserts then it should be "recipes/deserts". Default : ""
            file_extension: str
                The type of the files. If you want all, just leave it None. If you only want "json" files then it
                should be "json". Default: None       
            Return
            ------
            file_names: list
                The list of file names including the prefix
            """
            import boto3
            s3 = boto3.resource('s3')
            my_bucket = s3.Bucket(bucket)
            file_objs =  my_bucket.objects.filter(Prefix=prefix).all()
            file_names = [file_obj.key for file_obj in file_objs if file_extension is not None and file_obj.key.split(".")[-1] == file_extension]
            return file_names

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

How to set True as default value for BooleanField on Django?

I am using django==1.11. The answer get the most vote is actually wrong. Checking the document from django, it says:

initial -- A value to use in this Field's initial display. This value is not used as a fallback if data isn't given.

And if you dig into the code of form validation process, you will find that, for each fields, form will call it's widget's value_from_datadict to get actual value, so this is the place where we can inject default value.

To do this for BooleanField, we can inherit from CheckboxInput, override default value_from_datadict and init function.

class CheckboxInput(forms.CheckboxInput):
    def __init__(self, default=False, *args, **kwargs):
        super(CheckboxInput, self).__init__(*args, **kwargs)
        self.default = default

    def value_from_datadict(self, data, files, name):
        if name not in data:
            return self.default
        return super(CheckboxInput, self).value_from_datadict(data, files, name)

Then use this widget when creating BooleanField.

class ExampleForm(forms.Form):
    bool_field = forms.BooleanField(widget=CheckboxInput(default=True), required=False)

android.view.InflateException: Binary XML file: Error inflating class fragment

I had this error too, and after very long debugging the problem seamed to be that my MainClass extended Activity instead of FrameActivity, in my case, the xml wasn't a problem. Hope to help you.

HTTP GET request in JavaScript?

Lots of great advice above, but not very reusable, and too often filled with DOM nonsense and other fluff that hides the easy code.

Here's a Javascript class we created that's reusable and easy to use. Currently it only has a GET method, but that works for us. Adding a POST shouldn't tax anyone's skills.

var HttpClient = function() {
    this.get = function(aUrl, aCallback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() { 
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                aCallback(anHttpRequest.responseText);
        }

        anHttpRequest.open( "GET", aUrl, true );            
        anHttpRequest.send( null );
    }
}

Using it is as easy as:

var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
    // do something with response
});

pip or pip3 to install packages for Python 3?

If you had python 2.x and then installed python3, your pip will be pointing to pip3. you can verify that by typing pip --version which would be the same as pip3 --version.

On your system you have now pip, pip2 and pip3.

If you want you can change pip to point to pip2 instead of pip3.

Website screenshots

cutycapt saves webpages to most image formats(jpg,png..) download it from your synaptic, it works much better than wkhtmltopdf

Tooltips for cells in HTML table (no Javascript)

if (data[j] =='B'){
    row.cells[j].title="Basic";
}

In Java script conditionally adding title by comparing value of Data. The Table is generated by Java script dynamically.

how to specify new environment location for conda create

While using the --prefix option works, you have to explicitly use it every time you create an environment. If you just want your environments stored somewhere else by default, you can configure it in your .condarc file.

Please see: https://conda.io/docs/user-guide/configuration/use-condarc.html#specify-environment-directories-envs-dirs

Get device information (such as product, model) from adb command

Why don't you try to grep the return of your command ? Something like :

adb devices -l | grep 123abc12

It should return only the line you want to.

string.split - by multiple character delimiter

To show both string.Split and Regex usage:

string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, @"\]\[");

Disable PHP in directory (including all sub-directories) with .htaccess

None of those answers are working for me (either generating a 500 error or doing nothing). That is probably due to the fact that I'm working on a hosted server where I can't have access to Apache configuration.

But this worked for me :

RewriteRule ^.*\.php$ - [F,L]

This line will generate a 403 Forbidden error for any URL that ends with .php and ends up in this subdirectory.

@Oussama lead me to the right direction here, thanks to him.

VS 2017 Metadata file '.dll could not be found

I had the same problem and i tried solutions from Metadata file '.dll' could not be found

but none of these worked.

So after trial and error i fixed it by unloading and reloading the project doing this reset the configuration file and fixed the issue.

Difference between using "chmod a+x" and "chmod 755"

Indeed there is.

chmod a+x is relative to the current state and just sets the x flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.

chmod 755, however, sets the mask as written: rwxr-xr-x, no matter how it was before. It is equivalent to chmod u=rwx,go=rx.

Change color and appearance of drop down arrow

You can acheive this with CSS but you are not techinically changing the arrow itself.

In this example I am actually hiding the default arrow and displaying my own arrow instead.

_x000D_
_x000D_
.styleSelect select {_x000D_
  background: transparent;_x000D_
  width: 168px;_x000D_
  padding: 5px;_x000D_
  font-size: 16px;_x000D_
  line-height: 1;_x000D_
  border: 0;_x000D_
  border-radius: 0;_x000D_
  height: 34px;_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
.styleSelect {_x000D_
  width: 140px;_x000D_
  height: 34px;_x000D_
  overflow: hidden;_x000D_
  background: url("images/downArrow.png") no-repeat right #fff;_x000D_
  border: 2px solid #000;_x000D_
}
_x000D_
<div class="styleSelect">_x000D_
  <select class="units">_x000D_
    <option value="Metres">Metres</option>_x000D_
    <option value="Feet">Feet</option>_x000D_
    <option value="Fathoms">Fathoms</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I find out what is hammering my SQL Server?

You can run the SQL Profiler, and filter by CPU or Duration so that you're excluding all the "small stuff". Then it should be a lot easier to determine if you have a problem like a specific stored proc that is running much longer than it should (could be a missing index or something).

Two caveats:

  • If the problem is massive amounts of tiny transactions, then the filter I describe above would exclude them, and you'd miss this.
  • Also, if the problem is a single, massive job (like an 8-hour analysis job or a poorly designed select that has to cross-join a billion rows) then you might not see this in the profiler until it is completely done, depending on what events you're profiling (sp:completed vs sp:statementcompleted).

But normally I start with the Activity Monitor or sp_who2.

How do I add an existing directory tree to a project in Visual Studio?

You can also drag and drop the folder from Windows Explorer onto your Visual Studio solution window.

Change arrow colors in Bootstraps carousel

I know this is an older post, but it helped me out. I've also found that for bootstrap v4 you can also change the arrow color by overriding the controls like this:

.carousel-control-prev-icon {
 background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E") !important;
}

.carousel-control-next-icon {
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E") !important;
}

Where you change fill='%23fff' the fff at the end to any hexadecimal value that you want. For example:

fill='%23000' for black, fill='%23ff0000' for red and so on. Just a note, I haven't tested this without the !important declaration.

deny directory listing with htaccess

Options -Indexes should work to prevent directory listings.

If you are using a .htaccess file make sure you have at least the "allowoverride options" setting in your main apache config file.

Correct way to pause a Python program

I use the following for Python 2 and Python 3 to pause code execution until user presses Enter

import six

if six.PY2:
    raw_input("Press the <Enter> key to continue...")
else:
    input("Press the <Enter> key to continue...")

How to change fonts in matplotlib (python)?

The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file. Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):

import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')

plt.show()

print(fpath) will show you where you should put the .ttf.

You can see the output here: https://matplotlib.org/gallery/api/font_file.html

Logcat not displaying my log calls

I've noticed that Eclipse will sometimes throw an exception upon starting an Android app, then LogCat stops updating. I've corrected that by simply restarting Eclipse. I'm not sure if you've tried that and I know it's far from an optimal solution, but I suspect that the Eclipse plugin still has a few bugs to iron out.

Virtual/pure virtual explained

"Virtual" means that the method may be overridden in subclasses, but has an directly-callable implementation in the base class. "Pure virtual" means it is a virtual method with no directly-callable implementation. Such a method must be overridden at least once in the inheritance hierarchy -- if a class has any unimplemented virtual methods, objects of that class cannot be constructed and compilation will fail.

@quark points out that pure-virtual methods can have an implementation, but as pure-virtual methods must be overridden, the default implementation can't be directly called. Here is an example of a pure-virtual method with a default:

#include <cstdio>

class A {
public:
    virtual void Hello() = 0;
};

void A::Hello() {
    printf("A::Hello\n");
}

class B : public A {
public:
    void Hello() {
        printf("B::Hello\n");
        A::Hello();
    }
};

int main() {
    /* Prints:
           B::Hello
           A::Hello
    */
    B b;
    b.Hello();
    return 0;
}

According to comments, whether or not compilation will fail is compiler-specific. In GCC 4.3.3 at least, it won't compile:

class A {
public:
    virtual void Hello() = 0;
};

int main()
{
    A a;
    return 0;
}

Output:

$ g++ -c virt.cpp 
virt.cpp: In function ‘int main()’:
virt.cpp:8: error: cannot declare variable ‘a’ to be of abstract type ‘A’
virt.cpp:1: note:   because the following virtual functions are pure within ‘A’:
virt.cpp:3: note:   virtual void A::Hello()

Simple CSS: Text won't center in a button

You can bootstrap. Now a days, almost all websites are developed using bootstrap. You can simply add bootstrap link in head of html file. Now simply add class="btn btn-primary" and your button will look like a normal button. Even you can use btn class on a tag as well, it will look like button on UI.

How to set a ripple effect on textview or imageview on Android?

Please refer below answer for ripple effect.

ripple on Textview or view :

android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackgroundBorderless"

ripple on Button or Imageview :

android:foreground="?android:attr/selectableItemBackgroundBorderless"

Add 10 seconds to a Date

The Date() object in javascript is not that smart really.

If you just focus on adding seconds it seems to handle things smoothly but if you try to add X number of seconds then add X number of minute and hours, etc, to the same Date object you end up in trouble. So I simply fell back to only using the setSeconds() method and converting my data into seconds (which worked fine).

If anyone can demonstrate adding time to a global Date() object using all the set methods and have the final time come out correctly I would like to see it but I get the sense that one set method is to be used at a time on a given Date() object and mixing them leads to a mess.

var vTime = new Date();

var iSecondsToAdd = ( iSeconds + (iMinutes * 60) + (iHours * 3600) + (iDays * 86400) );

vTime.setSeconds(iSecondsToAdd);

Here is some more documentation that may help:

What is the difference between Tomcat, JBoss and Glassfish?

Apache tomcat is just an only serverlet container it does not support for Enterprise Java application(JEE). JBoss and Glassfish are supporting for JEE application but Glassfish much heavy than JBOSS server : Reference Slide

How to put a new line into a wpf TextBlock control?

you must use

 < SomeObject xml:space="preserve" > once upon a time ...
      this line will be below the first one < /SomeObject>

Or if you prefer :

 <SomeObject xml:space="preserve" />  once upon a time... &#10; this line below < / SomeObject>

watch out : if you both use &10 AND you go to the next line in your text, you'll have TWO empty lines.

here for details : http://msdn.microsoft.com/en-us/library/ms788746.aspx

Filtering Table rows using Jquery

Have a look at this jsfiddle.

The idea is to filter rows with function which will loop through words.

jo.filter(function (i, v) {
    var $t = $(this);
    for (var d = 0; d < data.length; ++d) {
        if ($t.is(":contains('" + data[d] + "')")) {
            return true;
        }
    }
    return false;
})
//show the rows that match.
.show();

EDIT: Note that case insensitive filtering cannot be achieved using :contains() selector but luckily there's text() function so filter string should be uppercased and condition changed to if ($t.text().toUpperCase().indexOf(data[d]) > -1). Look at this jsfiddle.

Does JavaScript guarantee object property order?

Property order in normal Objects is a complex subject in Javascript.

While in ES5 explicitly no order has been specified, ES2015 has an order in certain cases. Given is the following object:

o = Object.create(null, {
  m: {value: function() {}, enumerable: true},
  "2": {value: "2", enumerable: true},
  "b": {value: "b", enumerable: true},
  0: {value: 0, enumerable: true},
  [Symbol()]: {value: "sym", enumerable: true},
  "1": {value: "1", enumerable: true},
  "a": {value: "a", enumerable: true},
});

This results in the following order (in certain cases):

Object {
  0: 0,
  1: "1",
  2: "2",
  b: "b",
  a: "a",
  m: function() {},
  Symbol(): "sym"
}
  1. integer-like keys in ascending order
  2. normal keys in insertion order
  3. Symbols in insertion order

Thus, there are three segments, which may alter the insertion order (as happened in the example). And integer-like keys don't stick to the insertion order at all.

The question is, for what methods this order is guaranteed in the ES2015 spec?

The following methods guarantee the order shown:

  • Object.assign
  • Object.defineProperties
  • Object.getOwnPropertyNames
  • Object.getOwnPropertySymbols
  • Reflect.ownKeys

The following methods/loops guarantee no order at all:

  • Object.keys
  • for..in
  • JSON.parse
  • JSON.stringify

Conclusion: Even in ES2015 you shouldn't rely on the property order of normal objects in Javascript. It is prone to errors. Use Map instead.

Rank function in MySQL

select id,first_name,gender,age,
rank() over(partition by gender order by age) rank_g
from person

CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1));

INSERT INTO person VALUES (1, 'Bob', 25, 'M');
INSERT INTO person VALUES (2, 'Jane', 20, 'F');
INSERT INTO person VALUES (3, 'Jack', 30, 'M');
INSERT INTO person VALUES (4, 'Bill', 32, 'M');
INSERT INTO person VALUES (5, 'Nick', 22, 'M');
INSERT INTO person VALUES (6, 'Kathy', 18, 'F');
INSERT INTO person VALUES (7, 'Steve', 36, 'M');
INSERT INTO person VALUES (8, 'Anne', 25, 'F');
INSERT INTO person VALUES (9,'AKSH',32,'M');

Dynamic Web Module 3.0 -- 3.1

1) Go to your project and find ".settings" directory this one
2) Open file xml named:
org.eclipse.wst.common.project.facet.core.xml
3)

<?xml version="1.0" encoding="UTF-8"?>
    <faceted-project>
    <fixed facet="wst.jsdt.web"/>
    <installed facet="java" version="1.5"/>
    <installed facet="jst.web" version="2.3"/>
    <installed facet="wst.jsdt.web" version="1.0"/>
 </faceted-project>

Change jst.web version to 3.0 and java version to 1.7 or 1.8 (base on your current using jdk version)

4) Change your web.xml file under WEB-INF directory , please refer to this article:
https://www.mkyong.com/web-development/the-web-xml-deployment-descriptor-examples/
5) Go to pom.xml file and paste these lines:

<build>
    <finalName>YOUR_PROJECT_NAME</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>1.8</source> THIS IS YOUR USING JDK's VERSION
                <target>1.8</target> SAME AS ABOVE
            </configuration>
        </plugin>
    </plugins>
</build>  

Using app.config in .Net Core

  1. You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app. Look into sample provided in the link, that shows how to read configs in the console app.

  2. In most cases, the JSON source (read as .json file) is the most suitable config source.

    Note: don't be confused when someone says that config file should be appsettings.json. You can use any file name, that is suitable for you and file location may be different - there are no specific rules.

    But, as the real world is complicated, there are a lot of different configuration providers:

    • File formats (INI, JSON, and XML)
    • Command-line arguments
    • Environment variables

    and so on. You even could use/write a custom provider.

  3. Actually, app.config configuration file was an XML file. So you can read settings from it using XML configuration provider (source on github, nuget link). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you. Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file.

Javascript/DOM: How to remove all events of a DOM object?

Chrome only

As I'm trying to remove an EventListener within a Protractor test and do not have access to the Listener in the test, the following works to remove all event listeners of a single type:

function(eventType){
    getEventListeners(window).[eventType].forEach(
        function(e){
            window.removeEventListener(eventType, e.listener)
        }
    );
}

I hope this helps someone as previous answer were using the "remove" method which since then does not work anymore.

Java String encoding (UTF-8)

How is this different from the following?

This line of code here:

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

constructs a new String object (i.e. a copy of oldString), while this line of code:

String newString = oldString;

declares a new variable of type java.lang.String and initializes it to refer to the same String object as the variable oldString.

Is there any scenario in which the two lines will have different outputs?

Absolutely:

String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true

vs.

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
 // isSameInstance == false (in most cases)    
boolean isSameInstance = newString == oldString;

a_horse_with_no_name (see comment) is right of course. The equivalent of

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

is

String newString = new String(oldString);

minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.

Named tuple and default values for optional keyword arguments

Python 3.7: introduction of defaults param in namedtuple definition.

Example as shown in the documentation:

>>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
>>> Account._fields_defaults
{'balance': 0}
>>> Account('premium')
Account(type='premium', balance=0)

Read more here.

How to compare type of an object in Python?

You can compare classes for check level.

#!/usr/bin/env python
#coding:utf8

class A(object):
    def t(self):
        print 'A'
    def r(self):
        print 'rA',
        self.t()

class B(A):
    def t(self):
        print 'B'

class C(A):
    def t(self):
        print 'C'

class D(B, C):
    def t(self):
        print 'D',
        super(D, self).t()

class E(C, B):
    pass

d = D()
d.t()
d.r()

e = E()
e.t()
e.r()

print isinstance(e, D) # False
print isinstance(e, E) # True
print isinstance(e, C) # True
print isinstance(e, B) # True
print isinstance(e, (A,)) # True
print e.__class__ >= A, #False
print e.__class__ <= C, #False
print e.__class__ <  E, #False
print e.__class__ <= E  #True

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

Behavior differences

Some differences on Bash 4.3.11:

  • POSIX vs Bash extension:

  • regular command vs magic

    • [ is just a regular command with a weird name.

      ] is just the last argument of [.

    Ubuntu 16.04 actually has an executable for it at /usr/bin/[ provided by coreutils, but the bash built-in version takes precedence.

    Nothing is altered in the way that Bash parses the command.

    In particular, < is redirection, && and || concatenate multiple commands, ( ) generates subshells unless escaped by \, and word expansion happens as usual.

    • [[ X ]] is a single construct that makes X be parsed magically. <, &&, || and () are treated specially, and word splitting rules are different.

      There are also further differences like = and =~.

    In Bashese: [ is a built-in command, and [[ is a keyword: https://askubuntu.com/questions/445749/whats-the-difference-between-shell-builtin-and-shell-keyword

  • <

  • && and ||

    • [[ a = a && b = b ]]: true, logical and
    • [ a = a && b = b ]: syntax error, && parsed as an AND command separator cmd1 && cmd2
    • [ a = a ] && [ b = b ]: POSIX reliable equivalent
    • [ a = a -a b = b ]: almost equivalent, but deprecated by POSIX because it is insane and fails for some values of a or b like ! or ( which would be interpreted as logical operations
  • (

    • [[ (a = a || a = b) && a = b ]]: false. Without ( ), would be true because [[ && ]] has greater precedence than [[ || ]]
    • [ ( a = a ) ]: syntax error, () is interpreted as a subshell
    • [ \( a = a -o a = b \) -a a = b ]: equivalent, but (), -a, and -o are deprecated by POSIX. Without \( \) would be true because -a has greater precedence than -o
    • { [ a = a ] || [ a = b ]; } && [ a = b ] non-deprecated POSIX equivalent. In this particular case however, we could have written just: [ a = a ] || [ a = b ] && [ a = b ] because the || and && shell operators have equal precedence unlike [[ || ]] and [[ && ]] and -o, -a and [
  • word splitting and filename generation upon expansions (split+glob)

    • x='a b'; [[ $x = 'a b' ]]: true, quotes not needed
    • x='a b'; [ $x = 'a b' ]: syntax error, expands to [ a b = 'a b' ]
    • x='*'; [ $x = 'a b' ]: syntax error if there's more than one file in the current directory.
    • x='a b'; [ "$x" = 'a b' ]: POSIX equivalent
  • =

    • [[ ab = a? ]]: true, because it does pattern matching (* ? [ are magic). Does not glob expand to files in current directory.
    • [ ab = a? ]: a? glob expands. So may be true or false depending on the files in the current directory.
    • [ ab = a\? ]: false, not glob expansion
    • = and == are the same in both [ and [[, but == is a Bash extension.
    • case ab in (a?) echo match; esac: POSIX equivalent
    • [[ ab =~ 'ab?' ]]: false, loses magic with '' in Bash 3.2 and above and provided compatibility to bash 3.1 is not enabled (like with BASH_COMPAT=3.1)
    • [[ ab? =~ 'ab?' ]]: true
  • =~

    • [[ ab =~ ab? ]]: true, POSIX extended regular expression match, ? does not glob expand
    • [ a =~ a ]: syntax error. No bash equivalent.
    • printf 'ab\n' | grep -Eq 'ab?': POSIX equivalent (single line data only)
    • awk 'BEGIN{exit !(ARGV[1] ~ ARGV[2])}' ab 'ab?': POSIX equivalent.

Recommendation: always use []

There are POSIX equivalents for every [[ ]] construct I've seen.

If you use [[ ]] you:

  • lose portability
  • force the reader to learn the intricacies of another bash extension. [ is just a regular command with a weird name, no special semantics are involved.

Thanks to Stéphane Chazelas for important corrections and additions.

How to use glOrtho() in OpenGL?

glOrtho describes a transformation that produces a parallel projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:

OpenGL documentation (my bold)

The numbers define the locations of the clipping planes (left, right, bottom, top, near and far).

The "normal" projection is a perspective projection that provides the illusion of depth. Wikipedia defines a parallel projection as:

Parallel projections have lines of projection that are parallel both in reality and in the projection plane.

Parallel projection corresponds to a perspective projection with a hypothetical viewpoint—e.g., one where the camera lies an infinite distance away from the object and has an infinite focal length, or "zoom".

How can I dynamically set the position of view in Android?

Use RelativeLayout, place your view in it, get RelativeLayout.LayoutParams object from your view and set margins as you need. Then call requestLayout() on your view. This is the only way I know.

How is a CRC32 checksum calculated?

The polynomial for CRC32 is:

x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1

Or in hex and binary:

0x 01 04 C1 1D B7
1 0000 0100 1100 0001 0001 1101 1011 0111

The highest term (x32) is usually not explicitly written, so it can instead be represented in hex just as

0x 04 C1 1D B7

Feel free to count the 1s and 0s, but you'll find they match up with the polynomial, where 1 is bit 0 (or the first bit) and x is bit 1 (or the second bit).

Why this polynomial? Because there needs to be a standard given polynomial and the standard was set by IEEE 802.3. Also it is extremely difficult to find a polynomial that detects different bit errors effectively.

You can think of the CRC-32 as a series of "Binary Arithmetic with No Carries", or basically "XOR and shift operations". This is technically called Polynomial Arithmetic.

To better understand it, think of this multiplication:

(x^3 + x^2 + x^0)(x^3 + x^1 + x^0)
= (x^6 + x^4 + x^3
 + x^5 + x^3 + x^2
 + x^3 + x^1 + x^0)
= x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0

If we assume x is base 2 then we get:

x^7 + x^3 + x^2 + x^1 + x^0

Why? Because 3x^3 is 11x^11 (but we need only 1 or 0 pre digit) so we carry over:

=1x^110 + 1x^101 + 1x^100          + 11x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^101 + 1x^100 + 1x^100 + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^101 + 1x^101          + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^110                   + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^111                            + 1x^11 + 1x^10 + 1x^1 + x^0

But mathematicians changed the rules so that it is mod 2. So basically any binary polynomial mod 2 is just addition without carry or XORs. So our original equation looks like:

=( 1x^110 + 1x^101 + 1x^100 + 11x^11 + 1x^10 + 1x^1 + x^0 ) MOD 2
=( 1x^110 + 1x^101 + 1x^100 +  1x^11 + 1x^10 + 1x^1 + x^0 )
= x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0 (or that original number we had)

I know this is a leap of faith but this is beyond my capability as a line-programmer. If you are a hard-core CS-student or engineer I challenge to break this down. Everyone will benefit from this analysis.

So to work out a full example:

   Original message                : 1101011011
   Polynomial of (W)idth 4         :      10011
   Message after appending W zeros : 11010110110000

Now we divide the augmented Message by the Poly using CRC arithmetic. This is the same division as before:

            1100001010 = Quotient (nobody cares about the quotient)
       _______________
10011 ) 11010110110000 = Augmented message (1101011011 + 0000)
=Poly   10011,,.,,....
        -----,,.,,....
         10011,.,,....
         10011,.,,....
         -----,.,,....
          00001.,,....
          00000.,,....
          -----.,,....
           00010,,....
           00000,,....
           -----,,....
            00101,....
            00000,....
            -----,....
             01011....
             00000....
             -----....
              10110...
              10011...
              -----...
               01010..
               00000..
               -----..
                10100.
                10011.
                -----.
                 01110
                 00000
                 -----
                  1110 = Remainder = THE CHECKSUM!!!!

The division yields a quotient, which we throw away, and a remainder, which is the calculated checksum. This ends the calculation. Usually, the checksum is then appended to the message and the result transmitted. In this case the transmission would be: 11010110111110.

Only use a 32-bit number as your divisor and use your entire stream as your dividend. Throw out the quotient and keep the remainder. Tack the remainder on the end of your message and you have a CRC32.

Average guy review:

         QUOTIENT
        ----------
DIVISOR ) DIVIDEND
                 = REMAINDER
  1. Take the first 32 bits.
  2. Shift bits
  3. If 32 bits are less than DIVISOR, go to step 2.
  4. XOR 32 bits by DIVISOR. Go to step 2.

(Note that the stream has to be dividable by 32 bits or it should be padded. For example, an 8-bit ANSI stream would have to be padded. Also at the end of the stream, the division is halted.)

How to do a recursive find/replace of a string with awk or sed?

The simplest way for me is

grep -rl oldtext . | xargs sed -i 's/oldtext/newtext/g'

Unable to access JSON property with "-" dash

For ansible, and using hyphen, this worked for me:

    - name: free-ud-ssd-space-in-percent
      debug:
        var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]

ImportError: No module named PyQt4.QtCore

As mentioned in the comments, you need to install the python-qt4 package - no need to recompile it yourself.

sudo apt-get install python-qt4

Using setImageDrawable dynamically to set image in an ImageView

The resource drawable names are not stored as strings, so you'll have to resolve the string into the integer constant generated during the build. You can use the Resources class to resolve the string into that integer.

Resources res = getResources();
int resourceId = res.getIdentifier(
   generatedString, "drawable", getPackageName() );
imageView.setImageResource( resourceId );

This resolves your generated string into the integer that the ImageView can use to load the right image.

Alternately, you can use the id to load the Drawable manually and then set the image using that drawable instead of the resource ID.

Drawable drawable = res.getDrawable( resourceId );
imageView.setImageDrawable( drawable );

how to specify local modules as npm package dependencies

If it's acceptible to simply publish your modules preinstalled in node_modules alongside your other files, you can do it like this:

// ./node_modules/foo/package.json
{ 
  "name":"foo",
  "version":"0.0.1",
  "main":"index.js"
}

// ./package.json
...
"dependencies": {
  "foo":"0.0.1",
  "bar":"*"
}

// ./app.js
var foo = require('foo');

You may also want to store your module on git and tell your parent package.json to install the dependency from git: https://npmjs.org/doc/json.html#Git-URLs-as-Dependencies

How to update PATH variable permanently from Windows command line?

In a corporate network, where the user has only limited access and uses portable apps, there are these command line tricks:

  1. Query the user env variables: reg query "HKEY_CURRENT_USER\Environment". Use "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" for LOCAL_MACHINE.
  2. Add new user env variable: reg add "HKEY_CURRENT_USER\Environment" /v shared_dir /d "c:\shared" /t REG_SZ. Use REG_EXPAND_SZ for paths containing other %% variables.
  3. Delete existing env variable: reg delete "HKEY_CURRENT_USER\Environment" /v shared_dir.

I have Python on my Ubuntu system, but gcc can't find Python.h

I ran into the same issue while trying to build a very old copy of omniORB on a CentOS 7 machine. Resolved the issue by installing the python development libraries:

# yum install python-devel

This installed the Python.h into:

/usr/include/python2.7/Python.h

How to Query Database Name in Oracle SQL Developer?

try this:

select * from global_name;

How to comment out particular lines in a shell script

You have to rely on '#' but to make the task easier in vi you can perform the following (press escape first):

:10,20 s/^/#

with 10 and 20 being the start and end line numbers of the lines you want to comment out

and to undo when you are complete:

:10,20 s/^#//

Find IP address of directly connected device

You can also get information from directly connected networking devices, such as network switches with LDWin, a portable and free Windows program published on github:

http://www.sysadmit.com/2016/11/windows-como-saber-la-ip-del-switch-al-que-estoy-conectado.html

LDWin supports the following methods of link discovery: CDP (Cisco Discovery Protocol) and LLDP (Link Layer Discovery Protocol).

You can obtain the model, management IP, VLAN identifier, Port identifier, firmware version, etc.

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

Check the site's Application Pool in IIS / Application Pools / YourPool / Advanced Settings :

  • Advanced / Enable 32-Bit Applications: True

There's some anecdotal evidence to suggest you do this too:

  • Managed Pipeline Mode : Classic

Linux: command to open URL in default browser

At least on Debian and all its derivatives, there is a 'sensible-browser' shell script which choose the browser best suited for the given url.

http://man.he.net/man1/sensible-browser

Determining if an Object is of primitive type

The primitve wrapper types will not respond to this value. This is for class representation of primitives, though aside from reflection I can't think of too many uses for it offhand. So, for example

System.out.println(Integer.class.isPrimitive());

prints "false", but

public static void main (String args[]) throws Exception
{
    Method m = Junk.class.getMethod( "a",null);
    System.out.println( m.getReturnType().isPrimitive());
}

public static int a()
{
    return 1;
}

prints "true"

Make selected block of text uppercase

Without defining keyboard shortcuts

  1. Select the text you want capitalized

  2. Open View->Command Palette (or Shift+Command+P)

  3. Start typing "Transform to uppercase" and select that option

  4. Voila!

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

@Before(JUnit4) -> @BeforeEach(JUnit5) - method is called before every test

@After(JUnit4) -> @AfterEach(JUnit5) - method is called after every test

@BeforeClass(JUnit4) -> @BeforeAll(JUnit5) - static method is called before executing all tests in this class. It can be a large task as starting server, read file, making db connection...

@AfterClass(JUnit4) -> @AfterAll(JUnit5) - static method is called after executing all tests in this class.

Slide div left/right using jQuery

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
            $('#right').show("slide", { direction: "right" }, 500);_x000D_
        });_x000D_
    });_x000D_
    $("#right").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
            $('#left').show("slide", { direction: "left" }, 500);_x000D_
        });_x000D_
    });_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
        $('#fsEditWindow').show("slide", { direction: "left" }, 500);
    });
});

It will work like charm take a look at the demo.

How to add an image in Tkinter?

Python 3.3.1 [MSC v.1600 32 bit (Intel)] on win32 14.May.2013

This worked for me, by following the code above

from tkinter import *
from PIL import ImageTk, Image
import os

root = Tk()
img = ImageTk.PhotoImage(Image.open("True1.gif"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

Usage of sys.stdout.flush() method

Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush() forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.

Here's some good information about (un)buffered I/O and why it's useful:
http://en.wikipedia.org/wiki/Data_buffer
Buffered vs unbuffered IO

Convert number to month name in PHP

Just because everyone is using strtotime() and date() functions, I will show DateTime example:

$dt = DateTime::createFromFormat('!m', $result['month']);
echo $dt->format('F');

How to use an environment variable inside a quoted string in Bash

You are doing it right, so I guess something else is at fault (not export-ing COLUMNS ?).

A trick to debug these cases is to make a specialized command (a closure for programming language guys). Create a shell script named diff-columns doing:

exec /usr/bin/diff -x -y -w -p -W "$COLUMNS" "$@"

and just use

svn diff "$@" --diff-cmd  diff-columns

This way your code is cleaner to read and more modular (top-down approach), and you can test the diff-columns code thouroughly separately (bottom-up approach).

Bootstrap 4 img-circle class not working

In Bootstrap 4 it was renamed to .rounded-circle

Usage :

<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>

See migration docs from bootstrap.

Best dynamic JavaScript/JQuery Grid

My suggestion for dynamic JQuery Grid are below.

http://reconstrukt.com/ingrid/

https://github.com/mleibman/SlickGrid

http://www.datatables.net/index

Best one is :

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.

Variable length pagination

On-the-fly filtering

Multi-column sorting with data type detection

Smart handling of column widths

Display data from almost any data source

DOM, Javascript array, Ajax file and server-side processing (PHP, C#, Perl, Ruby, AIR, Gears etc)

Scrolling options for table viewport

Fully internationalisable

jQuery UI ThemeRoller support

Rock solid - backed by a suite of 2600+ unit tests

Wide variety of plug-ins inc. TableTools, FixedColumns, KeyTable and more

Dynamic creation of tables

Ajax auto loading of data

Custom DOM positioning

Single column filtering

Alternative pagination types

Non-destructive DOM interaction

Sorting column(s) highlighting

Advanced data source options

Extensive plug-in support

Sorting, type detection, API functions, pagination and filtering

Fully themeable by CSS

Solid documentation

110+ pre-built examples

Full support for Adobe AIR

Easiest way to use SVG in Android?

Try the SVG2VectorDrawable Plugin. Go to Preferences->Plugins->Browse Plugins and install SVG2VectorDrawable. Great for converting sag files to vector drawable. Once you have installed you will find an icon for this in the toolbar section just to the right of the help (?) icon.

How to merge a specific commit in Git

In my use case we had a similar need for CI CD. We used git flow with develop and master branches. Developers are free to merge their changes directly to develop or via a pull request from a feature branch. However to master we merge only the stable commits from the develop branch in an automated way via Jenkins.

In this case doing cherry-pick is not a good option. However we create a local-branch from the commit-id then merge that local-branch to master and perform mvn clean verify(we use maven). If success then release production version artifact to nexus using maven release plugin with localCheckout=true option and pushChanges=false. Finally when everything is success then push the changes and tag to origin.

A sample code snippet:

Assuming you are on master if done manually. However on jenkins, when you checkout the repo you will be on the default branch(master if configured).

git pull  // Just to pull any changes.
git branch local-<commitd-id> <commit-id>  // Create a branch from the given commit-id
git merge local-<commit-id>  // Merge that local branch to master.
mvn clean verify   // Verify if the code is build able
mvn <any args> release:clean release:prepare release:perform // Release artifacts
git push origin/master  // Push the local changes performed above to origin.
git push origin <tag>  // Push the tag to origin

This will give you a full control with a fearless merge or conflict hell.

Feel free to advise in case there is any better option.

Concatenating strings in Razor

Use the parentesis syntax of Razor:

@(Model.address + " " + Model.city)

or

@(String.Format("{0} {1}", Model.address, Model.city))

Update: With C# 6 you can also use the $-Notation (officially interpolated strings):

@($"{Model.address} {Model.city}")

How to unpublish an app in Google Play Developer Console

Click on Store Listing and then click on 'Unpublish App'.

See image for details

How do I install the OpenSSL libraries on Ubuntu?

sudo apt-get install libcurl4-openssl-dev

Maximum filename length in NTFS (Windows XP and Windows Vista)?

It's 257 characters. To be precise: NTFS itself does impose a maximum filename-length of several thousand characters (around 30'000 something). However, Windows imposes a 260 maximum length for the Path+Filename. The drive+folder takes up at least 3 characters, so you end up with 257.

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

What I recomend is: (This works to me after many days with errors)

-Make sure that you have downloaded:

- the Lastest SDK Platform from the latest Android version
- Android Suppor Librarie and Repository from EXTRAS 

-Redowload the ADT

-Make a security copy of your project.

-You must have the ADT, the workspace and the project that we will import in the same disk (e.g. C:/)

  1. Now delete the app compat and your project.

  2. In eclipse: File > Import > Android existing project > Next > Browse (The folder where you have your ADT)/sdk/extras/android/v7/appcompat > Import > Finish

  3. Now in the eclipse Package Explorer: android-support-v7-appcompat/libs/ Make on the two JARS: Right click > Build Path > Add to Build Path

  4. Right click on libs/ folder > Buil Path > Configure Build Path and check this two JARS > OK

  5. On the upper eclipse bar > Project > Clean

  6. Import your project > File > Import > Browse your project > Finish

  7. Now, Right click on the projectfile and android-support-v7-appcompat > Properties > Android > And select the latest API that appears > OK

  8. Right click on the projectfile > Properties > Android > Add > android-support-v7-appcompat

  9. On the upper eclipse bar > Project > Clean

How can I Insert data into SQL Server using VBNet

It means that the number of values specified in your VALUES clause on the INSERT statement is not equal to the total number of columns in the table. You must specify the columnname if you only try to insert on selected columns.

Another one, since you are using ADO.Net , always parameterized your query to avoid SQL Injection. What you are doing right now is you are defeating the use of sqlCommand.

ex

Dim query as String = String.Empty
query &= "INSERT INTO student (colName, colID, colPhone, "
query &= "                     colBranch, colCourse, coldblFee)  "
query &= "VALUES (@colName,@colID, @colPhone, @colBranch,@colCourse, @coldblFee)"

Using conn as New SqlConnection("connectionStringHere")
    Using comm As New SqlCommand()
        With comm
            .Connection = conn
            .CommandType = CommandType.Text
            .CommandText = query
            .Parameters.AddWithValue("@colName", strName)
            .Parameters.AddWithValue("@colID", strId)
            .Parameters.AddWithValue("@colPhone", strPhone)
            .Parameters.AddWithValue("@colBranch", strBranch)
            .Parameters.AddWithValue("@colCourse", strCourse)
            .Parameters.AddWithValue("@coldblFee", dblFee)
        End With
        Try
            conn.open()
            comm.ExecuteNonQuery()
        Catch(ex as SqlException)
            MessageBox.Show(ex.Message.ToString(), "Error Message")
        End Try
    End Using
End USing 

PS: Please change the column names specified in the query to the original column found in your table.

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

def nans(df): return df[df.isnull().any(axis=1)]

then when ever you need it you can type:

nans(your_dataframe)

How to get the query string by javascript?

Very Straightforward!

function parseQueryString(){
    var assoc = {};
    var keyValues = location.search.slice(1).split('&');
    var decode = function(s){
        return decodeURIComponent(s.replace(/\+/g, ' '));
    };

    for (var i = 0; i < keyValues.length; ++i) {
        var key = keyValues[i].split('=');
        if (1 < key.length) {
            assoc[decode(key[0])] = decode(key[1]);
        }
    }

    return assoc;
}

How does the communication between a browser and a web server take place?

Communication between a browser and a webserver takes place at so many levels that is close to impossible to answer this question. HTTP plays a role, but HTTP is meaningless without TCP which is meaningless without IP which is meaningless without a physical network on which it sent. Then, there are POST vs GET requests which are similar but enough different to warrant a special dicussion. Sometimes an HTTP request needs to be authenticated, sometimes, it needs not. Mime types should be mentioned. Then, a browser sends a different request if there is a proxy. And then also encodings play a role. So, I guess, the most concise answer to this kind of question is: the browser asks the server for data and the server gives the requested data to the browser.

moving changed files to another branch for check-in

If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally - changes to files are not tied to a particular branch until you commit them.

If you have already committed your changes:

  1. Type git log and remember the SHA of the commit you want to move.
  2. Check out the branch you want to move the commit to.
  3. Type git cherry-pick SHA substituting the SHA from above.
  4. Switch back to your original branch.
  5. Use git reset HEAD~1 to reset back before your wrong-branch commit.

cherry-pick takes a given commit and applies it to the currently checked-out head, thus allowing you to copy the commit over to a new branch.

Emulator error: This AVD's configuration is missing a kernel file

Open AVD Manager in Administrator mode Select VM and click edit, click OK Start VM.

Editor's note: By administrator mode, he meant Right-click > Run as administrator on windows platforms .

Python Finding Prime Factors

This is my python code: it has a fast check for primes and checks from highest to lowest the prime factors. You have to stop if no new numbers came out. (Any ideas on this?)

import math


def is_prime_v3(n):
    """ Return 'true' if n is a prime number, 'False' otherwise """
    if n == 1:
        return False

    if n > 2 and n % 2 == 0:
        return False

    max_divisor = math.floor(math.sqrt(n))
    for d in range(3, 1 + max_divisor, 2):
        if n % d == 0:
            return False
    return True


number = <Number>

for i in range(1,math.floor(number/2)):
    if is_prime_v3(i):
        if number % i == 0:
            print("Found: {} with factor {}".format(number / i, i))

The answer for the initial question arrives in a fraction of a second.

What is the difference between compare() and compareTo()?

Employee Table
Name, DoB, Salary
Tomas , 2/10/1982, 300
Daniel , 3/11/1990, 400
Kwame , 2/10/1998, 520

The Comparable interface allows you to sort a list of objects eg Employees with reference to one primary field – for instance, you could sort by name or by salary with the CompareTo() method

emp1.getName().compareTo(emp2.getName())

A more flexible interface for such requirements is provided by the Comparator interface, whose only method is compare()

public interface Comparator<Employee> {
 int compare(Employee obj1, Employee obj2);
}

Sample code

public class NameComparator implements Comparator<Employee> {

public int compare(Employee e1, Employee e2) {
     // some conditions here
        return e1.getName().compareTo(e2.getName()); // returns 1 since (T)omas > (D)an 
    return e1.getSalary().compareTo(e2.getSalary()); // returns -1 since 400 > 300
}

}

How to set width of a p:column in a p:dataTable in PrimeFaces 3.0?

I don't know what browser you're using, but according to w3schools.com, nth-child and nth-last-child do now work on MSIE 8. I don't know about 9. http://www.w3schools.com/cssref/pr_border-style.asp will give you more info.

How to make HTML element resizable using pure Javascript?

_x000D_
_x000D_
// import
function get_difference(pre, mou) {
  return {
    x: mou.x - pre.x,
    y: mou.y - pre.y
  };
}

/*
if your panel is in a nested environment, which the parent container's width and height does not equa to document width 
and height, for example, in an element `canvas`, then edit it to

function oMousePos(e) {
  var rc = canvas.getBoundingClientRect();
  return {
    x: e.clientX - rc.left,
    y: e.clientY - rc.top,
  };
}
*/

function oMousePos(e) {
  return {
    x: e.clientX,
    y: e.clientY,
  };
}

function render_element(styles, el) {
  for (const [kk, vv] of Object.entries(styles)) {
    el.style[kk] = vv;
  }
}

class MoveablePanel {

  /*
  prevent an element from moving out of window
  */
  constructor(container, draggable, left, top) {
    this.container = container;
    this.draggable = draggable;
    this.left = left;
    this.top = top;
    let rect = container.getBoundingClientRect();
    this.width = rect.width;
    this.height = rect.height;
    this.status = false;

    // initial position of the panel, should not be changed
    this.original = {
      left: left,
      top: top
    };

    // current left and top postion
    // {this.left, this.top}

    // assign the panel to initial position
    // initalize in registration
    this.default();

    if (!MoveablePanel._instance) {
      MoveablePanel._instance = [];
    }
    MoveablePanel._instance.push(this);
  }

  mousedown(e) {
    this.status = true;
    this.previous = oMousePos(e)
  }

  mousemove(e) {
    if (!this.status) {
      return;
    }
    let pos = oMousePos(e);
    let vleft = this.left + pos.x - this.previous.x;
    let vtop = this.top + pos.y - this.previous.y;
    let kleft, ktop;

    if (vleft < 0) {
      kleft = 0;
    } else if (vleft > window.innerWidth - this.width) {
      kleft = window.innerWidth - this.width;
    } else {
      kleft = vleft;
    }

    if (vtop < 0) {
      ktop = 0;
    } else if (vtop > window.innerHeight - this.height) {
      ktop = window.innerHeight - this.height;
    } else {
      ktop = vtop;
    }
    this.container.style.left = `${kleft}px`;
    this.container.style.top = `${ktop}px`;
  }

  /*
  sometimes user move the cursor too fast which mouseleave is previous than mouseup
  to prevent moving too fast and break the control, mouseleave is handled the same as mouseup
  */

  mouseupleave(e) {
    if (!this.status) {
      return null;
    }
    this.status = false;
    let pos = oMousePos(e);
    let vleft = this.left + pos.x - this.previous.x;
    let vtop = this.top + pos.y - this.previous.y;

    if (vleft < 0) {
      this.left = 0;
    } else if (vleft > window.innerWidth - this.width) {
      this.left = window.innerWidth - this.width;
    } else {
      this.left = vleft;
    }

    if (vtop < 0) {
      this.top = 0;
    } else if (vtop > window.innerHeight - this.height) {
      this.top = window.innerHeight - this.height;
    } else {
      this.top = vtop;
    }

    this.show();
    return true;
  }

  default () {
    this.container.style.left = `${this.original.left}px`;
    this.container.style.top = `${this.original.top}px`;
  }

  /*
  panel with a higher z index will interupt drawing
  therefore if panel is not displaying, set it with a lower z index that canvas

  change index doesn't work, if panel is hiding, then we move it out
  hide: record current position, move panel out
  show: assign to recorded position

  notice this position has nothing to do panel drag movement
  they cannot share the same variable
  */

  hide() {
    // move to the right bottom conner
    this.container.style.left = `${window.screen.width}px`;
    this.container.style.top = `${window.screen.height}px`;
  }

  show() {
    this.container.style.left = `${this.left}px`;
    this.container.style.top = `${this.top}px`;
  }
}
// end of import

class DotButton{
    constructor(
        width_px, 
        styles, // mainly pos, padding and margin, e.g. {top: 0, left: 0, margin: 0},
        color, 
        color_hover,
        border, // boolean
        border_dismiss, // boolean: dismiss border when hover
    ){
        this.width = width_px;
        this.styles = styles;
        this.color = color;
        this.color_hover = color_hover;
        this.border = border;
        this.border_dismiss = border_dismiss;
    }

    create(_styles=null){
        var el = document.createElement('div');
        Object.keys(this.styles).forEach(kk=>{
            el.style[kk] = `${this.styles[kk]}px`;
        });
        if(_styles){
            Object.keys(_styles).forEach(kk=>{
                el.style[kk] = `${this.styles[kk]}px`;
            });
        }
        el.style.width = `${this.width}px`
        el.style.height = `${this.width}px`
        el.style.position = 'absolute';
        el.style.left = `${this.left_px}px`;
        el.style.top = `${this.top_px}px`;
        el.style.background = this.color;
        if(this.border){
            el.style.border = '1px solid'; 
        }
        el.style.borderRadius = `${this.width}px`;

        el.addEventListener('mouseenter', ()=>{
            el.style.background = this.color_hover;
            if(this.border_dismiss){
                el.style.border = `1px solid ${this.color_hover}`; 
            }
        });
        el.addEventListener('mouseleave', ()=>{
            el.style.background = this.color;
            if(this.border_dismiss){
                el.style.border = '1px solid'; 
            }
        });
        return el;
    }
}

function cursor_hover(el, default_cursor, to_cursor){
    el.addEventListener('mouseenter', function(){
        this.style.cursor = to_cursor;
    }.bind(el));


    el.addEventListener('mouseleave', function(){
        this.style.cursor = default_cursor;
    }.bind(el));
}

class FlexPanel extends MoveablePanel{
    constructor(
        parent_el,
        top_px,
        left_px,
        width_px, 
        height_px, 
        background,
        handle_width_px, 
        coner_vmin_ratio, 
        button_width_px, 
        button_margin_px, 
    ){
        super(
            (()=>{
                var el = document.createElement('div');
                render_element(
                    {
                        position: 'fixed', 
                        top: `${top_px}px`,
                        left: `${left_px}px`,
                        width: `${width_px}px`,
                        height: `${height_px}px`,
                        background: background, 
                    }, 
                    el,
                );
                return el;
            })(), // iife returns a container (panel el)
            new DotButton(button_width_px, {top: 0, right: 0, margin: button_margin_px}, 'green', 'lightgreen', false, false).create(), // draggable
            left_px, // left
            top_px, // top
        );

        this.draggable.addEventListener('mousedown', e => {
            e.preventDefault();
            this.mousedown(e);
        });

        this.draggable.addEventListener('mousemove', e => {
            e.preventDefault();
            this.mousemove(e);
        });

        this.draggable.addEventListener('mouseup', e => {
            e.preventDefault();
            this.mouseupleave(e);
        });

        this.draggable.addEventListener('mouseleave', e => {
            e.preventDefault();
            this.mouseupleave(e);
        });

        this.parent_el = parent_el;
        this.background = background;

        // parent
        this.width = width_px;
        this.height = height_px;

        this.handle_width_px = handle_width_px;
        this.coner_vmin_ratio = coner_vmin_ratio;

        this.panel_el = document.createElement('div');

        // styles that won't change 
        this.panel_el.style.position = 'absolute';
        this.panel_el.style.top = `${this.handle_width_px}px`;
        this.panel_el.style.left = `${this.handle_width_px}px`; 
        this.panel_el.style.background = this.background;
    
        this.handles = [
            this.handle_top,
            this.handle_left,
            this.handle_bottom,
            this.handle_right, 

            this.handle_lefttop,
            this.handle_topleft,
            this.handle_topright,
            this.handle_righttop, 
            this.handle_rightbottom, 
            this.handle_bottomright,
            this.handle_bottomleft,
            this.handle_leftbottom, 
        ] = Array.from({length: 12}, i => document.createElement('div'));

        this.handles.forEach(el=>{
            el.style.position = 'absolute';
        });

        this.handle_topleft.style.top = '0';
        this.handle_topleft.style.left = `${this.handle_width_px}px`;

        this.handle_righttop.style.right = '0';
        this.handle_righttop.style.top = `${this.handle_width_px}px`;

        this.handle_bottomright.style.bottom = '0';
        this.handle_bottomright.style.right = `${this.handle_width_px}px`;

        this.handle_leftbottom.style.left = '0';
        this.handle_leftbottom.style.bottom = `${this.handle_width_px}px`;


        this.handle_lefttop.style.left = '0';
        this.handle_lefttop.style.top = '0';

        this.handle_topright.style.top = '0';
        this.handle_topright.style.right = '0';

        this.handle_rightbottom.style.right = '0';
        this.handle_rightbottom.style.bottom = '0';

        this.handle_bottomleft.style.bottom = '0';
        this.handle_bottomleft.style.left = '0';

        this.update_ratio();

        [
            'ns-resize', // |
            'ew-resize', // -
            'ns-resize', // |
            'ew-resize', // -

            'nwse-resize', // \
            'nwse-resize', // \
            'nesw-resize', // /
            'nesw-resize', // /
            'nwse-resize', // \
            'nwse-resize', // \
            'nesw-resize', // /
            'nesw-resize', // /
        ].map((dd, ii)=>{
            cursor_hover(this.handles[ii], 'default', dd);
        });

        this.vtop = this.top;
        this.vleft = this.left;
        this.vwidth = this.width;
        this.vheight = this.height;

        this.update_ratio();

        this.handles.forEach(el=>{
            this.container.appendChild(el);
        });

        cursor_hover(this.draggable, 'default', 'move');

        this.panel_el.appendChild(this.draggable);
        this.container.appendChild(this.panel_el);
        this.parent_el.appendChild(this.container);

        [
            this.edgemousedown, 
            this.verticalmousemove,
            this.horizontalmousemove,
            this.nwsemousemove,
            this.neswmousemove,
            this.edgemouseupleave,
        ] = [
            this.edgemousedown.bind(this),
            this.verticalmousemove.bind(this),
            this.horizontalmousemove.bind(this),
            this.nwsemousemove.bind(this),
            this.neswmousemove.bind(this),
            this.edgemouseupleave.bind(this),
        ];

        this.handle_top.addEventListener('mousedown', e=>{this.edgemousedown(e, 'top')});
        this.handle_left.addEventListener('mousedown', e=>{this.edgemousedown(e, 'left')});
        this.handle_bottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottom')});
        this.handle_right.addEventListener('mousedown', e=>{this.edgemousedown(e, 'right')}); 
        this.handle_lefttop.addEventListener('mousedown', e=>{this.edgemousedown(e, 'lefttop')});
        this.handle_topleft.addEventListener('mousedown', e=>{this.edgemousedown(e, 'topleft')});
        this.handle_topright.addEventListener('mousedown', e=>{this.edgemousedown(e, 'topright')});
        this.handle_righttop.addEventListener('mousedown', e=>{this.edgemousedown(e, 'righttop')}); 
        this.handle_rightbottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'rightbottom')}); 
        this.handle_bottomright.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottomright')});
        this.handle_bottomleft.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottomleft')});
        this.handle_leftbottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'leftbottom')});

        this.handle_top.addEventListener('mousemove', this.verticalmousemove);
        this.handle_left.addEventListener('mousemove', this.horizontalmousemove);
        this.handle_bottom.addEventListener('mousemove', this.verticalmousemove);
        this.handle_right.addEventListener('mousemove', this.horizontalmousemove); 
        this.handle_lefttop.addEventListener('mousemove', this.nwsemousemove);
        this.handle_topleft.addEventListener('mousemove', this.nwsemousemove);
        this.handle_topright.addEventListener('mousemove', this.neswmousemove);
        this.handle_righttop.addEventListener('mousemove', this.neswmousemove); 
        this.handle_rightbottom.addEventListener('mousemove', this.nwsemousemove); 
        this.handle_bottomright.addEventListener('mousemove', this.nwsemousemove);
        this.handle_bottomleft.addEventListener('mousemove', this.neswmousemove);
        this.handle_leftbottom.addEventListener('mousemove', this.neswmousemove);

        this.handle_top.addEventListener('mouseup', e=>{this.verticalmousemove(e); this.edgemouseupleave()});
        this.handle_left.addEventListener('mouseup', e=>{this.horizontalmousemove(e); this.edgemouseupleave()});
        this.handle_bottom.addEventListener('mouseup', e=>{this.verticalmousemove(e); this.edgemouseupleave()});
        this.handle_right.addEventListener('mouseup', e=>{this.horizontalmousemove(e); this.edgemouseupleave()}); 
        this.handle_lefttop.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_topleft.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_topright.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
        this.handle_righttop.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()}); 
        this.handle_rightbottom.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()}); 
        this.handle_bottomright.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_bottomleft.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
        this.handle_leftbottom.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
    
        this.handle_top.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_left.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottom.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_right.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_lefttop.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_topleft.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_topright.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_righttop.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_rightbottom.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottomright.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottomleft.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_leftbottom.addEventListener('mouseleave', this.edgemouseupleave);
    }

    // box size change triggers corner handler size change
    update_ratio(){
        this.container.style.top = `${this.vtop}px`;
        this.container.style.left = `${this.vleft}px`;
        this.container.style.width = `${this.vwidth}px`;
        this.container.style.height = `${this.vheight}px`;

        this.panel_el.style.width = `${this.vwidth - 2 * this.handle_width_px}px`;
        this.panel_el.style.height = `${this.vheight - 2 * this.handle_width_px}px`;

        this.ratio = this.vwidth < this.vheight ? this.coner_vmin_ratio * this.vwidth : this.coner_vmin_ratio * this.vheight;
        [
            this.handle_top,
            this.handle_bottom, 
        ].forEach(el=>{
            el.style.width = `${this.vwidth - 2 * this.ratio}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_left,
            this.handle_right, 
        ].forEach(el=>{
            el.style.height = `${this.vheight - 2 * this.ratio}px`;
            el.style.width = `${this.handle_width_px}px`;
        });

        this.handle_top.style.top = `0`;
        this.handle_top.style.left = `${this.ratio}px`;

        this.handle_left.style.top = `${this.ratio}px`;
        this.handle_left.style.left = `0`;

        this.handle_bottom.style.bottom = `0`;
        this.handle_bottom.style.right = `${this.ratio}px`;

        this.handle_right.style.bottom = `${this.ratio}px`;
        this.handle_right.style.right = `0`;

        [
            this.handle_topright,
            this.handle_bottomleft,
        ].forEach(el=>{
            el.style.width = `${this.ratio}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_lefttop,
            this.handle_rightbottom,
        ].forEach(el=>{
            el.style.width = `${this.handle_width_px}px`;
            el.style.height = `${this.ratio}px`;
        });

        [
            this.handle_topleft,
            this.handle_bottomright,
        ].forEach(el=>{
            el.style.width = `${this.ratio - this.handle_width_px}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_righttop,
            this.handle_leftbottom,
        ].forEach(el=>{
            el.style.height = `${this.handle_width_px}px`;
            el.style.width = `${this.ratio - this.handle_width_px}px`;
        });
    }

    edgemousedown(e, flag){
        this.previous = oMousePos(e);
        this.flag = flag;
        this.drag = true;
    }

    verticalmousemove(e){
        if(this.drag){
            // -
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            switch(this.flag){
                case 'top':
                    this.vtop = this.top + ydif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                    this.vwidth = this.width;
                break;

                case 'bottom':
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                    this.vwidth = this.width;
                break;
            }
            this.update_ratio();
        }
    }

    horizontalmousemove(e){
        if(this.drag){
            // |
            this.mouse = oMousePos(e);
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'left':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;

                    this.vtop = this.top;
                    this.vheight = this.height;
                break;

                case 'right':
                    this.vwidth = this.width + xdif;
                
                    this.vtop = this.top;
                    this.vleft = this.left;
                    this.vheight = this.height;
                break;
            }
            this.update_ratio();
        }
    }

    nwsemousemove(e){
        if(this.drag){
            // \
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'topleft':
                    this.vleft = this.left + xdif;
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height - ydif;
                break;

                case 'lefttop':
                    this.vleft = this.left + xdif;
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height - ydif;
                break;

                case 'bottomright':
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                break;

                case 'rightbottom':
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                break;
            }
            this.update_ratio();
        }
    }

    neswmousemove(e){
        if(this.drag){
            // /
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'topright':
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                break;

                case 'righttop':
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                break;

                case 'bottomleft':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                break;

                case 'leftbottom':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                break;
            }
            this.update_ratio();
        }
    }

    edgemouseupleave(){
        this.drag = false;
        this.top = this.vtop;
        this.left = this.vleft;
        this.width = this.vwidth;
        this.height = this.vheight;
    }

    mouseupleave(e){
        if(super.mouseupleave(e)){
            this.vtop = this.top;
            this.vleft = this.left;         
        }
    }
}


var fp = new FlexPanel(
    document.body, // parent div container
    20, // top margin
    20, // left margin
    200, // width 
    150, // height
    'lightgrey', // background
    20, // handle height when horizontal; handle width when vertical
    0.2, // edge up and left resize bar width : top resize bar width = 1 : 5
    35, // green move button width and height
    2, // button margin
);

/*
this method creates an element for you
which you don't need to pass in a selected element

to manipuate dom element
fp.container -> entire panel
fp.panel_el -> inside panel
*/
_x000D_
_x000D_
_x000D_

Achieving functionalities fully requires a lot of hard coding. Please refer to the documentation, it will show you how to use each class as element.

How to check if an element is off-screen

No need for a plugin to check if outside of view port.

var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
var d = $(document).scrollTop();

$.each($("div"),function(){
    p = $(this).position();
    //vertical
    if (p.top > h + d || p.top > h - d){
        console.log($(this))
    }
    //horizontal
    if (p.left < 0 - $(this).width() || p.left > w){
        console.log($(this))
    }
});

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

For me in Xcode 5.1 I was getting The entitlements specified in your application’s Code Signing Entitlements file do not match those specified in your provisioning profile. when trying to test the app on my device. Device Development Certificate has to expire Feb 2015.

Issue was resolved:

Selected Target->Capabilities, under GameCenter, here I was getting error on GameCenter entitlement as it was not added to project, although first version of application was released via same XCode 5.1 but there were no errors like this before.

Below, a button was given with title Fix Issue. When clicked it added the GameCenter entitlement and issue was resolved.

After wards the screen looks like:

enter image description here

For me, there was nothing to do with certificate. App now runs successfully on the device.

Why does Google prepend while(1); to their JSON responses?

Since the <script> tag is exempted from the Same Origin Policy which is a security necessity in the web world, while(1) when added to the JSON response prevents misuse of it in the <script> tag.

One command to create a directory and file inside it linux command

mkdir -p Python/Beginner/CH01 && touch $_/hello_world.py

Explanation: -p -> use -p if you wanna create parent and child directories $_ -> use it for current directory we work with it inline

How to use bitmask?

Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45

unsigned long alpha = 0x45
unsigned long pixel = 0x12345678;
pixel = ((pixel & 0x00FFFFFF) | (alpha << 24));

The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel.

How do I add a linker or compile flag in a CMake file?

The preferred way to specify toolchain-specific options is using CMake's toolchain facility. This ensures that there is a clean division between:

  • instructions on how to organise source files into targets -- expressed in CMakeLists.txt files, entirely toolchain-agnostic; and
  • details of how certain toolchains should be configured -- separated into CMake script files, extensible by future users of your project, scalable.

Ideally, there should be no compiler/linker flags in your CMakeLists.txt files -- even within if/endif blocks. And your program should build for the native platform with the default toolchain (e.g. GCC on GNU/Linux or MSVC on Windows) without any additional flags.

Steps to add a toolchain:

  1. Create a file, e.g. arm-linux-androideadi-gcc.cmake with global toolchain settings:

    set(CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++)
    set(CMAKE_CXX_FLAGS_INIT "-fexceptions")
    

    (You can find an example Linux cross-compiling toolchain file here.)

  2. When you want to generate a build system with this toolchain, specify the CMAKE_TOOLCHAIN_FILE parameter on the command line:

    mkdir android-arm-build && cd android-arm-build
    cmake -DCMAKE_TOOLCHAIN_FILE=$(pwd)/../arm-linux-androideadi-gcc.cmake ..
    

    (Note: you cannot use a relative path.)

  3. Build as normal:

    cmake --build .
    

Toolchain files make cross-compilation easier, but they have other uses:

  • Hardened diagnostics for your unit tests.

    set(CMAKE_CXX_FLAGS_INIT "-Werror -Wall -Wextra -Wpedantic")
    
  • Tricky-to-configure development tools.

    # toolchain file for use with gcov
    set(CMAKE_CXX_FLAGS_INIT "--coverage -fno-exceptions -g")
    
  • Enhanced safety checks.

    # toolchain file for use with gdb
    set(CMAKE_CXX_FLAGS_DEBUG_INIT "-fsanitize=address,undefined -fsanitize-undefined-trap-on-error")
    set(CMAKE_EXE_LINKER_FLAGS_INIT "-fsanitize=address,undefined -static-libasan")
    

Cross browser JavaScript (not jQuery...) scroll to top animation

function scrollTo(element, to, duration) {
    if (duration <= 0) return;
    var difference = to - element.scrollTop;
    var perTick = difference / duration * 10;

    setTimeout(function() {
        element.scrollTop = element.scrollTop + perTick;
        if (element.scrollTop === to) return;
        scrollTo(element, to, duration - 10);
    }, 10);
}

Demo:

_x000D_
_x000D_
function runScroll() {_x000D_
  scrollTo(document.body, 0, 600);_x000D_
}_x000D_
var scrollme;_x000D_
scrollme = document.querySelector("#scrollme");_x000D_
scrollme.addEventListener("click",runScroll,false)_x000D_
_x000D_
function scrollTo(element, to, duration) {_x000D_
  if (duration <= 0) return;_x000D_
  var difference = to - element.scrollTop;_x000D_
  var perTick = difference / duration * 10;_x000D_
_x000D_
  setTimeout(function() {_x000D_
    element.scrollTop = element.scrollTop + perTick;_x000D_
    if (element.scrollTop == to) return;_x000D_
    scrollTo(element, to, duration - 10);_x000D_
  }, 10);_x000D_
}
_x000D_
<p>Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page._x000D_
</p>_x000D_
<button id=scrollme type="button">To the top</button>
_x000D_
_x000D_
_x000D_

Unsafe JavaScript attempt to access frame with URL

I was getting the same error message when I tried to change the domain for iframe.src.

For me, the answer was to change the iframe.src to a url on the same domain, but which was actually an html re-direct page to the desired domain. The other domain then showed up in my iframe without any errors.

Worked like a charm.:)

How do I get AWS_ACCESS_KEY_ID for Amazon?

Amazon changes the admin console from time to time, hence the previous answers above are irrelevant in 2020.

The way to get the secret access key (Oct.2020) is:

  1. go to IAM console: https://console.aws.amazon.com/iam
  2. click on "Users". (see image) enter image description here
  3. go to the user you need his access key. enter image description here

As i see the answers above, I can assume my answer will become irrelevant in a year max :-)

HTH

Git branching: master vs. origin/master vs. remotes/origin/master

One clarification (and a point that confused me):

"remotes/origin/HEAD is the default branch" is not really correct.

remotes/origin/master was the default branch in the remote repository (last time you checked). HEAD is not a branch, it just points to a branch.

Think of HEAD as your working area. When you think of it this way then 'git checkout branchname' makes sense with respect to changing your working area files to be that of a particular branch. You "checkout" branch files into your working area. HEAD for all practical purposes is what is visible to you in your working area.

String comparison in bash. [[: not found

If you know you're on bash, and still get this error, make sure you write the if with spaces.

[[1==1]] # This outputs error

[[ 1==1 ]] # OK

Checking if my Windows application is running

The recommended way is to use a Mutex. You can check out a sample here : http://www.codeproject.com/KB/cs/singleinstance.aspx

In specific the code:


        /// 
        /// check if given exe alread running or not
        /// 
        /// returns true if already running
        private static bool IsAlreadyRunning()
        {
            string strLoc = Assembly.GetExecutingAssembly().Location;
            FileSystemInfo fileInfo = new FileInfo(strLoc);
            string sExeName = fileInfo.Name;
            bool bCreatedNew;

            Mutex mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew);
            if (bCreatedNew)
                mutex.ReleaseMutex();

            return !bCreatedNew;
        }

How to open .mov format video in HTML video Tag?

My new answer is to use ffmpeg to transcode the .mov like ffmpeg -i sourceFile.mov destinationFile.mp4. Do same for the webm format.

OLD Answer: Here's what you do:

  1. Upload your video to Youtube.
  2. Install the "Complete YouTube Saver" plugin for Firefox
  3. Using the plugin in Firefox, download both the MP4 and WEBM formats and place them on your Web server
  4. Add the HTML5 Video element to your webpage per MDN's recommendation
<video controls>
  <source src="somevideo.webm" type="video/webm">
  <source src="somevideo.mp4" type="video/mp4">
  I'm sorry; your browser doesn't support HTML5 video in WebM with VP8/VP9 or MP4 with H.264.
  <!-- You can embed a Flash player here, to play your mp4 video in older browsers -->
</video>
  1. Style the <video> element with CSS to suit your needs. For example Materializecss has a simple helper class to render the video nicely across device types.

Change a Django form field to a hidden field

If you have a custom template and view you may exclude the field and use {{ modelform.instance.field }} to get the value.

also you may prefer to use in the view:

form.fields['field_name'].widget = forms.HiddenInput()

but I'm not sure it will protect save method on post.

Hope it helps.

How can I specify a branch/tag when adding a Git submodule?

Git 1.8.2 added the possibility to track branches.

# add submodule to track branch_name branch
git submodule add -b branch_name URL_to_Git_repo optional_directory_rename

# update your submodule
git submodule update --remote 

See also Git submodules

Why is the Java main method static?

static indicates that this method is class method.and called without requirment of any object of class.

Creating a dynamic choice field

If you need a dynamic choice field in django admin; This works for django >=2.1.

class CarAdminForm(forms.ModelForm):
    class Meta:
        model = Car

    def __init__(self, *args, **kwargs):
        super(CarForm, self).__init__(*args, **kwargs)

        # Now you can make it dynamic.
        choices = (
            ('audi', 'Audi'),
            ('tesla', 'Tesla')
        )

        self.fields.get('car_field').choices = choices

    car_field = forms.ChoiceField(choices=[])

@admin.register(Car)
class CarAdmin(admin.ModelAdmin):
    form = CarAdminForm

Hope this helps.

JavaScript implementation of Gzip

I guess a generic client-side JavaScript compression implementation would be a very expensive operation in terms of processing time as opposed to transfer time of a few more HTTP packets with uncompressed payload.

Have you done any testing that would give you an idea how much time there is to save? I mean, bandwidth savings can't be what you're after, or can it?

Webpack how to build production code and how to use it

After observing number of viewers to this question I decided to conclude an answer from Vikramaditya and Sandeep.

To build the production code the first thing you have to create is production configuration with optimization packages like,

  new webpack.optimize.CommonsChunkPlugin('common.js'),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin(),
  new webpack.optimize.AggressiveMergingPlugin()

Then in the package.json file you can configure the build procedure with this production configuration

"scripts": {
    "build": "NODE_ENV=production webpack --config ./webpack.production.config.js"
},

now you have to run the following command to initiate the build

npm run build

As per my production build configuration webpack will build the source to ./dist directory.

Now your UI code will be available in ./dist/ directory. Configure your server to serve these files as static assets. Done!

Update value of a nested dictionary of varying depth

def update(value, nvalue):
    if not isinstance(value, dict) or not isinstance(nvalue, dict):
        return nvalue
    for k, v in nvalue.items():
        value.setdefault(k, dict())
        if isinstance(v, dict):
            v = update(value[k], v)
        value[k] = v
    return value

use dict or collections.Mapping

How to get duration, as int milli's and float seconds from <chrono>?

Is this what you're looking for?

#include <chrono>
#include <iostream>

int main()
{
    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::milliseconds ms;
    typedef std::chrono::duration<float> fsec;
    auto t0 = Time::now();
    auto t1 = Time::now();
    fsec fs = t1 - t0;
    ms d = std::chrono::duration_cast<ms>(fs);
    std::cout << fs.count() << "s\n";
    std::cout << d.count() << "ms\n";
}

which for me prints out:

6.5e-08s
0ms

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

You haven't started the bundler yet. Run npm start or react-native start in the root directory of your project before react-native run-android.

Insert picture/table in R Markdown

Several sites provide reasonable cheat sheets or HOWTOs for tables and images. Top on my list are:

Pictures are very simple to use but do not offer the ability to adjust the image to fit the page (see Update, below). To adjust the image properties (size, resolution, colors, border, etc), you'll need some form of image editor. I find I can do everything I need with one of ImageMagick, GIMP, or InkScape, all free and open source.

To add a picture, use:

![Caption for the picture.](/path/to/image.png)

I know pandoc supports PNG and JPG, which should meet most of your needs.

You do have control over image size if you are creating it in R (e.g., a plot). This can be done either directly in the command to create the image or, even better, via options if you are using knitr (highly recommended ... check out chunk options, specifically under Plots).

I strongly recommend perusing these tutorials; markdown is very handy and has many features most people don't use on a regular basis but really like once they learn it. (SO is not necessarily the best place to ask questions that are answered very directly in these tutorials.)


Update, 2019-Aug-31

Some time ago, pandoc incorporated "link_attributes" for images (apparently in 2015, with commit jgm/pandoc#244cd56). "Resizing images" can be done directly. For example:

![unchanged image](foo.jpg)
![much-smaller image](foo.jpg){#id .class width=30 height=20px}
![half-size image](foo.jpg){#id .class width=50% height=50%}

The dimensions can be provided with no units (pixels assumed), or with "px, cm, mm, in, inch and %" (ref: https://pandoc.org/MANUAL.html, search for link_attributes).

(I'm not certain that CommonMark has implemented this, though there was a lengthy discussion.)

How to run a hello.js file in Node.js on windows?

WinXp: I have created a .bat file

node c:\path\to\file\my_program.js

That just run my_program.bat from Explorer or in cmd window

Getting text from td cells with jQuery

$(".field-group_name").each(function() {
        console.log($(this).text());
    });

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

Use SELECT inside an UPDATE query

Does this work? Untested but should get the point across.

UPDATE FUNCTIONS
SET Func_TaxRef = 
(
  SELECT Min(TAX.Tax_Code) AS MinOfTax_Code
  FROM TAX, FUNCTIONS F1
  WHERE F1.Func_Pure <= [Tax_ToPrice]
    AND F1.Func_Year=[Tax_Year]
    AND F1.Func_ID = FUNCTIONS.Func_ID
  GROUP BY F1.Func_ID;
)

Basically for each row in FUNCTIONS, the subquery determines the minimum current tax code and sets FUNCTIONS.Func_TaxRef to that value. This is assuming that FUNCTIONS.Func_ID is a Primary or Unique key.

PHP foreach loop through multidimensional array

<?php
$first = reset($arr_nav); // Get the first element
$last  = end($arr_nav);   // Get the last element
// Ensure that we have a first element and that it's an array
if(is_array($first)) { 
   $first['class'] = 'first';
}
// Ensure we have a last element and that it differs from the first
if(is_array($last) && $last !== $first) {
   $last['class'] = 'last';
}

Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.

How to use template module with different set of variables?

With Ansible 2.x you can use vars: with tasks.

Template test.j2:

mkdir -p {{myTemplateVariable}}

Playbook:

- template: src=test.j2 dest=/tmp/File1
  vars:
    myTemplateVariable: myDirName

- template: src=test.j2 dest=/tmp/File2
  vars:
    myTemplateVariable: myOtherDir

This will pass different myTemplateVariable values into test.j2.

How to change value of object which is inside an array using JavaScript or jQuery?

This is another answer involving find. This relies on the fact that find:

  • iterates through every object in the array UNTIL a match is found
  • each object is provided to you and is MODIFIABLE

Here's the critical Javascript snippet:

projects.find( function (p) {
    if (p.value !== 'jquery-ui') return false;
    p.desc = 'your value';
    return true;
} );

Here's an alternate version of the same Javascript:

projects.find( function (p) {
    if (p.value === 'jquery-ui') {
        p.desc = 'your value';
        return true;
    }
    return false;
} );

Here's an even shorter (and somewhat more evil version):

projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );

Here's a full working version:

_x000D_
_x000D_
  var projects = [_x000D_
            {_x000D_
                value: "jquery",_x000D_
                label: "jQuery",_x000D_
                desc: "the write less, do more, JavaScript library",_x000D_
                icon: "jquery_32x32.png"_x000D_
            },_x000D_
            {_x000D_
                value: "jquery-ui",_x000D_
                label: "jQuery UI",_x000D_
                desc: "the official user interface library for jQuery",_x000D_
                icon: "jqueryui_32x32.png"_x000D_
            },_x000D_
            {_x000D_
                value: "sizzlejs",_x000D_
                label: "Sizzle JS",_x000D_
                desc: "a pure-JavaScript CSS selector engine",_x000D_
                icon: "sizzlejs_32x32.png"_x000D_
            }_x000D_
        ];_x000D_
_x000D_
projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );_x000D_
_x000D_
console.log( JSON.stringify( projects, undefined, 2 ) );
_x000D_
_x000D_
_x000D_

How do I find the duplicates in a list and create another list with them?

I am entering much much late in to this discussion. Even though, I would like to deal with this problem with one liners . Because that's the charm of Python. if we just want to get the duplicates in to a separate list (or any collection),I would suggest to do as below.Say we have a duplicated list which we can call as 'target'

    target=[1,2,3,4,4,4,3,5,6,8,4,3]

Now if we want to get the duplicates,we can use the one liner as below:

    duplicates=dict(set((x,target.count(x)) for x in filter(lambda rec : target.count(rec)>1,target)))

This code will put the duplicated records as key and count as value in to the dictionary 'duplicates'.'duplicate' dictionary will look like as below:

    {3: 3, 4: 4} #it saying 3 is repeated 3 times and 4 is 4 times

If you just want all the records with duplicates alone in a list, its again much shorter code:

    duplicates=filter(lambda rec : target.count(rec)>1,target)

Output will be:

    [3, 4, 4, 4, 3, 4, 3]

This works perfectly in python 2.7.x + versions

git with development, staging and production branches

Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!

https://twitter.com/Beanstalkapp/status/306129447885631488

Applications are expected to have a root view controller at the end of application launch

This occurred for me because i inadvertently commented out:

[self.window makeKeyAndVisible];

from

- (BOOL)application:(UIApplication*) didFinishLaunchingWithOptions:(NSDictionary*)

How do I check if an HTML element is empty using jQuery?

Here's a jQuery filter based on https://stackoverflow.com/a/6813294/698289

$.extend($.expr[':'], {
  trimmedEmpty: function(el) {
    return !$.trim($(el).html());
  }
});

Placing an image to the top right corner - CSS

You can just do it like this:

#content {
    position: relative;
}
#content img {
    position: absolute;
    top: 0px;
    right: 0px;
}

<div id="content">
    <img src="images/ribbon.png" class="ribbon"/>
    <div>some text...</div>
</div>

How can I keep Bootstrap popovers alive while being hovered?

I found that the accepted answer and the similar ones to it had some flaws. Mainly that it's repeatedly adding that mouseleave listener to the element.

I've combined their solution with some custom code to achieve the functionality in question without memory leaks or listener bloat.

    var getPopoverTimeout = function ($el) {
        return $el.data('timeout');
    }
    $element.popover({
        trigger: "manual",
        html: true,
        content: ...,
        title: ...,
        container: $element
     }).on("mouseenter", function () {
        var $this = $(this);
        if (!$this.find('.popover').length) {
            $this.popover("show");
        } else if (getPopoverTimeout($element)) {
            clearTimeout(getPopoverTimeout($element));
        }
    }).on("mouseleave", function () {
        var $this = $(this);
        $element.data('timeout', setTimeout(function () {
            if (!$(".popover:hover").length) {
                $this.popover("hide")
            }
        }, 250));
    });

Which provides a nice 'hover-intent' like solution so that it doesn't flash in and out.

How can I detect the touch event of an UIImageView?

A UIImageView is derived from a UIView which is derived from UIResponder so it's ready to handle touch events. You'll want to provide the touchesBegan, touchesMoved, and touchesEnded methods and they'll get called if the user taps the image. If all you want is a tap event, it's easier to just use a custom button with the image set as the button image. But if you want finer-grain control over taps, moves, etc. this is the way to go.

You'll also want to look at a few more things:

  • Override canBecomeFirstResponder and return YES to indicate that the view can become the focus of touch events (the default is NO).

  • Set the userInteractionEnabled property to YES. The default for UIViews is YES, but for UIImageViews is NO so you have to explicitly turn it on.

  • If you want to respond to multi-touch events (i.e. pinch, zoom, etc) you'll want to set multipleTouchEnabled to YES.

Print a div content using Jquery

I update this function
now you can print any tag or any part of the page with its full style
must include jquery.js file

HTML

<div id='DivIdToPrint'>
    <p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printtag("DivIdToPrint");' >

JavaScript

        function printtag(tagid) {
            var hashid = "#"+ tagid;
            var tagname =  $(hashid).prop("tagName").toLowerCase() ;
            var attributes = ""; 
            var attrs = document.getElementById(tagid).attributes;
              $.each(attrs,function(i,elem){
                attributes +=  " "+  elem.name+" ='"+elem.value+"' " ;
              })
            var divToPrint= $(hashid).html() ;
            var head = "<html><head>"+ $("head").html() + "</head>" ;
            var allcontent = head + "<body  onload='window.print()' >"+ "<" + tagname + attributes + ">" +  divToPrint + "</" + tagname + ">" +  "</body></html>"  ;
            var newWin=window.open('','Print-Window');
            newWin.document.open();
            newWin.document.write(allcontent);
            newWin.document.close();
           // setTimeout(function(){newWin.close();},10);
        }

Expected response code 220 but got code "", with message "" in Laravel

I did as per sid saying my env after updating is

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<mygmailaddress>
MAIL_PASSWORD=<gmailpassword>
MAIL_ENCRYPTION=tls

this did work without 2 step verification. with 2 step verification enabled it did not work for me.

Deactivate or remove the scrollbar on HTML

In HTML

<div style="overflow: hidden;">

in CSS

overflow: hidden;

you can also end scrolling for x or y separately

overflow-y: hidden; /* Hide vertical scrollbar */
  overflow-x: hidden; /* Hide horizontal scrollbar */

How can I check if my python object is a number?

Use Number from the numbers module to test isinstance(n, Number) (available since 2.6).

isinstance(n, numbers.Number)

Here it is in action with various kinds of numbers and one non-number:

>>> from numbers import Number
... from decimal import Decimal
... from fractions import Fraction
... for n in [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1), '2']:
...     print '%15s %s' % (n.__repr__(), isinstance(n, Number))
              2 True
            2.0 True
 Decimal('2.0') True
         (2+0j) True
 Fraction(2, 1) True
            '2' False

This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.

jsPDF multi page PDF with HTML renderer

var a = 0;
var d;
var increment;

for(n in array){
    d = a++;        

    if(n % 6 === 0 && n != 0){
        doc.addPage();
        a = 1;
        d = 0;
    }

    increment = d == 0 ? 10 : 50;
    size = (d * increment) <= 0 ? 10 : d * increment;

    doc.text(array[n], 10, size);
}

How to get Node.JS Express to listen only on localhost?

Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

Where value in column containing comma delimited values

Since you don't know how many comma-delimited entries you can find, you may need to create a function with 'charindex' and 'substring' SQL Server functions. Values, as returned by the function could be used in a 'in' expression.

You function can be recursively invoked or you can create loop, searching for entries until no more entries are present in the string. Every call to the function uses the previous found index as the starting point of the next call. The first call starts at 0.

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I found the answer to this problem here

Just do

mb_convert_encoding($data['name'], 'UTF-8', 'UTF-8');

How to concatenate int values in java?

This worked for me.

int i = 14;
int j = 26;
int k = Integer.valueOf(String.valueOf(i) + String.valueOf(j));
System.out.println(k);

It turned out as 1426

MySQL: Can't create table (errno: 150)

Make sure that the all tables can support foreign key - InnoDB engine

creating a random number using MYSQL

You could create a random number using FLOOR(RAND() * n) as randnum (n is an integer), however if you do not need the same random number to be repeated then you will have to somewhat store in a temp table. So you can check it against with where randnum not in (select * from temptable)...

How would I extract a single file (or changes to a file) from a git stash?

Edit: See cambunctious's answer, which is basically what I now prefer because it only uses the changes in the stash, rather than comparing them to your current state. This makes the operation additive, with much less chance of undoing work done since the stash was created.

To do it interactively, you would first do

git diff stash^! -- path/to/relevant/file/in/stash.ext perhaps/another/file.ext > my.patch

...then open the patch file in a text editor, alter as required, then do

git apply < my.patch

cambunctious's answer bypasses the interactivity by piping one command directly to the other, which is fine if you know you want all changes from the stash. You can edit the stash^! to be any commit range that has the cumulative changes you want (but check over the output of the diff first).

If applying the patch/diff fails, you can change the last command to git apply --reject which makes all the changes it can, and leaves .rej files where there are conflicts it can;r resolve. The .rej files can then be applied using wiggle, like so:

wiggle --replace path/to/relevant/file/in/stash.ext path/to/relevant/file/in/stash.ext.rej

This will either resolve the conflict, or give you conflict markers that you'd get from a merge.


Previous solution: There is an easy way to get changes from any branch, including stashes:

$ git checkout --patch stash@{0} path/to/file

You may omit the file spec if you want to patch in many parts. Or omit patch (but not the path) to get all changes to a single file. Replace 0 with the stash number from git stash list, if you have more than one. Note that this is like diff, and offers to apply all differences between the branches. To get changes from only a single commit/stash, have a look at git cherry-pick --no-commit.

Using jquery to get all checked checkboxes with a certain class name

<input type="checkbox" id="Checkbox1" class = "chk" value = "1" />
<input type="checkbox" id="Checkbox2" class = "chk" value = "2" />
<input type="checkbox" id="Checkbox3" class = "chk" value = "3" />
<input type="checkbox" id="Checkbox4" class = "chk" value = "4" />
<input type="button" id="demo" value = "Demo" />

<script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
    $("#demo").live("click", function () {
        $("input:checkbox[class=chk]:checked").each(function () {
            alert("Id: " + $(this).attr("id") + " Value: " + $(this).val());
        });
    });
</script>

http://www.jqueryfaqs.com/Articles/Get-values-of-all-checked-checkboxes-by-class-name-using-jQuery.aspx

Determining type of an object in ruby

variable_name.class

Here variable name is "a" a.class

What does -XX:MaxPermSize do?

The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name).

This Oracle article succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) :

The permanent generation does not have a noticeable impact on garbage collector performance for most applications. However, some applications dynamically generate and load many classes; for example, some implementations of JavaServer Pages (JSP) pages. These applications may need a larger permanent generation to hold the additional classes. If so, the maximum permanent generation size can be increased with the command-line option -XX:MaxPermSize=.

Note that this other Oracle documentation lists the other HotSpot arguments.

Update : Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.

What is a smart pointer and when should I use one?

Smart Pointers are those where you don't have to worry about Memory De-Allocation, Resource Sharing and Transfer.

You can very well use these pointer in the similar way as any allocation works in Java. In java Garbage Collector does the trick, while in Smart Pointers, the trick is done by Destructors.

Ignore Duplicates and Create New List of Unique Values in Excel

The MODERN approach is to consider cases where column of information come from a web service such as an OData source. If you need to generate a filter select fields off of massive data that has replicated values for the column, consider the code below:

var CatalogURL = getweb(currenturl)
                 +"/_api/web/lists/getbytitle('Site%20Inventory%20and%20Assets')/items?$select=Expense_x005F_x0020_Type&$orderby=Expense_x005F_x0020_Type";

/* the column that is replicated, is ordered by <column_name> */

    OData.read(CatalogURL,
        function(data,request){

            var myhtml ="";
            var myValue ="";

            for(var i = 0; i < data.results.length; i++)
            {
                myValue = data.results[i].Expense_x005F_x0020_Type;

                if(i == 0)
                {
                        myhtml += "<option value='"+myValue+"'>"+myValue+"</option>";
                }
                else
                if(myValue != data.results[i-1].Expense_x005F_x0020_Type)
                {
                        myhtml += "<option value='"+myValue+"'>"+myValue+"</option>";

                }
                else
                {

                }


            }

            $("#mySelect1").append(myhtml);

        });

Posting form to different MVC post action depending on the clicked submit button

You can choose the url where the form must be posted (and thus, the invoked action) in different ways, depending on the browser support:

In this way you don't need to do anything special on the server side.

Of course, you can use Url extensions methods in your Razor to specify the form action.

For browsers supporting HMTL5: simply define your submit buttons like this:

<input type='submit' value='...' formaction='@Url.Action(...)' />

For older browsers I recommend using an unobtrusive script like this (include it in your "master layout"):

$(document).on('click', '[type="submit"][data-form-action]', function (event) {
  var $this = $(this);
  var formAction = $this.attr('data-form-action');
  $this.closest('form').attr('action', formAction);
});

NOTE: This script will handle the click for any element in the page that has type=submit and data-form-action attributes. When this happens, it takes the value of data-form-action attribute and set the containing form's action to the value of this attribute. As it's a delegated event, it will work even for HTML loaded using AJAX, without taking extra steps.

Then you simply have to add a data-form-action attribute with the desired action URL to your button, like this:

<input type='submit' data-form-action='@Url.Action(...)' value='...'/>

Note that clicking the button changes the form's action, and, right after that, the browser posts the form to the desired action.

As you can see, this requires no custom routing, you can use the standard Url extension methods, and you have nothing special to do in modern browsers.

How can I simulate an array variable in MySQL?

In MYSQL version after 5.7.x, you can use JSON type to store an array. You can get value of an array by a key via MYSQL.

Why does the arrow (->) operator in C exist?

Beyond historical (good and already reported) reasons, there's is also a little problem with operators precedence: dot operator has higher priority than star operator, so if you have struct containing pointer to struct containing pointer to struct... These two are equivalent:

(*(*(*a).b).c).d

a->b->c->d

But the second is clearly more readable. Arrow operator has the highest priority (just as dot) and associates left to right. I think this is clearer than use dot operator both for pointers to struct and struct, because we know the type from the expression without have to look at the declaration, that could even be in another file.

Sanitizing user input before adding it to the DOM in Javascript

You could use a simple regular expression to assert that the id only contains allowed characters, like so:

if(id.match(/^[0-9a-zA-Z]{1,16}$/)){
    //The id is fine
}
else{
    //The id is illegal
}

My example allows only alphanumerical characters, and strings of length 1 to 16, you should change it to match the type of ids that you use.

By the way, at line 6, the value property is missing a pair of quotes, an easy mistake to make when you quote on two levels.

I can't see your actual data flow, depending on context this check may not at all be needed, or it may not be enough. In order to make a proper security review we would need more information.

In general, about built in escape or sanitize functions, don't trust them blindly. You need to know exactly what they do, and you need to establish that that is actually what you need. If it is not what you need, the code your own, most of the time a simple whitelisting regex like the one I gave you works just fine.

Comparing chars in Java

It might be clearer written as a switch statement with fall through e.g.

switch (symbol){
    case 'A':
    case 'B':
      // Do stuff
      break;
     default:
}

Determine the number of lines within a text file

A viable option, and one that I have personally used, would be to add your own header to the first line of the file. I did this for a custom model format for my game. Basically, I have a tool that optimizes my .obj files, getting rid of the crap I don't need, converts them to a better layout, and then writes the total number of lines, faces, normals, vertices, and texture UVs on the very first line. That data is then used by various array buffers when the model is loaded.

This is also useful because you only need to loop through the file once to load it in, instead of once to count the lines, and again to read the data into your created buffers.

$watch'ing for data changes in an Angular directive

You need to enable deep object dirty checking. By default angular only checks the reference of the top level variable that you watch.

App.directive('d3Visualization', function() {
    return {
        restrict: 'E',
        scope: {
            val: '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('val', function(newValue, oldValue) {
                if (newValue)
                    console.log("I see a data change!");
            }, true);
        }
    }
});

see Scope. The third parameter of the $watch function enables deep dirty checking if it's set to true.

Take note that deep dirty checking is expensive. So if you just need to watch the children array instead of the whole data variable the watch the variable directly.

scope.$watch('val.children', function(newValue, oldValue) {}, true);

version 1.2.x introduced $watchCollection

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)

scope.$watchCollection('val.children', function(newValue, oldValue) {});

Find the max of two or more columns with pandas

@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy() (or .values for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.

For example, you can use ndarray.max() along the first axis.

# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
   A  B
0  1 -2
1  2  8
2  3  1

df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns, 
# df['C'] = df.values.max(1) 
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

If your data has NaNs, you will need numpy.nanmax:

df['C'] = np.nanmax(df.values, axis=1)
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

You can also use numpy.maximum.reduce. numpy.maximum is a ufunc (Universal Function), and every ufunc has a reduce:

df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

enter image description here

np.maximum.reduce and np.max appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).

The graph was generated using perfplot. Benchmarking code, for reference:

import pandas as pd
import perfplot

np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))

perfplot.show(
    setup=lambda n: pd.concat([df_] * n, ignore_index=True),
    kernels=[
        lambda df: df.assign(new=df.max(axis=1)),
        lambda df: df.assign(new=df.values.max(1)),
        lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
        lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
    ],
    labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
    n_range=[2**k for k in range(0, 15)],
    xlabel='N (* len(df))',
    logx=True,
    logy=True)

Excel function to make SQL-like queries on worksheet data?

One quick way to do this is to create a column with a formula that evaluates to true for the rows you care about and then filter for the value TRUE in that column.

Is there an upper bound to BigInteger?

The number is held in an int[] - the maximum size of an array is Integer.MAX_VALUE. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE.

Admittedly, this is implementation dependent, not part of the specification.


In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:

BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range.

Implementation note: BigInteger constructors and operations throw ArithmeticException when the result is out of the supported range of -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive).

How do I reformat HTML code using Sublime Text 2?

The only package I've been able to find is Tag.

You can install it using the package control. https://sublime.wbond.net

After installing package control. Go to package control (Preferences -> Package Control) then type install, hit enter. Then type tag and hit enter.

After installing Tag, highlight the text and press the shortcut Ctrl+Alt+F.

GCC -fPIC option

A minor addition to the answers already posted: object files not compiled to be position independent are relocatable; they contain relocation table entries.

These entries allow the loader (that bit of code that loads a program into memory) to rewrite the absolute addresses to adjust for the actual load address in the virtual address space.

An operating system will try to share a single copy of a "shared object library" loaded into memory with all the programs that are linked to that same shared object library.

Since the code address space (unlike sections of the data space) need not be contiguous, and because most programs that link to a specific library have a fairly fixed library dependency tree, this succeeds most of the time. In those rare cases where there is a discrepancy, yes, it may be necessary to have two or more copies of a shared object library in memory.

Obviously, any attempt to randomize the load address of a library between programs and/or program instances (so as to reduce the possibility of creating an exploitable pattern) will make such cases common, not rare, so where a system has enabled this capability, one should make every attempt to compile all shared object libraries to be position independent.

Since calls into these libraries from the body of the main program will also be made relocatable, this makes it much less likely that a shared library will have to be copied.

JQuery style display value

Well, for one thing your epression can be simplified:

$("#pDetails").attr("style")

since there should only be one element for any given ID and the ID selector will be much faster than the attribute id selector you're using.

If you just want to return the display value or something, use css():

$("#pDetails").css("display")

If you want to search for elements that have display none, that's a lot harder to do reliably. This is a rough example that won't be 100%:

$("[style*='display: none']")

but if you just want to find things that are hidden, use this:

$(":hidden")

"register" keyword in C?

Storytime!

C, as a language, is an abstraction of a computer. It allows you to do things, in terms of what a computer does, that is manipulate memory, do math, print things, etc.

But C is only an abstraction. And ultimately, what it's extracting from you is Assembly language. Assembly is the language that a CPU reads, and if you use it, you do things in terms of the CPU. What does a CPU do? Basically, it reads from memory, does math, and writes to memory. The CPU doesn't just do math on numbers in memory. First, you have to move a number from memory to memory inside the CPU called a register. Once you're done doing whatever you need to do to this number, you can move it back to normal system memory. Why use system memory at all? Registers are limited in number. You only get about a hundred bytes in modern processors, and older popular processors were even more fantastically limited (The 6502 had 3 8-bit registers for your free use). So, your average math operation looks like:

load first number from memory
load second number from memory
add the two
store answer into memory

A lot of that is... not math. Those load and store operations can take up to half your processing time. C, being an abstraction of computers, freed the programmer the worry of using and juggling registers, and since the number and type vary between computers, C places the responsibility of register allocation solely on the compiler. With one exception.

When you declare a variable register, you are telling the compiler "Yo, I intend for this variable to be used a lot and/or be short lived. If I were you, I'd try to keep it in a register." When the C standard says compilers don't have to actually do anything, that's because the C standard doesn't know what computer you're compiling for, and it might be like the 6502 above, where all 3 registers are needed just to operate, and there's no spare register to keep your number. However, when it says you can't take the address, that's because registers don't have addresses. They're the processor's hands. Since the compiler doesn't have to give you an address, and since it can't have an address at all ever, several optimizations are now open to the compiler. It could, say, keep the number in a register always. It doesn't have to worry about where it's stored in computer memory (beyond needing to get it back again). It could even pun it into another variable, give it to another processor, give it a changing location, etc.

tl;dr: Short-lived variables that do lots of math. Don't declare too many at once.

Do I really need to encode '&' as '&amp;'?

Validation aside, the fact remains that encoding certain characters is important to an HTML document so that it can render properly and safely as a web page.

Encoding & as &amp; under all circumstances, for me, is an easier rule to live by, reducing the likelihood of errors and failures.

Compare the following: which is easier? which is easier to bugger up?

Methodology 1

  1. Write some content which includes ampersand characters.
  2. Encode them all.

Methodology 2

(with a grain of salt, please ;) )

  1. Write some content which includes a ampersand characters.
  2. On a case-by-case basis, look at each ampersand. Determine if:
    • It is isolated, and as such unambiguously an ampersand. eg. volt & amp
       > In that case don't bother encoding it.
    • It is not isolated, but you feel it is nonetheless unambiguous, as the resulting entity does not exist and will never exist since the entity list could never evolve. eg amp&volt
       > In that case don't bother encoding it.
    • It is not isolated, and ambiguous. eg. volt&amp
       > Encode it.

??

Pointer to a string in C?

The same notation is used for pointing at a single character or the first character of a null-terminated string:

char c = 'Z';
char a[] = "Hello world";

char *ptr1 = &c;
char *ptr2 = a;      // Points to the 'H' of "Hello world"
char *ptr3 = &a[0];  // Also points to the 'H' of "Hello world"
char *ptr4 = &a[6];  // Points to the 'w' of "world"
char *ptr5 = a + 6;  // Also points to the 'w' of "world"

The values in ptr2 and ptr3 are the same; so are the values in ptr4 and ptr5. If you're going to treat some data as a string, it is important to make sure it is null terminated, and that you know how much space there is for you to use. Many problems are caused by not understanding what space is available and not knowing whether the string was properly null terminated.

Note that all the pointers above can be dereferenced as if they were an array:

 *ptr1    == 'Z'
  ptr1[0] == 'Z'

 *ptr2    == 'H'
  ptr2[0] == 'H'
  ptr2[4] == 'o'

 *ptr4    == 'w'
  ptr4[0] == 'w'
  ptr4[4] == 'd'

  ptr5[0] ==   ptr3[6]
*(ptr5+0) == *(ptr3+6)

Late addition to question

What does char (*ptr)[N]; represent?

This is a more complex beastie altogether. It is a pointer to an array of N characters. The type is quite different; the way it is used is quite different; the size of the object pointed to is quite different.

char (*ptr)[12] = &a;

(*ptr)[0] == 'H'
(*ptr)[6] == 'w'

*(*ptr + 6) == 'w'

Note that ptr + 1 points to undefined territory, but points 'one array of 12 bytes' beyond the start of a. Given a slightly different scenario:

char b[3][12] = { "Hello world", "Farewell", "Au revoir" };

char (*pb)[12] = &b[0];

Now:

(*(pb+0))[0] == 'H'
(*(pb+1))[0] == 'F'
(*(pb+2))[5] == 'v'

You probably won't come across pointers to arrays except by accident for quite some time; I've used them a few times in the last 25 years, but so few that I can count the occasions on the fingers of one hand (and several of those have been answering questions on Stack Overflow). Beyond knowing that they exist, that they are the result of taking the address of an array, and that you probably didn't want it, you don't really need to know more about pointers to arrays.

Can't connect to local MySQL server through socket '/tmp/mysql.sock

The relevant section of the MySQL manual is here. I'd start by going through the debugging steps listed there.

Also, remember that localhost and 127.0.0.1 are not the same thing in this context:

  • If host is set to localhost, then a socket or pipe is used.
  • If host is set to 127.0.0.1, then the client is forced to use TCP/IP.

So, for example, you can check if your database is listening for TCP connections vi netstat -nlp. It seems likely that it IS listening for TCP connections because you say that mysql -h 127.0.0.1 works just fine. To check if you can connect to your database via sockets, use mysql -h localhost.

If none of this helps, then you probably need to post more details about your MySQL config, exactly how you're instantiating the connection, etc.

Consider defining a bean of type 'service' in your configuration [Spring boot]

@SpringBootApplication @ComponentScan(basePackages = {"io.testapi"})

In the main class below springbootapplication annotation i have written componentscan and it worked for me.

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Correct Method is

.PopupPanel
{
    border: solid 1px black;
    position: fixed;
    left: 50%;
    top: 50%;
    background-color: white;
    z-index: 100;
    height: 400px;
    margin-top: -200px;

    width: 600px;
    margin-left: -300px;
}

Android: How to Programmatically set the size of a Layout

my sample code

wv = (WebView) findViewById(R.id.mywebview);
wv.getLayoutParams().height = LayoutParams.MATCH_PARENT; // LayoutParams: android.view.ViewGroup.LayoutParams
// wv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
wv.requestLayout();//It is necesary to refresh the screen

Detecting superfluous #includes in C/C++?

There is a free tool Include File Dependencies Watcher which can be integrated in the visual studio. It shows superfluous #includes in red.

How to get "their" changes in the middle of conflicting Git rebase?

You want to use:

git checkout --ours foo/bar.java
git add foo/bar.java

If you rebase a branch feature_x against main (i.e. running git rebase main while on branch feature_x), during rebasing ours refers to main and theirs to feature_x.

As pointed out in the git-rebase docs:

Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.

For further details read this thread.

How to round down to nearest integer in MySQL?

SUBSTR will be better than FLOOR in some cases because FLOOR has a "bug" as follow:

SELECT 25 * 9.54 + 0.5 -> 239.00

SELECT FLOOR(25 * 9.54 + 0.5) -> 238  (oops!)

SELECT SUBSTR((25*9.54+0.5),1,LOCATE('.',(25*9.54+0.5)) - 1) -> 239

How to query MongoDB with "like"?

Regex are expensive are process.

Another way is to create an index of text and then search it using $search.

Create a text Index of fields you want to make searchable:

db.collection.createIndex({name: 'text', otherField: 'text'});

Search for a string in text index:

db.collection.find({
  '$text'=>{'$search': "The string"}
})

Setting focus to iframe contents

i had a similar problem where i was trying to focus on a txt area in an iframe loaded from another page. in most cases it work. There was an issue where it would fire in FF when the iFrame was loaded but before it was visible. so the focus never seemed to be set correctly.

i worked around this with a simular solution to cheeming's answer above

    var iframeID = document.getElementById("modalIFrame"); 
//focus the IFRAME element 
$(iframeID).focus(); 
//use JQuery to find the control in the IFRAME and set focus 
$(iframeID).contents().find("#emailTxt").focus(); 

Append an empty row in dataframe using pandas

Assuming df is your dataframe,

df_prime = pd.concat([df, pd.DataFrame([[np.nan] * df.shape[1]], columns=df.columns)], ignore_index=True)

where df_prime equals df with an additional last row of NaN's.

Note that pd.concat is slow so if you need this functionality in a loop, it's best to avoid using it. In that case, assuming your index is incremental, you can use

df.loc[df.iloc[-1].name + 1,:] = np.nan

Hibernate Annotations - Which is better, field or property access?

To make your classes cleaner, put the annotation in the field then use @Access(AccessType.PROPERTY)

Copy data from one column to other column (which is in a different table)

A similar question's answer worked more correctly for me than this question's selected answer (by Mark Byers). Using Mark's answer, my updated column got the same value in all the rows (perhaps the value from the first row that matched the join). Using ParveenaArora's answer from the other thread updated the column with the correct values.

Transforming Parveena's solution to use this question' table and column names, the query would be as follows (where I assume the tables are related through tblindiantime.contact_id):

UPDATE tblindiantime
SET CountryName = contacts.BusinessCountry
FROM contacts
WHERE tblindiantime.contact_id = contacts.id;

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

There is no difference in terms of functionality


The addwithvalue method takes an object as the value. There is no type data type checking. Potentially, that could lead to error if data type does not match with SQL table. The add method requires that you specify the Database type first. This helps to reduce such errors.

For more detail Please click here

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}

How do I get rid of the "cannot empty the clipboard" error?

Are you running Skype? This has been the best solution I have found to get rid of the "cannot empty the clipboard error" in Excel 2007 & 2010. Delete the Skype add-on in IE and/or Firefox and good-bye annoying error!

In reply to rjacobs7 post on February 28, 2011

Cannot clear clipboard error - Windows 7, Excel 2010 - This error occurs nearly every time a drag and drop of cell contents is attempted. I've had this same error over the past 10 years on older computers and older versions of Windows and Office. It has now reoccurred with a new laptop running Windows 7 64 bit and Office 2010. The issue can be replicated only if a browser - IE or Firefox - is open at the same time that Excel is open. Having Word and/or Outlook open at the same time will not cause the problem to occur unless a browser is also open. This error is extremely irritating and no solutions from Microsoft or other posts on this issue resolve it.

I have a solution - at least for me! Delete the Skype add-in in IE and Firefox and the "cannot clear clipboard" error after a drag and drop goes away when IE and/or Firefox are running. Apparently some sort of memory-management issue with Skype, Office and the browsers.

Create two threads, one display odd & other even numbers

package com.example;

public class MyClass  {
    static int mycount=0;
    static Thread t;
    static Thread t2;
    public static void main(String[] arg)
    {
        t2=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " even \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>25)
                    System.exit(0);
                run();
            }
        });
        t=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " odd \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>26)
                    System.exit(0);
                run();
            }
        });
        t.start();
        t2.start();
    }
}

For Restful API, can GET method use json data?

In theory, there's nothing preventing you from sending a request body in a GET request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.

However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.

The simple option is to use POST instead of GET as recommended by other answers. Since POST is not standardized by HTTP, you'll have to document how exactly that's supposed to work.

Another option, which I prefer, is to implement your application assuming the GET payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override, which is a popular convention for clients to emulate HTTP methods with POST. So, if a client has a broken implementation, it can write the GET request as a POST, sending the X-HTTP-Method-Override: GET method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.

How to send a simple string between two programs using pipes?

dup2( STDIN_FILENO, newfd )

And read:

char reading[ 1025 ];
int fdin = 0, r_control;
if( dup2( STDIN_FILENO, fdin ) < 0 ){
    perror( "dup2(  )" );
    exit( errno );
}
memset( reading, '\0', 1025 );
while( ( r_control = read( fdin, reading, 1024 ) ) > 0 ){
    printf( "<%s>", reading );
    memset( reading, '\0', 1025 );
}
if( r_control < 0 )
    perror( "read(  )" );    
close( fdin );    

But, I think that fcntl can be a better solution

echo "salut" | code

Good examples of python-memcache (memcached) being used in Python?

A good rule of thumb: use the built-in help system in Python. Example below...

jdoe@server:~$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'memcache']
>>> help(memcache)

------------------------------------------
NAME
    memcache - client module for memcached (memory cache daemon)

FILE
    /usr/lib/python2.7/dist-packages/memcache.py

MODULE DOCS
    http://docs.python.org/library/memcache

DESCRIPTION
    Overview
    ========

    See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

    Usage summary
    =============
...
------------------------------------------

Create an empty list in python with certain size

(This was written based on the original version of the question.)

I want to create a empty list (or whatever is the best way) can hold 10 elements.

All lists can hold as many elements as you like, subject only to the limit of available memory. The only "size" of a list that matters is the number of elements currently in it.

but when I run it, the result is []

print display s1 is not valid syntax; based on your description of what you're seeing, I assume you meant display(s1) and then print s1. For that to run, you must have previously defined a global s1 to pass into the function.

Calling display does not modify the list you pass in, as written. Your code says "s1 is a name for whatever thing was passed in to the function; ok, now the first thing we'll do is forget about that thing completely, and let s1 start referring instead to a newly created list. Now we'll modify that list". This has no effect on the value you passed in.

There is no reason to pass in a value here. (There is no real reason to create a function, either, but that's beside the point.) You want to "create" something, so that is the output of your function. No information is required to create the thing you describe, so don't pass any information in. To get information out, return it.

That would give you something like:

def display():
    s1 = list();
    for i in range(0, 9):
        s1[i] = i
    return s1

The next problem you will note is that your list will actually have only 9 elements, because the end point is skipped by the range function. (As side notes, [] works just as well as list(), the semicolon is unnecessary, s1 is a poor name for the variable, and only one parameter is needed for range if you're starting from 0.) So then you end up with

def create_list():
    result = list()
    for i in range(10):
        result[i] = i
    return result

However, this is still missing the mark; range is not some magical keyword that's part of the language the way for and def are, but instead it's a function. And guess what that function returns? That's right - a list of those integers. So the entire function collapses to

def create_list():
    return range(10)

and now you see why we don't need to write a function ourselves at all; range is already the function we're looking for. Although, again, there is no need or reason to "pre-size" the list.

Stashing only staged changes in git - is it possible?

Yes, It's possible with DOUBLE STASH

  1. Stage all your files that you need to stash.
  2. Run git stash --keep-index. This command will create a stash with ALL of your changes (staged and unstaged), but will leave the staged changes in your working directory (still in state staged).
  3. Run git stash push -m "good stash"
  4. Now your "good stash" has ONLY staged files.

Now if you need unstaged files before stash, simply apply first stash (the one created with --keep-index) and now you can remove files you stashed to "good stash".

Enjoy

How do a LDAP search/authenticate against this LDAP in Java

You can also use the following code :

package com.agileinfotech.bsviewer.ldap;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPLoginAuthentication {
    public LDAPLoginAuthentication() {
        // TODO Auto-generated constructor
    }

    ResourceBundle resBundle = ResourceBundle.getBundle("settings");

    @SuppressWarnings("unchecked")
    public String authenticateUser(String username, String password) {
        String strUrl = "success";
        Hashtable env = new Hashtable(11);
        boolean b = false;
        String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
        env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
        env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
            // Close the context when we're done
            b = true;
            ctx.close();

        } catch (NamingException e) {
            b = false;
        } finally {
            if (b) {
                strUrl = "success";
            } else {
                strUrl = "failer";
            }
        }
        return strUrl;
    }
}

Standardize data columns in R

With dplyr v0.7.4 all variables can be scaled by using mutate_all():

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tibble)

set.seed(1234)
dat <- tibble(x = rnorm(10, 30, .2), 
              y = runif(10, 3, 5),
              z = runif(10, 10, 20))

dat %>% mutate_all(scale)
#> # A tibble: 10 x 3
#>         x      y       z
#>     <dbl>  <dbl>   <dbl>
#>  1 -0.827 -0.300 -0.0602
#>  2  0.663 -0.342 -0.725 
#>  3  1.47  -0.774 -0.588 
#>  4 -1.97  -1.13   0.118 
#>  5  0.816 -0.595 -1.02  
#>  6  0.893  1.19   0.998 
#>  7 -0.192  0.328 -0.948 
#>  8 -0.164  1.50  -0.748 
#>  9 -0.182  1.25   1.81  
#> 10 -0.509 -1.12   1.16

Specific variables can be excluded using mutate_at():

dat %>% mutate_at(scale, .vars = vars(-x))
#> # A tibble: 10 x 3
#>        x      y       z
#>    <dbl>  <dbl>   <dbl>
#>  1  29.8 -0.300 -0.0602
#>  2  30.1 -0.342 -0.725 
#>  3  30.2 -0.774 -0.588 
#>  4  29.5 -1.13   0.118 
#>  5  30.1 -0.595 -1.02  
#>  6  30.1  1.19   0.998 
#>  7  29.9  0.328 -0.948 
#>  8  29.9  1.50  -0.748 
#>  9  29.9  1.25   1.81  
#> 10  29.8 -1.12   1.16

Created on 2018-04-24 by the reprex package (v0.2.0).

Python element-wise tuple operations like sum

Here is another handy solution if you are already using numpy. It is compact and the addition operation can be replaced by any numpy expression.

import numpy as np
tuple(np.array(a) + b)

Show Hide div if, if statement is true

Probably the easiest to hide a div and show a div in PHP based on a variables and the operator.

<?php 
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
?>
<html>
<?php if($numrows > null){ ?>
     no meow :-(
<?php } ?>

<?php if($numrows < null){ ?>
     lots of meow
<?php } ?>
</html>

Here is my original code before adding your requirements:

<?php 
$address = 'meow';
?>
<?php if($address == null){ ?>
     no meow :-(
<?php } ?>

<?php if($address != null){ ?>
     lots of meow
<?php } ?>

How do I count unique visitors to my site?

Here is a nice tutorial, it is what you need. (Source: coursesweb.net/php-mysql)

Register and show online users and visitors

Count Online users and visitors using a MySQL table

In this tutorial you can learn how to register, to count, and display in your webpage the number of online users and visitors. The principle is this: each user / visitor is registered in a text file or database. Every time a page of the website is accessed, the php script deletes all records older than a certain time (eg 2 minutes), adds the current user / visitor and takes the number of records left to display.

You can store the online users and visitors in a file on the server, or in a MySQL table. In this case, I think that using a text file to add and read the records is faster than storing them into a MySQL table, which requires more requests.

First it's presented the method with recording in a text file on the server, than the method with MySQL table.

To download the files with the scripts presented in this tutorial, click -> Count Online Users and Visitors.

• Both scripts can be included in ".php" files (with include()), or in ".html" files (with <script>), as you can see in the examples presented at the bottom of this page; but the server must run PHP.

Storing online users and visitors in a text file

To add records in a file on the server with PHP you must set CHMOD 0766 (or CHMOD 0777) permissions to that file, so the PHP can write data in it.

  1. Create a text file on your server (for example, named userson.txt) and give it CHMOD 0777 permissions (in your FTP application, right click on that file, choose Properties, then select Read, Write, and Execute options).
  2. Create a PHP file (named usersontxt.php) having the code below, then copy this php file in the same directory as userson.txt.

The code for usersontxt.php;

<?php
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. If you want to include the script above in a ".php" file, add the following code in the place you want to show the number of online users and visitors:

4.To show the number of online visitors /users in a ".html" file, use this code:

<script type="text/javascript" src="usersontxt.php?uvon=showon"></script>

This script (and the other presented below) works with $_SESSION. At the beginning of the PHP file in which you use it, you must add: session_start();. Count Online users and visitors using a MySQL table

To register, count and show the number of online visitors and users in a MySQL table, require to perform three SQL queries: Delete the records older than a certain time. Insert a row with the new user /visitor, or, if it is already inserted, Update the timestamp in its column. Select the remaining rows. Here's the code for a script that uses a MySQL table (named "userson") to store and display the Online Users and Visitors.

  1. First we create the "userson" table, with 2 columns (uvon, dt). In the "uvon" column is stored the name of the user (if logged in) or the visitor's IP. In the "dt" column is stored a number with the timestamp (Unix time) when the page is accessed.
  • Add the following code in a php file (for example, named "create_userson.php"):

The code for create_userson.php:

<?php
header('Content-type: text/html; charset=utf-8');

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// check connection
if (mysqli_connect_errno()) exit('Connect failed: '. mysqli_connect_error());

// sql query for CREATE "userson" TABLE
$sql = "CREATE TABLE `userson` (
 `uvon` VARCHAR(32) PRIMARY KEY,
 `dt` INT(10) UNSIGNED NOT NULL
 ) CHARACTER SET utf8 COLLATE utf8_general_ci"; 

// Performs the $sql query on the server to create the table
if ($conn->query($sql) === TRUE) echo 'Table "userson" successfully created';
else echo 'Error: '. $conn->error;

$conn->close();
?>
  1. Now we create the script that Inserts, Deletes, and Selects data in the userson table (For explanations about the code, see the comments in script).
  • Add the code below in another php file (named usersmysql.php): In both file you must add your personal data for connecting to MySQL database, in the variables: $host, $user, $pass, and $dbname .

The code for usersmysql.php:

<?php
// Script Online Users and Visitors - coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();         // start Session, if not already started

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)
$vst_id = '-vst-';         // an identifier to know that it is a visitor, not logged user
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the rows with visitors
$dt = time();                                    // current timestamp
$timeon = 120;             // number of secconds to keep a user online
$nrvst = 0;                                     // to store the number of visitors
$nrusr = 0;                                     // to store the number of usersrs
$usron = '';                                    // to store the name of logged users

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// Define and execute the Delete, Insert/Update, and Select queries
$sqldel = "DELETE FROM `userson` WHERE `dt`<". ($dt - $timeon);
$sqliu = "INSERT INTO `userson` (`uvon`, `dt`) VALUES ('$uvon', $dt) ON DUPLICATE KEY UPDATE `dt`=$dt";
$sqlsel = "SELECT * FROM `userson`";

// Execute each query
if(!$conn->query($sqldel)) echo 'Error: '. $conn->error;
if(!$conn->query($sqliu)) echo 'Error: '. $conn->error;
$result = $conn->query($sqlsel);

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // traverse the sets of results and set the number of online visitors and users ($nrvst, $nrusr)
  while($row = $result->fetch_assoc()) {
    if(preg_match($rgxvst, $row['uvon'])) $nrvst++;       // increment the visitors
    else {
      $nrusr++;                   // increment the users
      $usron .= '<br/> - <i>'.$row['uvon']. '</i>';          // stores the user's name
    }
  }
}

$conn->close();                  // close the MySQL connection

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. ($nrusr+$nrvst). '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. After you have created these two php files on your server, run the "create_userson.php" on your browser to create the "userson" table.

  2. Include the usersmysql.php file in the php file in which you want to display the number of online users and visitors.

  3. Or, if you want to insert it in a ".html" file, add this code:

Examples using these scripts

• Including the "usersontxt.php` in a php file:

<!doctype html>

Counter Online Users and Visitors

• Including the "usersmysql.php" in a html file:

<!doctype html>
<html>
<head>
 <meta charset="utf-8" />
 <title>Counter Online Users and Visitors</title>
 <meta name="description" content="PHP script to count and show the number of online users and visitors" />
 <meta name="keywords" content="online users, online visitors" />
</head>
<body>

<!-- Includes the script ("usersontxt.php", or "usersmysql.php") -->
<script type="text/javascript" src="usersmysql.php?uvon=showon"></script>

</body>
</html>

Both scripts (with storing data in a text file on the server, or into a MySQL table) will display a result like this: Online: 5

Visitors: 3 Users: 2

  • MarPlo
  • Marius