Programs & Examples On #Search box

A search box or search field is a common GUI element used in computer programs

Add Twitter Bootstrap icon to Input box

For bootstrap 4

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

            <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
        <form class="form-inline my-2 my-lg-0">
                        <div class="input-group">
                            <input class="form-control" type="search" placeholder="Search">
                            <div class="input-group-append">
                                <div class="input-group-text"><i class="fa fa-search"></i></div>
                            </div>
                        </div>
                    </form>

Demo

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

Go to "Target" -> "Build Phases", select your target, select the “Build Phases” tab, click “Add Build Phase”, and select “Add Copy Files”. Change the destination to “Products Directory”. Drag your file into the “Add files” section.

Get the Id of current table row with Jquery

You can use .closest() to get up to the current <tr> parent, like this:

$('input[type=button]' ).click(function() {
   var bid = this.id; // button ID 
   var trid = $(this).closest('tr').attr('id'); // table row ID 
 });

How do I read CSV data into a record array in NumPy?

This work as a charm...

import csv
with open("data.csv", 'r') as f:
    data = list(csv.reader(f, delimiter=";"))

import numpy as np
data = np.array(data, dtype=np.float)

How to save LogCat contents to file?

In addition to answer by Dinesh Prajapati, Use

 adb -d logcat <your package name>:<log level>

where -d is for device and you may also choose -e instead for emulator log and log level is a/d/i/v/e/w etc.

Now your command goes like:

adb -d logcat com.example.example:V > logfileName_WithPath.txt

How to select the row with the maximum value in each group

If you want the biggest pt value for a subject, you could simply use:

   pt_max = as.data.frame(aggregate(pt~Subject, group, max))

Equation for testing if a point is inside a circle

In general, x and y must satisfy (x - center_x)^2 + (y - center_y)^2 < radius^2.

Please note that points that satisfy the above equation with < replaced by == are considered the points on the circle, and the points that satisfy the above equation with < replaced by > are considered the outside the circle.

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

when you are in El Capitan, will get error: ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted need to close the "System Integrity Protection".

first, reboot and hold on cmd + R to enter the Recovery mode, then launch the terminal and type the command: csrutil disable, now you can reboot and try again.

How to watch for array changes?

An interesting collection library is https://github.com/mgesmundo/smart-collection. Allows you to watch arrays and add views to them as well. Not sure about the performance as I am testing it out myself. Will update this post soon.

How to get the current time as datetime

Update for Swift 3:

let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)

I do this:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute

See the same question in objective-c How do I get hour and minutes from NSDate?

Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!

Best Practice to Use HttpClient in Multithreaded Environment

I think you will want to use ThreadSafeClientConnManager.

You can see how it works here: http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html

Or in the AndroidHttpClient which uses it internally.

How do you perform a left outer join using linq extension methods

You can create extension method like:

public static IEnumerable<TResult> LeftOuterJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source, IEnumerable<TInner> other, Func<TSource, TKey> func, Func<TInner, TKey> innerkey, Func<TSource, TInner, TResult> res)
    {
        return from f in source
               join b in other on func.Invoke(f) equals innerkey.Invoke(b) into g
               from result in g.DefaultIfEmpty()
               select res.Invoke(f, result);
    }

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

Convert XmlDocument to String

" is shown as \" in the debugger, but the data is correct in the string, and you don't need to replace anything. Try to dump your string to a file and you will note that the string is correct.

Nth word in a string variable

STRING=(one two three four)
echo "${STRING[n]}"

Install dependencies globally and locally using package.json

New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies section of your package.json. Anytime you use something from scripts in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.

For example:

npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally

Then in package.json:

// devDependencies has mocha and babel now

"scripts": {
  "test": "mocha",
  "build": "babel -d lib src",
  "prepublish": "babel -d lib src"
}

Then at your command prompt you can run:

npm run build # finds babel
npm test # finds mocha

npm publish # will run babel first

But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:

"scripts": {
  "preinstall": "npm i -g themodule"
}

So actually my npm install executes npm install again .. which is weird but seems to work.

Note: you might have issues if you are using the most common setup for npm where global Node package installs required sudo. One option is to change your npm configuration so this isn't necessary:

npm config set prefix ~/npm, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH to your ~/.bashrc.

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

C default arguments

No, but you might consider using a set of functions (or macros) to approximate using default args:

// No default args
int foo3(int a, int b, int c)
{
    return ...;
}

// Default 3rd arg
int foo2(int a, int b)
{
    return foo3(a, b, 0);  // default c
}

// Default 2nd and 3rd args
int foo1(int a)
{
    return foo3(a, 1, 0);  // default b and c
}

What tool can decompile a DLL into C++ source code?

This might be impossible or at least very hard. The DLL's contents don't depend (a lot) on it being written in C++; it's all machine code. That code might have been optimized so a lot of information that was present in the original source code is simply gone.

That said, here is one article that goes through a lot of material about doing this.

How to count check-boxes using jQuery?

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;

What do hjust and vjust do when making a plot using ggplot?

Probably the most definitive is Figure B.1(d) of the ggplot2 book, the appendices of which are available at http://ggplot2.org/book/appendices.pdf.

enter image description here

However, it is not quite that simple. hjust and vjust as described there are how it works in geom_text and theme_text (sometimes). One way to think of it is to think of a box around the text, and where the reference point is in relation to that box, in units relative to the size of the box (and thus different for texts of different size). An hjust of 0.5 and a vjust of 0.5 center the box on the reference point. Reducing hjust moves the box right by an amount of the box width times 0.5-hjust. Thus when hjust=0, the left edge of the box is at the reference point. Increasing hjust moves the box left by an amount of the box width times hjust-0.5. When hjust=1, the box is moved half a box width left from centered, which puts the right edge on the reference point. If hjust=2, the right edge of the box is a box width left of the reference point (center is 2-0.5=1.5 box widths left of the reference point. For vertical, less is up and more is down. This is effectively what that Figure B.1(d) says, but it extrapolates beyond [0,1].

But, sometimes this doesn't work. For example

DF <- data.frame(x=c("a","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p + opts(axis.text.x=theme_text(vjust=0))
p + opts(axis.text.x=theme_text(vjust=1))
p + opts(axis.text.x=theme_text(vjust=2))

The three latter plots are identical. I don't know why that is. Also, if text is rotated, then it is more complicated. Consider

p + opts(axis.text.x=theme_text(hjust=0, angle=90))
p + opts(axis.text.x=theme_text(hjust=0.5 angle=90))
p + opts(axis.text.x=theme_text(hjust=1, angle=90))
p + opts(axis.text.x=theme_text(hjust=2, angle=90))

The first has the labels left justified (against the bottom), the second has them centered in some box so their centers line up, and the third has them right justified (so their right sides line up next to the axis). The last one, well, I can't explain in a coherent way. It has something to do with the size of the text, the size of the widest text, and I'm not sure what else.

Table is marked as crashed and should be repaired

I had the same issue when my server free disk space available was 0

You can use the command (there must be ample space for the mysql files)

REPAIR TABLE `<table name>`;

for repairing individual tables

Date ticks and rotation in matplotlib

Solution works for matplotlib 2.1+

There exists an axes method tick_params that can change tick properties. It also exists as an axis method as set_tick_params

ax.tick_params(axis='x', rotation=45)

Or

ax.xaxis.set_tick_params(rotation=45)

As a side note, the current solution mixes the stateful interface (using pyplot) with the object-oriented interface by using the command plt.xticks(rotation=70). Since the code in the question uses the object-oriented approach, it's best to stick to that approach throughout. The solution does give a good explicit solution with plt.setp( axs[1].xaxis.get_majorticklabels(), rotation=70 )

How do I calculate percentiles with python/numpy?

You might be interested in the SciPy Stats package. It has the percentile function you're after and many other statistical goodies.

percentile() is available in numpy too.

import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) # return 50th percentile, e.g median.
print p
3.0

This ticket leads me to believe they won't be integrating percentile() into numpy anytime soon.

Scheduling recurring task in Android

I have created on time task in which the task which user wants to repeat, add in the Custom TimeTask run() method. it is successfully reoccurring.

 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.Timer;
 import java.util.TimerTask;

 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.CheckBox;
 import android.widget.TextView;
 import android.app.Activity;
 import android.content.Intent;

 public class MainActivity extends Activity {

     CheckBox optSingleShot;
     Button btnStart, btnCancel;
     TextView textCounter;

     Timer timer;
     MyTimerTask myTimerTask;

     int tobeShown = 0  ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    optSingleShot = (CheckBox)findViewById(R.id.singleshot);
    btnStart = (Button)findViewById(R.id.start);
    btnCancel = (Button)findViewById(R.id.cancel);
    textCounter = (TextView)findViewById(R.id.counter);
    tobeShown = 1;

    if(timer != null){
        timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
        //singleshot delay 1000 ms
        timer.schedule(myTimerTask, 1000);
    }else{
        //delay 1000ms, repeat in 5000ms
        timer.schedule(myTimerTask, 1000, 1000);
    }

    btnStart.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {


            Intent i = new Intent(MainActivity.this, ActivityB.class);
            startActivity(i);

            /*if(timer != null){
                timer.cancel();
            }

            //re-schedule timer here
            //otherwise, IllegalStateException of
            //"TimerTask is scheduled already" 
            //will be thrown
            timer = new Timer();
            myTimerTask = new MyTimerTask();

            if(optSingleShot.isChecked()){
                //singleshot delay 1000 ms
                timer.schedule(myTimerTask, 1000);
            }else{
                //delay 1000ms, repeat in 5000ms
                timer.schedule(myTimerTask, 1000, 1000);
            }*/
        }});

    btnCancel.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            if (timer!=null){
                timer.cancel();
                timer = null;
            }
        }
    });

}

@Override
protected void onResume() {
    super.onResume();

    if(timer != null){
        timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
        //singleshot delay 1000 ms
        timer.schedule(myTimerTask, 1000);
    }else{
        //delay 1000ms, repeat in 5000ms
        timer.schedule(myTimerTask, 1000, 1000);
    }
}


@Override
protected void onPause() {
    super.onPause();

    if (timer!=null){
        timer.cancel();
        timer = null;
    }

}

@Override
protected void onStop() {
    super.onStop();

    if (timer!=null){
        timer.cancel();
        timer = null;
    }

}

class MyTimerTask extends TimerTask {

    @Override
    public void run() {

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = 
                new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
        final String strDate = simpleDateFormat.format(calendar.getTime());

        runOnUiThread(new Runnable(){

            @Override
            public void run() {
                textCounter.setText(strDate);
            }});
    }
}

}

MVC 4 Razor adding input type date

 @Html.TextBoxFor(m => m.EntryDate, new{ type = "date" })

 or type = "time"

 it will display a calendar
 it will not work if you give @Html.EditorFor()

Should I make HTML Anchors with 'name' or 'id'?

How about using name attribute for old browsers and id attribute to the new browsers. Both options will be used and fallback method will be implemented by default!!!

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

Steps for Window10:

  • Go to https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python
  • Download the right version according to python version and hardware specs: for my case, mysqlclient-1.4.2-cp37-cp37m-win32.whl works for python3.7 and Intel CPU.
  • While your env is still activated, go to the download folder and run pip install mysqlclient-1.4.2-cp37-cp37m-win32.whl

How do I get the height of a div's full content with jQuery?

  1. Using scrollHeight is not only buggy, but doesn't work when your container has a hardcoded height (which is probably most cases, since you wanna get contents height without doing container.height() itself)
  2. @shazboticus-s-shazbot solution is good when you can mess around with the container height temporarily / have a hard-coded height.
  3. An alternative solution would be:

_x000D_
_x000D_
$('#outer')_x000D_
    // Get children in array format, as we'll be reducing them into a single number_x000D_
    .contents().toArray()_x000D_
    // Filter out text and comment nodes, only allowing tags_x000D_
    .filter(el => el.nodeType === 1)_x000D_
    // Sum up all the children individual heights_x000D_
    .reduce((accumulator, el) => $(el).outerHeight(true) + accumulator, 0);
_x000D_
_x000D_
_x000D_

Of course, this latter alternative only works when #outer doesn't have immediate text childrens that take up space and you want to measure. Those are my 2 cents.

  1. If you want to measure unwrapped text, I'd suggest modifying your DOM tree and having an inner <div> of which you can measure easily by doing $('#outer').children().height()

Rails 4: assets not loading in production

The default matcher for compiling files includes application.js, application.css and all non-JS/CSS files (this will include all image assets automatically) from app/assets folders including your gems:

If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the precompile array in config/initializers/assets.rb:

Rails.application.config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']

http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets

Get an object's class name at runtime

In Angular2, this can help to get components name:

    getName() {
        let comp:any = this.constructor;
        return comp.name;
    }

comp:any is needed because TypeScript compiler will issue errors since Function initially does not have property name.

How do you add CSS with Javascript?

use .css in Jquery like $('strong').css('background','red');

_x000D_
_x000D_
$('strong').css('background','red');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<strong> Example_x000D_
</strong> 
_x000D_
_x000D_
_x000D_

How can I display a tooltip on an HTML "option" tag?

I just tried doing this on Chrome:

var $sel = $('#sel'); $sel.find('option').hover(function(){$sel.attr('title',$(this).attr('title'));console.log($(this).attr('title'))}, function(){$sel.attr('title','');});

However, the hover enter never fires... So you wouldn't be able to do this at all using the standard select. You could achieve this though through some non standard ways:

  • You could fake a select box by using radio boxes that look like dropdowns. So for example, have a radio box absolute positioned and opacity set to 0 placed over the styled box that is pretending to be the option.
  • Or you could use pure javascript and have a series of boxes and adding javascript onclick events to recreate the dropbox yourself - so you will update a hidden value with whichever box was clicked using javascript.
  • Or use one of the non standard libraries already out there. (If there are any?)

node and Error: EMFILE, too many open files

I am not sure whether this will help anyone, I started working on a big project with lot of dependencies which threw me the same error. My colleague suggested me to install watchman using brew and that fixed this problem for me.

brew update
brew install watchman

Edit on 26 June 2019: Github link to watchman

Possible to access MVC ViewBag object from Javascript file?

In order to do this your JavaScript file would need to be pre-processed on the server side. Essentially, it would have to become an ASP.NET View of some kind, and script tags which reference the file would essentially be referencing a controller action which responds with that view.

That sounds like a can of worms you don't want to open.

Since JavaScript is client-side, why not just set the value to some client-side element and have the JavaScript interact with that. It's perhaps an additional step of indirection, but it sounds like much less of a headache than creating a JavaScript view.

Something like this:

<script type="text/javascript">
    var someValue = @ViewBag.someValue
</script>

Then the external JavaScript file can reference the someValue JavaScript variable within the scope of that document.

Or even:

<input type="hidden" id="someValue" value="@ViewBag.someValue" />

Then you can access that hidden input.

Unless you come up with some really slick way to actually make your JavaScript file usable as a view. It's certainly doable, and I can't readily think of any problems you'd have (other than really ugly view code since the view engine will get very confused as to what's JavaScript and what's Razor... so expect a ton of <text> markup), so if you find a slick way to do it that would be pretty cool, albeit perhaps unintuitive to someone who needs to support the code later.

Whitespace Matching Regex - Java

For Java (not php, not javascript, not anyother):

txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")

Deserializing a JSON into a JavaScript object

You could also use eval() but JSON.parse() is safer and easier way, so why would you?

good and works

var yourJsonObject = JSON.parse(json_as_text);

I don't see any reason why would you prefer to use eval. It only puts your application at risk.

That said - this is also possible.

bad - but also works

var yourJsonObject = eval(json_as_text);

Why is eval a bad idea?

Consider the following example.

Some third party or user provided JSON string data.

var json = `
[{
    "adjacencies": [
        {
          "nodeTo": function(){
            return "delete server files - you have been hacked!";
          }(),
          "nodeFrom": "graphnode1",
          "data": {
            "$color": "#557EAA"
          }
        }
    ],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode1",
    "name": "graphnode1"
},{
    "adjacencies": [],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode2",
    "name": "graphnode2"
}]
`;

Your server-side script processes that data.

Using JSON.parse:

window.onload = function(){
  var placeholder = document.getElementById('placeholder1');
  placeholder.innerHTML = JSON.parse(json)[0].adjacencies[0].nodeTo;
}

will throw:

Uncaught SyntaxError: Unexpected token u in JSON at position X. 

Function will not get executed.

You are safe.

Using eval():

window.onload = function(){
  var placeholder = document.getElementById('placeholder1');
  placeholder.innerHTML = eval(json)[0].adjacencies[0].nodeTo;
}

will execute the function and return the text.

If I replace that harmless function with one that removes files from your website folder you have been hacked. No errors/warnings will get thrown in this example.

You are NOT safe.

I was able to manipulate a JSON text string so it acts as a function which will execute on the server.

eval(JSON)[0].adjacencies[0].nodeTo expects to process a JSON string but, in reality, we just executed a function on our server.

This could also be prevented if we server-side check all user-provided data before passing it to an eval() function but why not just use the built-in tool for parsing JSON and avoid all this trouble and danger?

jQuery DatePicker with today as maxDate

If you're using bootstrap 3 date time picker, try this:

$('.selector').datetimepicker({ maxDate: $.now() });

How to retrieve SQL result column value using column name in Python?

you must look for something called " dictionary in cursor "

i'm using mysql connector and i have to add this parameter to my cursor , so i can use my columns names instead of index's

db = mysql.connector.connect(
    host=db_info['mysql_host'],
    user=db_info['mysql_user'],
    passwd=db_info['mysql_password'],
    database=db_info['mysql_db'])

cur = db.cursor()

cur = db.cursor( buffered=True , dictionary=True)

Passing $_POST values with cURL

Check out this page which has an example of how to do it.

Removing an element from an Array (Java)

You can't remove an element from the basic Java array. Take a look at various Collections and ArrayList instead.

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

Builder Pattern in Effective Java

You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.

public class NutritionalFacts {
    private final int sodium;
    private final int fat;
    private final int carbo;

    public int getSodium(){
        return sodium;
    }

    public int getFat(){
        return fat;
    }

    public int getCarbo(){
        return carbo;
    }

    public static class Builder {
        private int sodium;
        private int fat;
        private int carbo;

        public Builder sodium(int s) {
            this.sodium = s;
            return this;
        }

        public Builder fat(int f) {
            this.fat = f;
            return this;
        }

        public Builder carbo(int c) {
            this.carbo = c;
            return this;
        }

        public NutritionalFacts build() {
            return new NutritionalFacts(this);
        }
    }

    private NutritionalFacts(Builder b) {
        this.sodium = b.sodium;
        this.fat = b.fat;
        this.carbo = b.carbo;
    }
}

And now you can set the properties as follows:

NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).
fat(5).build();

NameError: uninitialized constant (rails)

Similar with @Michael-Neal.

I had named the controller as singular. app/controllers/product_controller.rb

When I renamed it as plural, error solved. app/controllers/products_controller.rb

matplotlib get ylim values

It's an old question, but I don't see mentioned that, depending on the details, the sharey option may be able to do all of this for you, instead of digging up axis limits, margins, etc. There's a demo in the docs that shows how to use sharex, but the same can be done with y-axes.

Make Div overlay ENTIRE page (not just viewport)?

The viewport is all that matters, but you likely want the entire website to stay darkened even while scrolling. For this, you want to use position:fixed instead of position:absolute. Fixed will keep the element static on the screen as you scroll, giving the impression that the entire body is darkened.

Example: http://jsbin.com/okabo3/edit

div.fadeMe {
  opacity:    0.5; 
  background: #000; 
  width:      100%;
  height:     100%; 
  z-index:    10;
  top:        0; 
  left:       0; 
  position:   fixed; 
}
<body>
  <div class="fadeMe"></div>
  <p>A bunch of content here...</p>
</body>

How to connect wireless network adapter to VMWare workstation?

Use a Linux Live cd/usb and boot an that to be able to directly connect to your wifi hardware or use linux as the main OS with direct access to the wifi card and then use windows as a guest os, I know that this maybe not the ideal way but it will work.

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

remap is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:

:map and :noremap are recursive and non-recursive versions of the various mapping commands. For example, if we run:

:map j gg           (moves cursor to first line)
:map Q j            (moves cursor to first line)
:noremap W j        (moves cursor down one line)

Then:

  • j will be mapped to gg.
  • Q will also be mapped to gg, because j will be expanded for the recursive mapping.
  • W will be mapped to j (and not to gg) because j will not be expanded for the non-recursive mapping.

Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.

For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map and :noremap), one that works in normal mode (:nmap and :nnoremap), one in visual mode (:vmap and :vnoremap) and so on.

For more guidance on this, see:

:help :map
:help :noremap
:help recursive_mapping
:help :map-modes

Get method arguments using Spring AOP?

Your can use either of the following methods.

@Before("execution(* ong.customer.bo.CustomerBo.addCustomer(String))")
public void logBefore1(JoinPoint joinPoint) {
    System.out.println(joinPoint.getArgs()[0]);
 }

or

@Before("execution(* ong.customer.bo.CustomerBo.addCustomer(String)), && args(inputString)")
public void logBefore2(JoinPoint joinPoint, String inputString) {
    System.out.println(inputString);
 }

joinpoint.getArgs() returns object array. Since, input is single string, only one object is returned.

In the second approach, the name should be same in expression and input parameter in the advice method i.e. args(inputString) and public void logBefore2(JoinPoint joinPoint, String inputString)

Here, addCustomer(String) indicates the method with one String input parameter.

Git will not init/sync/update new submodules

Thinking that manually setting up .gitmodules is enough is WRONG

My local git version 2.22.0 as of this writing.

So I came to this thread wondering why wasn't git submodule init working; I setup the .gitmodules file and proceeded to do git submodule init ...

IMPORTANT

  1. git submodule add company/project.git includes/project is required (when adding the module for the first time), this will:

    • add config to .git/config
    • update the .gitmodules file
    • track the submodule location (includes/project in this example).
  2. you must then git commit after you have added the submodule, this will commit .gitmodules and the tracked submodule location.

When the project is cloned again, it will have the .gitmodules and the empty submodules directory (e.g. includes/project in this example). At this point .git/config does not have submodule config yet, until git submodule init is run, and remember this only works because .gitmodules AND includes/project are tracked in the main git repo.

Also for reference see:

How to install SQL Server Management Studio 2012 (SSMS) Express?

You can download the 32bit or 64bit version of "Express With Tools" or "SQL Server Management Studio Express" (SSMSE tools only) from:

https://web.archive.org/web/20170507040411/https://www.microsoft.com/betaexperience/pd/SQLEXPNOCTAV2/enus/default.aspx

This link is for SQL Server 2012 Express Service Pack 1 released 11/09/2012 (11.0.3000.00) The original RTM release was 11.0.2100.60 from March or May of 2012.

enter image description here

Could not find an implementation of the query pattern

For those of you (like me) that wasted too much time from this error:

I had received the same error: "Could not find implementation of query Pattern for source type 'DbSet'" but the solution for me was fixing a mistake at the DbContext level.

When I created my context I had this:

public class ContactContext : DbContext
    {
        public ContactContext() : base() { }

        public DbSet Contacts { get; set; }
    }

And my Repository (I was following a Repository pattern in ASP.NET guide) looked like this:

public Contact FindById(int id)
    {       
        var contact = from c in _db.Contacts where c.Id == id select c;
        return contact;
    }

My issue came from the initial setup of my DbContext, when I used DbSet as a generic instead of the type.

I changed public DbSet Contacts { get; set; } to public DbSet<Contact> Contacts { get; set; } and suddenly the query was recognized.


This is probably what k.m says in his answer, but since he mentioned IEnumerable<t> and not DbSet<<YourDomainObject>> I had to dig around in the code for a couple hours to find the line that caused this headache.

How to override toString() properly in Java?

You can't call a constructor as if it was a normal method, you can only call it with new to create a new object:

Kid newKid = new Kid(this.name, this.height, this.bDay);

But constructing a new object from your toString() method is not what you want to be doing.

How can I use nohup to run process as a background process in linux?

In general, I use nohup CMD & to run a nohup background process. However, when the command is in a form that nohup won't accept then I run it through bash -c "...".

For example:

nohup bash -c "(time ./script arg1 arg2 > script.out) &> time_n_err.out" &

stdout from the script gets written to script.out, while stderr and the output of time goes into time_n_err.out.

So, in your case:

nohup bash -c "(time bash executeScript 1 input fileOutput > scrOutput) &> timeUse.txt" &

Where are logs located?

In Laravel 6, by default the logs are in:

storage/logs/laravel.log

Remote origin already exists on 'git push' to a new repository

  1. git remote rm origin

  2. git remote -v It will not display any repository name

  3. git remote add origin [email protected]:username/myapp.git

  4. git push origin master It will start the process and creating the new branch. You can see your work is pushed to github.

Angular 2 - Redirect to an external URL and open in a new tab

in HTML:

<a class="main-item" (click)="onNavigate()">Go to URL</a>

OR

<button class="main-item" (click)="onNavigate()">Go to URL</button>

in TS file:

onNavigate(){
    // your logic here.... like set the url 
    const url = 'https://www.google.com';
    window.open(url, '_blank');
}

Checking if a number is an Integer in Java

 int x = 3;

 if(ceil(x) == x) {

  System.out.println("x is an integer");

 } else {

  System.out.println("x is not an integer");

 }

Assign an initial value to radio button as checked

I've put this answer on a similar question that was marked as a duplicate of this question. The answer has helped a decent amount of people so I thought I'd add it here too in just in case.

This doesn't exactly answer the question but for anyone using AngularJS trying to achieve this, the answer is slightly different. And actually the normal answer won't work (at least it didn't for me).

Your html will look pretty similar to the normal radio button:

<input type='radio' name='group' ng-model='mValue' value='first' />First
<input type='radio' name='group' ng-model='mValue' value='second' /> Second

In your controller you'll have declared the mValue that is associated with the radio buttons. To have one of these radio buttons preselected, assign the $scope variable associated with the group to the desired input's value:

$scope.mValue="second"

This makes the "second" radio button selected on loading the page.

How do I perform a JAVA callback between classes?

Define an interface, and implement it in the class that will receive the callback.

Have attention to the multi-threading in your case.

Code example from http://cleancodedevelopment-qualityseal.blogspot.com.br/2012/10/understanding-callbacks-with-java.html

interface CallBack {                   //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
    void methodToCallBack();
}

class CallBackImpl implements CallBack {          //class that implements the method to callback defined in the interface
    public void methodToCallBack() {
        System.out.println("I've been called back");
    }
}

class Caller {

    public void register(CallBack callback) {
        callback.methodToCallBack();
    }

    public static void main(String[] args) {
        Caller caller = new Caller();
        CallBack callBack = new CallBackImpl();       //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
        caller.register(callBack);
    }
} 

In your case, apart from multi-threading you could do like this:

interface ServerInterface {
    void newSeverConnection(Socket socket);
}

public class Server implements ServerInterface {

    public Server(int _address) {
        System.out.println("Starting Server...");
        serverConnectionHandler = new ServerConnections(_address, this);
        workers.execute(serverConnectionHandler);
        System.out.println("Do something else...");
    }

    void newServerConnection(Socket socket) {
        System.out.println("A function of my child class was called.");
    }

}

public class ServerConnections implements Runnable {

    private ServerInterface serverInterface;

    public ServerConnections(int _serverPort, ServerInterface _serverInterface) {
      serverPort = _serverPort;
      serverInterface = _serverInterface;
    }

    @Override
    public void run() {
        System.out.println("Starting Server Thread...");

        if (serverInterface == null) {
            System.out.println("Server Thread error: callback null");
        }

        try {
            mainSocket = new ServerSocket(serverPort);

            while (true) {
                serverInterface.newServerConnection(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Multi-threading

Remember this does not handle multi-threading, this is another topic and can have various solutions depending on the project.

The observer-pattern

The observer-pattern does nearly this, the major difference is the use of an ArrayList for adding more than one listener. Where this is not needed, you get better performance with one reference.

What is the best way to test for an empty string in Go?

I think the best way is to compare with blank string

BenchmarkStringCheck1 is checking with blank string

BenchmarkStringCheck2 is checking with len zero

I check with the empty and non-empty string checking. You can see that checking with a blank string is faster.

BenchmarkStringCheck1-4     2000000000           0.29 ns/op        0 B/op          0 allocs/op
BenchmarkStringCheck1-4     2000000000           0.30 ns/op        0 B/op          0 allocs/op


BenchmarkStringCheck2-4     2000000000           0.30 ns/op        0 B/op          0 allocs/op
BenchmarkStringCheck2-4     2000000000           0.31 ns/op        0 B/op          0 allocs/op

Code

func BenchmarkStringCheck1(b *testing.B) {
    s := "Hello"
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        if s == "" {

        }
    }
}

func BenchmarkStringCheck2(b *testing.B) {
    s := "Hello"
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        if len(s) == 0 {

        }
    }
}

Parse (split) a string in C++ using string delimiter (standard C++)

strtok allows you to pass in multiple chars as delimiters. I bet if you passed in ">=" your example string would be split correctly (even though the > and = are counted as individual delimiters).

EDIT if you don't want to use c_str() to convert from string to char*, you can use substr and find_first_of to tokenize.

string token, mystring("scott>=tiger");
while(token != mystring){
  token = mystring.substr(0,mystring.find_first_of(">="));
  mystring = mystring.substr(mystring.find_first_of(">=") + 1);
  printf("%s ",token.c_str());
}

Does my application "contain encryption"?

Yes, according to iTunes Connect Export Compliance Information screens, if you use built-in iOS or MacOS encryption (keychain, https), you are using encryption for purposes of US Government Export regulations. Whether you qualify for an export compliance exemption depends on what your app does and how it uses this encryption. Attached images show the iTunes Connect Export Compliance Screens to help you determine your export reporting obligations. In particular, it states:

If you are making use of ATS or making a call to HTTPS please note that you are required to submit a year-end self classification report to the US government. Learn more

iTunes Connect Export Compliance Information Q1

iTunes Connect Export Compliance Information Q2

printf() formatting for hex

The %#08X conversion must precede the value with 0X; that is required by the standard. There's no evidence in the standard that the # should alter the behaviour of the 08 part of the specification except that the 0X prefix is counted as part of the length (so you might want/need to use %#010X. If, like me, you like your hex presented as 0x1234CDEF, then you have to use 0x%08X to achieve the desired result. You could use %#.8X and that should also insert the leading zeroes.

Try variations on the following code:

#include <stdio.h>

int main(void)
{
    int j = 0;
    printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    for (int i = 0; i < 8; i++)
    {
        j = (j << 4) | (i + 6);
        printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    }
    return(0);
}

On an RHEL 5 machine, and also on Mac OS X (10.7.5), the output was:

0x00000000 = 00000000 = 00000000 = 0000000000
0x00000006 = 0X000006 = 0X00000006 = 0x00000006
0x00000067 = 0X000067 = 0X00000067 = 0x00000067
0x00000678 = 0X000678 = 0X00000678 = 0x00000678
0x00006789 = 0X006789 = 0X00006789 = 0x00006789
0x0006789A = 0X06789A = 0X0006789A = 0x0006789a
0x006789AB = 0X6789AB = 0X006789AB = 0x006789ab
0x06789ABC = 0X6789ABC = 0X06789ABC = 0x06789abc
0x6789ABCD = 0X6789ABCD = 0X6789ABCD = 0x6789abcd

I'm a little surprised at the treatment of 0; I'm not clear why the 0X prefix is omitted, but with two separate systems doing it, it must be standard. It confirms my prejudices against the # option.


The treatment of zero is according to the standard.

ISO/IEC 9899:2011 §7.21.6.1 The fprintf function

¶6 The flag characters and their meanings are:
...
# The result is converted to an "alternative form". ... For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. ...

(Emphasis added.)


Note that using %#X will use upper-case letters for the hex digits and 0X as the prefix; using %#x will use lower-case letters for the hex digits and 0x as the prefix. If you prefer 0x as the prefix and upper-case letters, you have to code the 0x separately: 0x%X. Other format modifiers can be added as needed, of course.

For printing addresses, use the <inttypes.h> header and the uintptr_t type and the PRIXPTR format macro:

#include <inttypes.h>
#include <stdio.h>

int main(void)
{
    void *address = &address;  // &address has type void ** but it converts to void *
    printf("Address 0x%.12" PRIXPTR "\n", (uintptr_t)address);
    return 0;
}

Example output:

Address 0x7FFEE5B29428

Choose your poison on the length — I find that a precision of 12 works well for addresses on a Mac running macOS. Combined with the . to specify the minimum precision (digits), it formats addresses reliably. If you set the precision to 16, the extra 4 digits are always 0 in my experience on the Mac, but there's certainly a case to be made for using 16 instead of 12 in portable 64-bit code (but you'd use 8 for 32-bit code).

How do I use ROW_NUMBER()?

ROW_NUMBER() returns a unique number for each row starting with 1. You can easily use this by simply writing:

ROW_NUMBER() OVER (ORDER BY 'Column_Name' DESC) as ROW_NUMBER

How to easily resize/optimize an image size with iOS?

If you image is in document directory, Add this URL extension:

extension URL {
    func compressedImageURL(quality: CGFloat = 0.3) throws -> URL? {
        let imageData = try Data(contentsOf: self)
        debugPrint("Image file size before compression: \(imageData.count) bytes")

        let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + NSUUID().uuidString + ".jpg")

        guard let actualImage = UIImage(data: imageData) else { return nil }
        guard let compressedImageData = UIImageJPEGRepresentation(actualImage, quality) else {
            return nil
        }
        debugPrint("Image file size after compression: \(compressedImageData.count) bytes")

        do {
            try compressedImageData.write(to: compressedURL)
            return compressedURL
        } catch {
            return nil
        }
    }
}

Usage:

guard let localImageURL = URL(string: "< LocalImagePath.jpg >") else {
    return
}

//Here you will get URL of compressed image
guard let compressedImageURL = try localImageURL.compressedImageURL() else {
    return
}

debugPrint("compressedImageURL: \(compressedImageURL.absoluteString)")

Note:- Change < LocalImagePath.jpg > with your local jpg image path.

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You need to use anchors to match the beginning of the string ^ and the end of the string $

^[0-9]{2}$

How to delete a module in Android Studio

Remove from File > File Structure > Dependencies > - button. Then if it is stull there you can remove the module by going to the settings.gradle file and removing it from the include line.

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

  1. Right click on ConstraintLayout.
  2. Select convertview.
  3. select RelativeLayout

For more clarity refer below image

enter image description here

postgresql port confusion 5433 or 5432?

For me in PgAdmin 4 on Mac OS High Sierra, Clicking the PostrgreSQL10 database under Servers in the left column, then the Properties tab, showed 5433 as the port under Connection. (I don't know why, because I chose 5432 during install). Anyway, I clicked the Edit icon under the Properties tab, change that to 5432, saved, and that solved the problem. Go figure.

How to align entire html body to the center?

<style>
        body{
            max-width: 1180px;
            width: 98%;
            margin: 0px auto;
            text-align: left;
        }
</style>

Just apply this style before applying any CSS. You can change width as per your need.

WCF Service, the type provided as the service attribute values…could not be found

I had the same problem. Make sure you include assembly name in Factory property in your .svc file. Maybe you need to clean IIS cache if you had renamed project assembly name.

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

MessageBox.Show(
  "your message",
  "window title", 
  MessageBoxButtons.OK, 
  MessageBoxIcon.Asterisk //For Info Asterisk
  MessageBoxIcon.Exclamation //For triangle Warning 
)

getting only name of the class Class.getName()

Social.class.getSimpleName()

getSimpleName() : Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous. The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".

Getting multiple values with scanf()

Passable for getting multiple values with scanf()

int r,m,v,i,e,k;

scanf("%d%d%d%d%d%d",&r,&m,&v,&i,&e,&k);

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

I know this is an old topic. I had the same problem. I tested all the answers about this topic. And nothing worked here... but i found another solution.

Go to pom->overview and add these to you properties:

  • Name: "maven.compiler.target" Value: "1.7"

and

  • Name: "maven.compiler.source" Value: "1.7"

Now do a maven update.

How to install SQL Server Management Studio 2008 component only

The accepted answer was correct up until July 2011. To get the latest version, including the Service Pack you should find the latest version as described here:

For example, if you check the SP2 CTP and SP1, you'll find the latest version of SQL Server Management Studio under SP1:

Download the 32-bit (x86) or 64-bit (x64) version of the SQLManagementStudio*.exe files as appropriate and install it. You can find out whether your system is 32-bit or 64-bit by right clicking Computer, selecting Properties and looking at the System Type.

Although you could apply the service pack to the base version that results from following the accepted answer, it's easier to just download the latest version of SQL Server Management Studio and simply install it in one step.

Convert string to title case with JavaScript

"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())

How to save the output of a console.log(object) to a file?

right click on console.. click save as.. its this simple.. you'll get an output text file

Stopping a JavaScript function when a certain condition is met

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

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

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

Eclipse: How to build an executable jar with external jar?

Eclipse 3.5 has an option to package required libraries into the runnable jar. File -> Export... Choose runnable jar and click next. The runnable jar export window has a radio button where you can choose to package the required libraries into the jar.

How do I do a not equal in Django queryset filtering?

the field=value syntax in queries is a shorthand for field__exact=value. That is to say that Django puts query operators on query fields in the identifiers. Django supports the following operators:

exact
iexact
contains
icontains
in
gt
gte
lt
lte
startswith
istartswith
endswith
iendswith
range

date
year
iso_year
month
day
week
week_day
iso_week_day
quarter
time
hour
minute
second

isnull
regex
iregex

I'm sure by combining these with the Q objects as Dave Vogt suggests and using filter() or exclude() as Jason Baker suggests you'll get exactly what you need for just about any possible query.

How to clear Flutter's Build cache?

Same issue with mine.

New to Flutter. I'm using VS build-in terminal to do flutter run, to run the app in iPhone. It gives me error Error when reading 'lib/student_model.dart': No such file..., which is an old code version in my code. I have changed it to lib/model/student_model.dart.

And I search this line 'lib/student_model.dart'in the project, it appears filekernel_snapshot.d` containing it. So, it build the project with old code version.

For me, Flutter clean is not working. Restart VS fix the issue, not sure the problem is due to Flutter or VS?

And I'm wondering if there is some command to just build flutter project without run?

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

TL;DR

a) the method/function only reads the array argument => implicit (internal) reference
b) the method/function modifies the array argument => value
c) the method/function array argument is explicitly marked as a reference (with an ampersand) => explicit (user-land) reference

Or this:
- non-ampersand array param: passed by reference; the writing operations alter a new copy of the array, copy which is created on the first write;
- ampersand array param: passed by reference; the writing operations alter the original array.

Remember - PHP does a value-copy the moment you write to the non-ampersand array param. That's what copy-on-write means. I'd love to show you the C source of this behaviour, but it's scary in there. Better use xdebug_debug_zval().

Pascal MARTIN was right. Kosta Kontos was even more so.

Answer

It depends.

Long version

I think I'm writing this down for myself. I should have a blog or something...

Whenever people talk of references (or pointers, for that matter), they usually end up in a logomachy (just look at this thread!).
PHP being a venerable language, I thought I should add up to the confusion (even though this a summary of the above answers). Because, although two people can be right at the same time, you're better off just cracking their heads together into one answer.

First off, you should know that you're not a pedant if you don't answer in a black-and-white manner. Things are more complicated than "yes/no".

As you will see, the whole by-value/by-reference thing is very much related to what exactly are you doing with that array in your method/function scope: reading it or modifying it?

What does PHP says? (aka "change-wise")

The manual says this (emphasis mine):

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition

As far as I can tell, when big, serious, honest-to-God programmers talk about references, they usually talk about altering the value of that reference. And that's exactly what the manual talks about: hey, if you want to CHANGE the value in a function, consider that PHP's doing "pass-by-value".

There's another case that they don't mention, though: what if I don't change anything - just read?
What if you pass an array to a method which doesn't explicitly marks a reference, and we don't change that array in the function scope? E.g.:

<?php
function readAndDoStuffWithAnArray($array) 
{
    return $array[0] + $array[1] + $array[2];
}

$x = array(1, 2, 3);

echo readAndDoStuffWithAnArray($x);

Read on, my fellow traveller.

What does PHP actually do? (aka "memory-wise")

The same big and serious programmers, when they get even more serious, they talk about "memory optimizations" in regards to references. So does PHP. Because PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting, that's why.

It wouldn't be ideal to pass HUGE arrays to various functions, and PHP to make copies of them (that's what "pass-by-value" does, after all):

<?php

// filling an array with 10000 elements of int 1
// let's say it grabs 3 mb from your RAM
$x = array_fill(0, 10000, 1); 

// pass by value, right? RIGHT?
function readArray($arr) { // <-- a new symbol (variable) gets created here
    echo count($arr); // let's just read the array
}

readArray($x);

Well now, if this actually was pass-by-value, we'd have some 3mb+ RAM gone, because there are two copies of that array, right?

Wrong. As long as we don't change the $arr variable, that's a reference, memory-wise. You just don't see it. That's why PHP mentions user-land references when talking about &$someVar, to distinguish between internal and explicit (with ampersand) ones.

Facts

So, when an array is passed as an argument to a method or function is it passed by reference?

I came up with three (yeah, three) cases:
a) the method/function only reads the array argument
b) the method/function modifies the array argument
c) the method/function array argument is explicitly marked as a reference (with an ampersand)


Firstly, let's see how much memory that array actually eats (run here):

<?php
$start_memory = memory_get_usage();
$x = array_fill(0, 10000, 1);
echo memory_get_usage() - $start_memory; // 1331840

That many bytes. Great.

a) the method/function only reads the array argument

Now let's make a function which only reads the said array as an argument and we'll see how much memory the reading logic takes:

<?php

function printUsedMemory($arr) 
{
    $start_memory = memory_get_usage();

    count($arr);       // read
    $x = $arr[0];      // read (+ minor assignment)
    $arr[0] - $arr[1]; // read

    echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}

$x = array_fill(0, 10000, 1); // this is 1331840 bytes
printUsedMemory($x);

Wanna guess? I get 80! See for yourself. This is the part that the PHP manual omits. If the $arr param was actually passed-by-value, you'd see something similar to 1331840 bytes. It seems that $arr behaves like a reference, doesn't it? That's because it is a references - an internal one.

b) the method/function modifies the array argument

Now, let's write to that param, instead of reading from it:

<?php

function printUsedMemory($arr)
{
    $start_memory = memory_get_usage();

    $arr[0] = 1; // WRITE!

    echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}

$x = array_fill(0, 10000, 1);
printUsedMemory($x);

Again, see for yourself, but, for me, that's pretty close to being 1331840. So in this case, the array is actually being copied to $arr.

c) the method/function array argument is explicitly marked as a reference (with an ampersand)

Now let's see how much memory a write operation to an explicit reference takes (run here) - note the ampersand in the function signature:

<?php

function printUsedMemory(&$arr) // <----- explicit, user-land, pass-by-reference
{
    $start_memory = memory_get_usage();

    $arr[0] = 1; // WRITE!

    echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}

$x = array_fill(0, 10000, 1);
printUsedMemory($x);

My bet is that you get 200 max! So this eats approximately as much memory as reading from a non-ampersand param.

How can I parse a CSV string with JavaScript, which contains comma in data?

According to this blog post, this function should do it:

String.prototype.splitCSV = function(sep) {
  for (var foo = this.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--) {
    if (foo[x].replace(/'\s+$/, "'").charAt(foo[x].length - 1) == "'") {
      if ((tl = foo[x].replace(/^\s+'/, "'")).length > 1 && tl.charAt(0) == "'") {
        foo[x] = foo[x].replace(/^\s*'|'\s*$/g, '').replace(/''/g, "'");
      } else if (x) {
        foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));
      } else foo = foo.shift().split(sep).concat(foo);
    } else foo[x].replace(/''/g, "'");
  } return foo;
};

You would call it like so:

var string = "'string, duppi, du', 23, lala";
var parsed = string.splitCSV();
alert(parsed.join("|"));

This jsfiddle kind of works, but it looks like some of the elements have spaces before them.

How to convert numbers between hexadecimal and decimal

It looks like you can say

Convert.ToInt64(value, 16)

to get the decimal from hexdecimal.

The other way around is:

otherVar.ToString("X");

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

Well, the <head> tag has nothing to do with the <header> tag. In the head comes all the metadata and stuff, while the header is just a layout component.
And layout comes into body. So I disagree with you.

How can I compare time in SQL Server?

Using float does not work.

DECLARE @t1 datetime, @t2 datetime
SELECT @t1 = '19000101 23:55:00', @t2 = '20001102 23:55:00'
SELECT CAST(@t1 as float) - floor(CAST(@t1 as float)), CAST(@t2 as float) - floor(CAST(@t2 as float))

You'll see that the values are not the same (SQL Server 2005). I wanted to use this method to check for times around midnight (the full method has more detail) in which I was comparing the current time for being between 23:55:00 and 00:05:00.

Open page in new window without popup blocking

PS> I posted this answer on a related question. Here's how I got round the issue of my async ajax request losing the trusted context:

I opened the popup directly on the users click, directed the url to about:blank and got a handle on that window. You could probably direct the popup to a 'loading' url while your ajax request is made

var myWindow = window.open("about:blank",'name','height=500,width=550');

Then, when my request is successful, I open my callback url in the window

function showWindow(win, url) {
     win.open(url,'name','height=500,width=550');
}

How to maintain page scroll position after a jquery event is carried out?

I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.

This is cut from wdCalendar where I modified this procedure:

 function BuildDaysAndWeekView(startday, l, events, config)
   ....
        var scrollpos = $("#dvtec").scrollTop();
        gridcontainer.html(html.join(""));
        setTimeout(function() {
            $("#dvtec").scrollTop(scrollpos);
        }, 25);
   ....

Without the delay, it simply did not work.

What do .c and .h file extensions mean to C?

.c : 'C' source code
.h : Header file

Usually, the .c files contain the implementation, and .h files contain the "interface" of an implementation.

What is the difference between String and StringBuffer in Java?

While I understand that this is not a major differentiating factor, I noticed today that StringBuffer(and StringBuilder) provides some interesting methods that String doesn't.

  • reverse()
  • setCharAt()

Fastest check if row exists in PostgreSQL

INSERT INTO target( userid, rightid, count )
  SELECT userid, rightid, count 
  FROM batch
  WHERE NOT EXISTS (
    SELECT * FROM target t2, batch b2
    WHERE t2.userid = b2.userid
    -- ... other keyfields ...
    )       
    ;

BTW: if you want the whole batch to fail in case of a duplicate, then (given a primary key constraint)

INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count 
FROM batch
    ;

will do exactly what you want: either it succeeds, or it fails.

What is cURL in PHP?

cURL is a way you can hit a URL from your code to get a html response from it. cURL means client URL which allows you to connect with other URLs and use their responses in your code.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

Function return value in PowerShell

The following simply returns 4 as an answer. When you replace the add expressions for strings it returns the first string.

Function StartingMain {
  $a = 1 + 3
  $b = 2 + 5
  $c = 3 + 7
  Return $a
}

Function StartingEnd($b) {
  Write-Host $b
}

StartingEnd(StartingMain)

This can also be done for an array. The example below will return "Text 2"

Function StartingMain {
  $a = ,@("Text 1","Text 2","Text 3")
  Return $a
}

Function StartingEnd($b) {
  Write-Host $b[1]
}

StartingEnd(StartingMain)

Note that you have to call the function below the function itself. Otherwise, the first time it runs it will return an error that it doesn't know what "StartingMain" is.

unix - count of columns in file

If you have python installed you could try:

python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \
    stores.dat

What's the console.log() of java?

The Log class:

API for sending log output.

Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e() methods.

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

Outside of Android, System.out.println(String msg) is used.

jsonify a SQLAlchemy result set in Flask

Here's what's usually sufficient for me:

I create a serialization mixin which I use with my models. The serialization function basically fetches whatever attributes the SQLAlchemy inspector exposes and puts it in a dict.

from sqlalchemy.inspection import inspect

class Serializer(object):

    def serialize(self):
        return {c: getattr(self, c) for c in inspect(self).attrs.keys()}

    @staticmethod
    def serialize_list(l):
        return [m.serialize() for m in l]

All that's needed now is to extend the SQLAlchemy model with the Serializer mixin class.

If there are fields you do not wish to expose, or that need special formatting, simply override the serialize() function in the model subclass.

class User(db.Model, Serializer):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String)
    password = db.Column(db.String)

    # ...

    def serialize(self):
        d = Serializer.serialize(self)
        del d['password']
        return d

In your controllers, all you have to do is to call the serialize() function (or serialize_list(l) if the query results in a list) on the results:

def get_user(id):
    user = User.query.get(id)
    return json.dumps(user.serialize())

def get_users():
    users = User.query.all()
    return json.dumps(User.serialize_list(users))

How to 'bulk update' with Django?

IT returns number of objects are updated in table.

update_counts = ModelClass.objects.filter(name='bar').update(name="foo")

You can refer this link to get more information on bulk update and create. Bulk update and Create

Failed to resolve: com.google.firebase:firebase-core:9.0.0

Error:(30, 13) Failed to resolve: com.google.firebase:firebase-auth:9.6.1

If you ever get this error and you are using Android studio 2.2 that comes with firebase component integrated in it which has libraries version 9.6.0 by default and you are adding the latest dependencies like 9.6.1 . You might need to downgrade com.google.firebase:firebase-auth:9.6.1 to com.google.firebase:firebase-auth:9.6.0

Or check the library version of your pre-installed firebase and make sure it is of the same version with the new library you are trying to add or added to your project.

Formatting code snippets for blogging on Blogger

Actually I had used (what else ;-) ) Vim for this: it has a 2html "plugin". See the docs here.

So as I edit my code, I just convert it to HTML and paste the results to Blogger's HTML editor.

Note: it's not so beautiful HTML (embeded css would be better), but it just works.

Oh: and it has syntax files for several languages which makes it pretty useful.

Create a view with ORDER BY clause

I've had success forcing the view to be ordered using

SELECT TOP 9999999 ... ORDER BY something

Unfortunately using SELECT TOP 100 PERCENT does not work due the issue here.

Get the device width in javascript

check it

const mq = window.matchMedia( "(min-width: 500px)" );

if (mq.matches) {
  // window width is at least 500px
} else {
  // window width is less than 500px
}

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

Set cookie and get cookie with JavaScript

These are much much better references than w3schools (the most awful web reference ever made):

Examples derived from these references:

// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

The Mozilla reference even has a nice cookie library you can use.

How to display length of filtered ng-repeat data

You can do it with 2 ways. In template and in Controller. In template you can set your filtered array to another variable, then use it like you want. Here is how to do it:

<ul>
  <li data-ng-repeat="user in usersList = (users | gender:filterGender)" data-ng-bind="user.name"></li>
</ul>
 ....
<span>{{ usersList.length | number }}</span>

If you need examples, see the AngularJs filtered count examples/demos

How to search images from private 1.0 registry in docker?

So I know this is a rapidly changing field but (as of 2015-09-08) I found the following in the Docker Registry HTTP API V2:

Listing Repositories (link)

GET /v2/_catalog

Listing Image Tags (link)

GET /v2/<name>/tags/list

Based on that the following worked for me on a local registry (registry:2 IMAGE ID 1e847b14150e365a95d76a9cc6b71cd67ca89905e3a0400fa44381ecf00890e1 created on 2015-08-25T07:55:17.072):

$ curl -X GET http://localhost:5000/v2/_catalog
{"repositories":["ubuntu"]}
$ curl -X GET http://localhost:5000/v2/ubuntu/tags/list
{"name":"ubuntu","tags":["latest"]}

How to remove blank lines from a Unix file

Use grep to match any line that has nothing between the start anchor (^) and the end anchor ($):

grep -v '^$' infile.txt > outfile.txt

If you want to remove lines with only whitespace, you can still use grep. I am using Perl regular expressions in this example, but here are other ways:

grep -P -v '^\s*$' infile.txt > outfile.txt

or, without Perl regular expressions:

grep -v '^[[:space:]]*$' infile.txt > outfile.txt

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

Dependency Walker tells all(well almost). http://www.dependencywalker.com/

It does not "install" -just get it, extract it and run the exec. It works for any x32 or x64 windows module|application.

As I recall it is fairly straightforward to see all dependencies, i.e. the dll modules, and since the appl. is a sum of the dependencies one can ascertain if it is full x64, x32(x86) or a bit of each.

Type of CPU that the module was built for is in the "CPU" column. Most 64-bit aps are still a bit of each but 32-bit ap w/b all x86.

Beautiful program for geeks/programmers and it is free...

How do I pass data to Angular routed components?

3rd approach is most common way to share data between components. you may inject the item service which you want to use in related component.

import { Injectable } from '@angular/core';
import { Predicate } from '../interfaces'

import * as _ from 'lodash';

@Injectable()
export class ItemsService {

    constructor() { }


    removeItemFromArray<T>(array: Array<T>, item: any) {
        _.remove(array, function (current) {
            //console.log(current);
            return JSON.stringify(current) === JSON.stringify(item);
        });
    }

    removeItems<T>(array: Array<T>, predicate: Predicate<T>) {
        _.remove(array, predicate);
    }

    setItem<T>(array: Array<T>, predicate: Predicate<T>, item: T) {
        var _oldItem = _.find(array, predicate);
        if(_oldItem){
            var index = _.indexOf(array, _oldItem);
            array.splice(index, 1, item);
        } else {
            array.push(item);
        }
    }


    addItemToStart<T>(array: Array<T>, item: any) {
        array.splice(0, 0, item);
    }


    getPropertyValues<T, R>(array: Array<T>, property : string) : R
    {
        var result = _.map(array, property);
        return <R><any>result;
    }

    getSerialized<T>(arg: any): T {
        return <T>JSON.parse(JSON.stringify(arg));
    }
}



export interface Predicate<T> {
    (item: T): boolean
}

css transition opacity fade background

http://jsfiddle.net/6xJQq/13/

.container {
    display: inline-block;
    padding: 5px; /*included padding to see background when img apacity is 100%*/
    background-color: black;
    opacity: 1;
}

.container:hover {
    background-color: red;
}

img {
    opacity: 1;
}

img:hover {
    opacity: 0.7;
}

.transition {
    transition: all .25s ease-in-out;
    -moz-transition: all .25s ease-in-out;
    -webkit-transition: all .25s  ease-in-out;
}

Spring Boot - How to get the running port

None of these solutions worked for me. I needed to know the server port while constructing a Swagger configuration bean. Using ServerProperties worked for me:

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.ws.rs.ApplicationPath;

import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;

@Component
@ApplicationPath("api")
public class JerseyConfig extends ResourceConfig 
{
    @Inject
    private org.springframework.boot.autoconfigure.web.ServerProperties serverProperties;

    public JerseyConfig() 
    {
        property(org.glassfish.jersey.server.ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
    }

    @PostConstruct
    protected void postConstruct()
    {
        // register application endpoints
        registerAndConfigureSwaggerUi();
    }

    private void registerAndConfigureSwaggerUi()
    {
        register(ApiListingResource.class);
        register(SwaggerSerializers.class);

        final BeanConfig config = new BeanConfig();
        // set other properties
        config.setHost("localhost:" + serverProperties.getPort()); // gets server.port from application.properties file         
    }
}

This example uses Spring Boot auto configuration and JAX-RS (not Spring MVC).

CSS @font-face not working with Firefox, but working with Chrome and IE

Try nerfing the local source declaration in your @font-face directives.

There's a known bug in either Firefox or the Google Font API that prevents the variants of fonts to be used if the font is installed locally, and matches the defined local name:

http://code.google.com/p/googlefontdirectory/issues/detail?id=13

To effectively nerf the local declaration, just make your local source string some nonsense. The generally accepted convention for this is to use a the smiley unicode character ("?"). Why? Paul Irish has a great explanation up on his blog:

http://paulirish.com/2010/font-face-gotchas/#smiley

How the single threaded non blocking IO model works in Node.js

Okay, most things should be clear so far... the tricky part is the SQL: if it is not in reality running in another thread or process in it’s entirety, the SQL-execution has to be broken down into individual steps (by an SQL processor made for asynchronous execution!), where the non-blocking ones are executed, and the blocking ones (e.g. the sleep) actually can be transferred to the kernel (as an alarm interrupt/event) and put on the event list for the main loop.

That means, e.g. the interpretation of the SQL, etc. is done immediately, but during the wait (stored as an event to come in the future by the kernel in some kqueue, epoll, ... structure; together with the other IO operations) the main loop can do other things and eventually check if something happened of those IOs and waits.

So, to rephrase it again: the program is never (allowed to get) stuck, sleeping calls are never executed. Their duty is done by the kernel (write something, wait for something to come over the network, waiting for time to elapse) or another thread or process. – The Node process checks if at least one of those duties is finished by the kernel in the only blocking call to the OS once in each event-loop-cycle. That point is reached, when everything non-blocking is done.

Clear? :-)

I don’t know Node. But where does the c.query come from?

There has been an error processing your request, Error log record number

Clear your cache and your website will be work well.

Using stored procedure output parameters in C#

Stored Procedure.........

CREATE PROCEDURE usp_InsertContract
    @ContractNumber varchar(7)
AS
BEGIN

    INSERT into [dbo].[Contracts] (ContractNumber)
        VALUES (@ContractNumber)

    SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
END

C#

pvCommand.CommandType = CommandType.StoredProcedure;

pvCommand.Parameters.Clear();
pvCommand.Parameters.Add(new SqlParameter("@ContractNumber", contractNumber));
object uniqueId;
int id;
    try
    {
    uniqueId = pvCommand.ExecuteScalar();
     id = Convert.ToInt32(uniqueId);
    }
    catch (Exception e)
    {
        Debug.Print("  Message: {0}", e.Message);
    }
}

EDIT: "I still get back a DBNull value....Object cannot be cast from DBNull to other types. I'll take this up again tomorrow. I'm off to my other job,"

I believe the Id column in your SQL Table isn't a identity column.

enter image description here

Implementing autocomplete

Update: This answer has led to the development of ng2-completer an Angular2 autocomplete component. This is the list of existing autocomplete components for Angular2:

  1. ng2-completer
  2. ng2-auto-complete
  3. ng2-typeahead

Credit goes to @dan-cancro for coming up with the idea

Keeping the original answer for those who wish to create their own directive:

To display autocomplete list we first need an attribute directive that will return the list of suggestions based on the input text and then display them in a dropdown. The directive has 2 options to display the list:

  1. Obtain a reference to the nativeElement and manipulate the DOM directly
  2. Dynamically load a list component using DynamicComponentLoader

It looks to me that 2nd way is a better choice as it uses angular 2 core mechanisms instead of bypassing them by working directly with the DOM and therefore I'll use this method.

This is the directive code:

"use strict";
import {Directive, DynamicComponentLoader, Input, ComponentRef, Output, EventEmitter, OnInit, ViewContainerRef} from "@angular/core";
import {Promise} from "es6-promise";
import {AutocompleteList} from "./autocomplete-list";

@Directive({
    selector: "[ng2-autocomplete]", // The attribute for the template that uses this directive
    host: {
        "(keyup)": "onKey($event)" // Liten to keyup events on the host component
    }
})
export class AutocompleteDirective implements OnInit {
    // The search function should be passed as an input
    @Input("ng2-autocomplete") public search: (term: string) => Promise<Array<{ text: string, data: any }>>;
    // The directive emits ng2AutocompleteOnSelect event when an item from the list is selected
    @Output("ng2AutocompleteOnSelect") public selected = new EventEmitter();

    private term = "";
    private listCmp: ComponentRef<AutocompleteList> = undefined;
    private refreshTimer: any = undefined;
    private searchInProgress = false;
    private searchRequired = false;

    constructor( private viewRef: ViewContainerRef, private dcl: DynamicComponentLoader) { }
    /**
     * On key event is triggered when a key is released on the host component
     * the event starts a timer to prevent concurrent requests
     */
    public onKey(event: any) {
        if (!this.refreshTimer) {
            this.refreshTimer = setTimeout(
            () => {
                if (!this.searchInProgress) {
                    this.doSearch();
                } else {
                    // If a request is in progress mark that a new search is required
                    this.searchRequired = true;
                }
            },
            200);
        }
        this.term = event.target.value;
        if (this.term === "" && this.listCmp) {
            // clean the list if the search term is empty
            this.removeList();
        }
    }

    public ngOnInit() {
        // When an item is selected remove the list
        this.selected.subscribe(() => {
            this.removeList();
        });
    }

    /**
     * Call the search function and handle the results
     */
    private doSearch() {
        this.refreshTimer = undefined;
        // if we have a search function and a valid search term call the search
        if (this.search && this.term !== "") {
            this.searchInProgress = true;
            this.search(this.term)
            .then((res) => {
                this.searchInProgress = false;
                // if the term has changed during our search do another search
                if (this.searchRequired) {
                    this.searchRequired = false;
                    this.doSearch();
                } else {
                    // display the list of results
                    this.displayList(res);
                }
            })
            .catch(err => {
                console.log("search error:", err);
                this.removeList();
            });
        }
    }

    /**
     * Display the list of results
     * Dynamically load the list component if it doesn't exist yet and update the suggestions list
     */
    private displayList(list: Array<{ text: string, data: any }>) {
        if (!this.listCmp) {
            this.dcl.loadNextToLocation(AutocompleteList, this.viewRef)
            .then(cmp => {
                // The component is loaded
                this.listCmp = cmp;
                this.updateList(list);
                // Emit the selectd event when the component fires its selected event
                (<AutocompleteList>(this.listCmp.instance)).selected
                    .subscribe(selectedItem => {

                    this.selected.emit(selectedItem);
                });
            });
        } else {
            this.updateList(list);
        }
    }

    /**
     * Update the suggestions list in the list component
     */
    private updateList(list: Array<{ text: string, data: any }>) {
        if (this.listCmp) {
            (<AutocompleteList>(this.listCmp.instance)).list = list;
        }
    }

    /**
     * remove the list component
     */
    private removeList() {
        this.searchInProgress = false;
        this.searchRequired = false;
        if (this.listCmp) {
            this.listCmp.destroy();
            this.listCmp = undefined;
        }
    }
}

The directive dynamically loads a dropdown component, this is a sample of such a component using bootstrap 4:

"use strict";
import {Component, Output, EventEmitter} from "@angular/core";

@Component({
    selector: "autocomplete-list",
    template: `<div class="dropdown-menu  search-results">
                    <a *ngFor="let item of list" class="dropdown-item" (click)="onClick(item)">{{item.text}}</a>
               </div>`, // Use a bootstrap 4 dropdown-menu to display the list
    styles: [".search-results { position: relative; right: 0; display: block; padding: 0; overflow: hidden; font-size: .9rem;}"]
})
export class AutocompleteList  {
    // Emit a selected event when an item in the list is selected
    @Output() public selected = new EventEmitter();

    public list;

    /**
     * Listen for a click event on the list
     */
    public onClick(item: {text: string, data: any}) {
        this.selected.emit(item);
    }
}

To use the directive in another component you need to import the directive, include it in the components directives and provide it with a search function and event handler for the selection:

 "use strict";
import {Component} from "@angular/core";

import {AutocompleteDirective} from "../component/ng2-autocomplete/autocomplete";

@Component({
    selector: "my-cmp",
    directives: [AutocompleteDirective],
    template: `<input class="form-control" type="text" [ng2-autocomplete]="search()" (ng2AutocompleteOnSelect)="onItemSelected($event)" autocomplete="off">`
})
export class MyComponent  {

    /**
     * generate a search function that returns a Promise that resolves to array of text and optionally additional data
     */  
    public search() {
        return (filter: string): Promise<Array<{ text: string, data: any }>> => {
            // do the search
            resolve({text: "one item", data: null});
        };
    }

    /**
     * handle item selection
     */  
    public onItemSelected(selected: { text: string, data: any }) {
        console.log("selected: ", selected.text);
    }
}

Update: code compatible with angular2 rc.1

How to save and load cookies using Python + Selenium WebDriver

Remember, you can only add a cookie for the current domain.

If you want to add a cookie for your Google account, do

browser.get('http://google.com')
for cookie in cookies:
    browser.add_cookie(cookie)

jQuery Upload Progress and AJAX file upload

Here are some options for using AJAX to upload files:

UPDATE: Here is a JQuery plug-in for Multiple File Uploading.

Maximum length of the textual representation of an IPv6 address?

45 characters.

You might expect an address to be

0000:0000:0000:0000:0000:0000:0000:0000

8 * 4 + 7 = 39

8 groups of 4 digits with 7 : between them.

But if you have an IPv4-mapped IPv6 address, the last two groups can be written in base 10 separated by ., eg. [::ffff:192.168.100.228]. Written out fully:

0000:0000:0000:0000:0000:ffff:192.168.100.228

(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45

Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4] for the address above.

How to iterate through LinkedHashMap with lists as values

You can use the entry set and iterate over the entries which allows you to access both, key and value, directly.

for (Entry<String, ArrayList<String>> entry : test1.entrySet() {
     System.out.println(entry.getKey() + "/" + entry.getValue());
}

I tried this but get only returns string

Why do you think so? The method get returns the type E for which the generic type parameter was chosen, in your case ArrayList<String>.

Difference between a virtual function and a pure virtual function

You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.

Python: Open file in zip without temporarily extracting it

Vincent Povirk's answer won't work completely;

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...

You have to change it in:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...

For details read the ZipFile docs here.

Replace words in a string - Ruby

If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:

'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"

Regular expressions have word boundaries, such as \b which matches start or end of a word. Thus,

'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"

In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:

'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"

Check if an element is present in a Bash array

Here's another way that might be faster, in terms of compute time, than iterating. Not sure. The idea is to convert the array to a string, truncate it, and get the size of the new array.

For example, to find the index of 'd':

arr=(a b c d)    
temp=`echo ${arr[@]}`
temp=( ${temp%%d*} )
index=${#temp[@]}

You could turn this into a function like:

get-index() {

    Item=$1
    Array="$2[@]"

    ArgArray=( ${!Array} )
    NewArray=( ${!Array%%${Item}*} )

    Index=${#NewArray[@]}

    [[ ${#ArgArray[@]} == ${#NewArray[@]} ]] && echo -1 || echo $Index

}

You could then call:

get-index d arr

and it would echo back 3, which would be assignable with:

index=`get-index d arr`

Android emulator doesn't take keyboard input - SDK tools rev 20

Just in case somebody finds it usefull.

I had a problem with the KEYCODE_DPAD_UP it belongs to the trackBall. to solve this change your avdfolder/config.ini hw.trackBall=yes and push DEL or F6

Entity Framework 6 Code first Default value

After @SedatKapanoglu comment, I am adding all my approach that works, because he was right, just using the fluent API does not work.

1- Create custom code generator and override Generate for a ColumnModel.

   public class ExtendedMigrationCodeGenerator : CSharpMigrationCodeGenerator
{

    protected override void Generate(ColumnModel column, IndentedTextWriter writer, bool emitName = false)
    {

        if (column.Annotations.Keys.Contains("Default"))
        {
            var value = Convert.ChangeType(column.Annotations["Default"].NewValue, column.ClrDefaultValue.GetType());
            column.DefaultValue = value;
        }


        base.Generate(column, writer, emitName);
    }

}

2- Assign the new code generator:

public sealed class Configuration : DbMigrationsConfiguration<Data.Context.EfSqlDbContext>
{
    public Configuration()
    {
        CodeGenerator = new ExtendedMigrationCodeGenerator();
        AutomaticMigrationsEnabled = false;
    }
}

3- Use fluent api to created the Annotation:

public static void Configure(DbModelBuilder builder){    
builder.Entity<Company>().Property(c => c.Status).HasColumnAnnotation("Default", 0);            
}

How to delete a folder in C++?

Use SHFileOperation to remove the folder recursivelly

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

Search an array for matching attribute

you can use ES5 some. Its pretty first by using callback

function findRestaurent(foodType) {
    var restaurant;
    restaurants.some(function (r) {
        if (r.food === id) {
            restaurant = r;
            return true;
        }
   });
  return restaurant;
}

Access iframe elements in JavaScript

Two ways

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')

OR

window.frames['myIFrame'].contentWindow.document.getElementById('myIFrameElemId')

How to convert a PIL Image into a numpy array?

You're not saying how exactly putdata() is not behaving. I'm assuming you're doing

>>> pic.putdata(a)
Traceback (most recent call last):
  File "...blablabla.../PIL/Image.py", line 1185, in putdata
    self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple

This is because putdata expects a sequence of tuples and you're giving it a numpy array. This

>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)

will work but it is very slow.

As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply

>>> pix = numpy.array(pic)

although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).

Then, after you make your changes to the array, you should be able to do either pic.putdata(pix) or create a new image with Image.fromarray(pix).

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I had the same error after using the hibernate code generation

https://www.mkyong.com/hibernate/how-to-generate-code-with-hibernate-tools/

then the hibernate.cfg.xml was created in /src/main/java but without the connection parameters after removing it - my problem was solved

Finding length of char array

If anyone is looking for a quick fix for this, here's how you do it.

while (array[i] != '\0') i++;

The variable i will hold the used length of the array, not the entire initialized array. I know it's a late post, but it may help someone.

Assign multiple values to array in C

You can use:

GLfloat coordinates[8] = {1.0f, ..., 0.0f};

but this is a compile-time initialisation - you can't use that method in the current standard to re-initialise (although I think there are ways to do it in the upcoming standard, which may not immediately help you).

The other two ways that spring to mind are to blat the contents if they're fixed:

GLfloat base_coordinates[8] = {1.0f, ..., 0.0f};
GLfloat coordinates[8];
:
memcpy (coordinates, base_coordinates, sizeof (coordinates));

or provide a function that looks like your initialisation code anyway:

void setCoords (float *p0, float p1, ..., float p8) {
    p0[0] = p1; p0[1] = p2; p0[2] = p3; p0[3] = p4;
    p0[4] = p5; p0[5] = p6; p0[6] = p7; p0[7] = p8;
}
:
setCoords (coordinates, 1.0f, ..., 0.0f);

keeping in mind those ellipses (...) are placeholders, not things to literally insert in the code.

Detecting real time window size changes in Angular 4

To get it on init

public innerWidth: any;
ngOnInit() {
    this.innerWidth = window.innerWidth;
}

If you wanna keep it updated on resize:

@HostListener('window:resize', ['$event'])
onResize(event) {
  this.innerWidth = window.innerWidth;
}

How to access a mobile's camera from a web app?

Nowadays at least with android it's relatively easy. Just use normal file input tag and when user clicks it the phone will ask if user wants to use camera (or file managers etc..) to upload a file. Just take a photo with the camera and it will automatically be added and uploaded.

No idea about iphone. Maybe someone can enlighten on that. EDIT: Iphone works similarly.

Sample of the input tag:

<input type="file" accept="image/*" capture="camera">

ApiNotActivatedMapError for simple html page using google-places-api

as of Jan 2017, unfortunately @Adi's answer, while it seems like it should work, does not. (Google's API key process is buggy)

you'll need to click "get a key" from this link: https://developers.google.com/maps/documentation/javascript/get-api-key

also I strongly recommend you don't ever choose "secure key" until you are ready to switch to production. I did http referrer restrictions on a key and afterwards was unable to get it working with localhost, even after disabling security for the key. I had to create a new key for it to work again.

Show a PDF files in users browser via PHP/Perl

You can also use fpdf class available at: http://www.fpdf.org. It gives options for both outputting to a file and displaying on browser.

Python functions call by reference

In Python the passing by reference or by value has to do with what are the actual objects you are passing.So,if you are passing a list for example,then you actually make this pass by reference,since the list is a mutable object.Thus,you are passing a pointer to the function and you can modify the object (list) in the function body.

When you are passing a string,this passing is done by value,so a new string object is being created and when the function terminates it is destroyed. So it all has to do with mutable and immutable objects.

Get size of folder or file

The File object has a length method:

f = new File("your/file/name");
f.length();

Custom exception type

You could implement your own exceptions and their handling for example like here:

// define exceptions "classes" 
function NotNumberException() {}
function NotPositiveNumberException() {}

// try some code
try {
    // some function/code that can throw
    if (isNaN(value))
        throw new NotNumberException();
    else
    if (value < 0)
        throw new NotPositiveNumberException();
}
catch (e) {
    if (e instanceof NotNumberException) {
        alert("not a number");
    }
    else
    if (e instanceof NotPositiveNumberException) {
        alert("not a positive number");
    }
}

There is another syntax for catching a typed exception, although this won't work in every browser (for example not in IE):

// define exceptions "classes" 
function NotNumberException() {}
function NotPositiveNumberException() {}

// try some code
try {
    // some function/code that can throw
    if (isNaN(value))
        throw new NotNumberException();
    else
    if (value < 0)
        throw new NotPositiveNumberException();
}
catch (e if e instanceof NotNumberException) {
    alert("not a number");
}
catch (e if e instanceof NotPositiveNumberException) {
    alert("not a positive number");
}

How to Convert date into MM/DD/YY format in C#

 DateTime.Today.ToString("MM/dd/yy")

Look at the docs for custom date and time format strings for more info.

(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.

enter image description here

Text in HTML Field to disappear when clicked?

To accomplish that, you can use the two events onfocus and onblur:

<input type="text" name="theName" value="DefaultValue"
  onblur="if(this.value==''){ this.value='DefaultValue'; this.style.color='#BBB';}"
  onfocus="if(this.value=='DefaultValue'){ this.value=''; this.style.color='#000';}"
  style="color:#BBB;" />

Export pictures from excel file into jpg using VBA

New versions of excel have made old answers obsolete. It took a long time to make this, but it does a pretty good job. Note that the maximum image size is limited and the aspect ratio is ever so slightly off, as I was not able to perfectly optimize the reshaping math. Note that I've named one of my worksheets wsTMP, you can replace it with Sheet1 or the like. Takes about 1 second to print the screenshot to target path.

Option Explicit

Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

Sub weGucciFam()

Dim tmp As Variant, str As String, h As Double, w As Double

Application.PrintCommunication = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
If Application.StatusBar = False Then Application.StatusBar = "EVENTS DISABLED"

keybd_event vbKeyMenu, 0, 0, 0 'these do just active window
keybd_event vbKeySnapshot, 0, 0, 0
keybd_event vbKeySnapshot, 0, 2, 0
keybd_event vbKeyMenu, 0, 2, 0 'sendkeys alt+printscreen doesn't work
wsTMP.Paste
DoEvents
Const dw As Double = 1186.56
Const dh As Double = 755.28

str = "C:\Users\YOURUSERNAMEHERE\Desktop\Screenshot.jpeg"
w = wsTMP.Shapes(1).Width
h = wsTMP.Shapes(1).Height

Application.DisplayAlerts = False
Set tmp = Charts.Add
On Error Resume Next
With tmp
    .PageSetup.PaperSize = xlPaper11x17
    .PageSetup.TopMargin = IIf(w > dw, dh - dw * h / w, dh - h) + 28
    .PageSetup.BottomMargin = 0
    .PageSetup.RightMargin = IIf(h > dh, dw - dh * w / h, dw - w) + 36
    .PageSetup.LeftMargin = 0
    .PageSetup.HeaderMargin = 0
    .PageSetup.FooterMargin = 0
    .SeriesCollection(1).Delete
    DoEvents
    .Paste
    DoEvents
    .Export Filename:=str, Filtername:="jpeg"
    .Delete
End With
On Error GoTo 0
Do Until wsTMP.Shapes.Count < 1
    wsTMP.Shapes(1).Delete
Loop

Application.PrintCommunication = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.StatusBar = False

End Sub

Using Server.MapPath in external C# Classes in ASP.NET

you can also use:

var path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/myfile.txt")

if

var path = Server.MapPath("~/App_Data");
var fullpath = Path.Combine(path , "myfile.txt");

is inaccessible

javascript get child by id

This works well:

function test(el){
  el.childNodes.item("child").style.display = "none";
}

If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.

How to get 'System.Web.Http, Version=5.2.3.0?

One way to fix it is by modifying the assembly redirect in the web.config file.

Modify the following:

<dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>

to

<dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="4.0.0.0" />
</dependentAssembly>

So the oldVersion attribute should change from "...-4.0.0.0" to "...-5.2.3.0".

Converting to upper and lower case in Java

WordUtils.capitalizeFully(str) from apache commons-lang has the exact semantics as required.

Python JSON encoding

Python lists translate to JSON arrays. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict:

>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'

How to open every file in a folder

import pyautogui
import keyboard
import time
import os
import pyperclip

os.chdir("target directory")

# get the current directory
cwd=os.getcwd()

files=[]

for i in os.walk(cwd):
    for j in i[2]:
        files.append(os.path.abspath(j))

os.startfile("C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe")
time.sleep(1)


for i in files:
    print(i)
    pyperclip.copy(i)
    keyboard.press('ctrl')
    keyboard.press_and_release('o')
    keyboard.release('ctrl')
    time.sleep(1)

    keyboard.press('ctrl')
    keyboard.press_and_release('v')
    keyboard.release('ctrl')
    time.sleep(1)
    keyboard.press_and_release('enter')
    keyboard.press('ctrl')
    keyboard.press_and_release('p')
    keyboard.release('ctrl')
    keyboard.press_and_release('enter')
    time.sleep(3)
    keyboard.press('ctrl')
    keyboard.press_and_release('w')
    keyboard.release('ctrl')
    pyperclip.copy('')

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

I had a similar issues fresh install and same error surprising. Finally I figured out it was a problem with browser cookies...

  1. Try cleaning your browser cookies and see it helps to resolve this issue, before even trying any configuration changes.

  2. Try using XAMPP Control panel "Admin" button instead of usual http://localhost or http://localhost/phpmyadmin

  3. Try direct link: http://localhost/phpmyadmin/main.php or http://127.0.0.1/phpmyadmin/main.php

  4. Finally try this: http://localhost/phpmyadmin/index.php?db=phpmyadmin&server=1&target=db_structure.php

Somehow if you have old installation and you upgraded to new version it keeps track of your old settings through cookies.

If this solution helped let me know.

Definition of int64_t

int64_t is guaranteed by the C99 standard to be exactly 64 bits wide on platforms that implement it, there's no such guarantee for a long which is at least 32 bits so it could be more.

§7.18.1.3 Exact-width integer types 1 The typedef name intN_t designates a signed integer type with width N , no padding bits, and a two’s complement representation. Thus, int8_t denotes a signed integer type with a width of exactly 8 bits.

Subset of rows containing NA (missing) values in a chosen column of a data frame

new_data <- data %>% filter_all(any_vars(is.na(.))) 

This should create a new data frame (new_data) with only the missing values in it.

Works best to keep a track of values that you might later drop because they had some columns with missing observations (NA).

CreateProcess: No such file or directory

It looks like there are a couple of release distro for MinGW. Which one did you try? For the record, I ran into the exact same problem as the OP and the distro I got was from TDM-GCC 4.5.1.

I found the MinGW distro here seems to work far better and sets things up correctly. So for anyone running into this retarded 'createprocess-no-such-file-or-directory' error and can't get things to work, uninstall your existing MinGW and try the one I linked instead.

How do I replace part of a string in PHP?

Just do:

$text = str_replace(' ', '_', $text)

How to recover just deleted rows in mysql?

As Mitch mentioned, backing data up is the best method.

However, it maybe possible to extract the lost data partially depending on the situation or DB server used. For most part, you are out of luck if you don't have any backup.

how to find all indexes and their columns for tables, views and synonyms in oracle

SELECT * FROM user_cons_columns WHERE table_name = 'table_name';

How to disable an input box using angular.js

Use ng-disabled or a special CSS class with ng-class

<input data-ng-model="userInf.username"  
       class="span12 editEmail" 
       type="text"  
       placeholder="[email protected]"  
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="{expression or condition}"
/>

Remove leading zeros from a number in Javascript

regexp:

"014".replace(/^0+/, '')

MongoDB SELECT COUNT GROUP BY

This type of query worked for me:

 db.events.aggregate({$group: {_id : "$date", number:  { $sum : 1} }} )

See http://docs.mongodb.org/manual/tutorial/aggregation-with-user-preference-data/

C# with MySQL INSERT parameters

Use the AddWithValue method:

comm.Parameters.AddWithValue("@person", "Myname");
comm.Parameters.AddWithValue("@address", "Myaddress");

Top 5 time-consuming SQL queries in Oracle

the complete information one that I got from askTom-Oracle. I hope it helps you

select * 
from v$sql 
where buffer_gets > 1000000 
or disk_reads > 100000 
or executions > 50000 

C# winforms combobox dynamic autocomplete

I've found Max Lambertini's answer very helpful, but have modified his HandleTextChanged method as such:

    //I like min length set to 3, to not give too many options 
    //after the first character or two the user types
    public Int32 AutoCompleteMinLength {get; set;}

    private void HandleTextChanged() {
        var txt = comboBox.Text;
        if (txt.Length < AutoCompleteMinLength)
            return;

        //The GetMatches method can be whatever you need to filter 
        //table rows or some other data source based on the typed text.
        var matches = GetMatches(comboBox.Text.ToUpper());

        if (matches.Count() > 0) {
            //The inside of this if block has been changed to allow
            //users to continue typing after the auto-complete results
            //are found.
            comboBox.Items.Clear();
            comboBox.Items.AddRange(matches);
            comboBox.DroppedDown = true;
            Cursor.Current = Cursors.Default;
            comboBox.Select(txt.Length, 0);
            return;
        }
        else {
            comboBox.DroppedDown = false;
            comboBox.SelectionStart = txt.Length;
        }
    }

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

If its money use:

NumberFormat.getNumberInstance(java.util.Locale.US).format(bd)

Outline radius?

Similar to Lea Hayes above, but here's how I did it:

_x000D_
_x000D_
div {_x000D_
  background: #999;_x000D_
  height: 100px;_x000D_
  width: 200px;_x000D_
  border: #999 solid 1px;_x000D_
  border-radius: 10px;_x000D_
  margin: 15px;_x000D_
  box-shadow: 0px 0px 0px 1px #fff inset;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

No nesting of DIVs or jQuery necessary, Altho for brevity I have left out the -moz and -webkit variants of some of the CSS. You can see the result above

How to declare a global variable in React?

I don't know what they're trying to say with this "React Context" stuff - they're talking Greek, to me, but here's how I did it:

Carrying values between functions, on the same page

In your constructor, bind your setter:

this.setSomeVariable = this.setSomeVariable.bind(this);

Then declare a function just below your constructor:

setSomeVariable(propertyTextToAdd) {
    this.setState({
        myProperty: propertyTextToAdd
    });
}

When you want to set it, call this.setSomeVariable("some value");

(You might even be able to get away with this.state.myProperty = "some value";)

When you want to get it, call var myProp = this.state.myProperty;

Using alert(myProp); should give you some value .

Extra scaffolding method to carry values across pages/components

You can assign a model to this (technically this.stores), so you can then reference it with this.state:

import Reflux from 'reflux'
import Actions from '~/actions/actions`

class YourForm extends Reflux.Store
{
    constructor()
    {
        super();
        this.state = {
            someGlobalVariable: '',
        };
        this.listenables = Actions;
        this.baseState = {
            someGlobalVariable: '',
        };
    }

    onUpdateFields(name, value) {
        this.setState({
            [name]: value,
        });
    }

    onResetFields() {
        this.setState({
           someGlobalVariable: '',
        });
    }
}
const reqformdata = new YourForm

export default reqformdata

Save this to a folder called stores as yourForm.jsx.

Then you can do this in another page:

import React from 'react'
import Reflux from 'reflux'
import {Form} from 'reactstrap'
import YourForm from '~/stores/yourForm.jsx'

Reflux.defineReact(React)

class SomePage extends Reflux.Component {
    constructor(props) {
        super(props);
        this.state = {
            someLocalVariable: '',
        }
        this.stores = [
            YourForm,
        ]
    }
    render() {

        const myVar = this.state.someGlobalVariable;
        return (
            <Form>
                <div>{myVar}</div>
            </Form>
        )
    }
}
export default SomePage

If you had set this.state.someGlobalVariable in another component using a function like:

setSomeVariable(propertyTextToAdd) {
    this.setState({
       myGlobalVariable: propertyTextToAdd
   });
}

that you bind in the constructor with:

this.setSomeVariable = this.setSomeVariable.bind(this);

the value in propertyTextToAdd would be displayed in SomePage using the code shown above.

Algorithm to randomly generate an aesthetically-pleasing color palette

Here is quick and dirty color generator in C# (using 'RYB approach' described in this article). It's a rewrite from JavaScript.

Use:

List<Color> ColorPalette = ColorGenerator.Generate(30).ToList();

First two colors tend to be white and a shade of black. I often skip them like this (using Linq):

List<Color> ColorsPalette = ColorGenerator
            .Generate(30)
            .Skip(2) // skip white and black
            .ToList(); 

Implementation:

public static class ColorGenerator
{

    // RYB color space
    private static class RYB
    {
        private static readonly double[] White = { 1, 1, 1 };
        private static readonly double[] Red = { 1, 0, 0 };
        private static readonly double[] Yellow = { 1, 1, 0 };
        private static readonly double[] Blue = { 0.163, 0.373, 0.6 };
        private static readonly double[] Violet = { 0.5, 0, 0.5 };
        private static readonly double[] Green = { 0, 0.66, 0.2 };
        private static readonly double[] Orange = { 1, 0.5, 0 };
        private static readonly double[] Black = { 0.2, 0.094, 0.0 };

        public static double[] ToRgb(double r, double y, double b)
        {
            var rgb = new double[3];
            for (int i = 0; i < 3; i++)
            {
                rgb[i] = White[i]  * (1.0 - r) * (1.0 - b) * (1.0 - y) +
                         Red[i]    * r         * (1.0 - b) * (1.0 - y) +
                         Blue[i]   * (1.0 - r) * b         * (1.0 - y) +
                         Violet[i] * r         * b         * (1.0 - y) +
                         Yellow[i] * (1.0 - r) * (1.0 - b) *        y +
                         Orange[i] * r         * (1.0 - b) *        y +
                         Green[i]  * (1.0 - r) * b         *        y +
                         Black[i]  * r         * b         *        y;
            }

            return rgb;
        }
    }

    private class Points : IEnumerable<double[]>
    {
        private readonly int pointsCount;
        private double[] picked;
        private int pickedCount;

        private readonly List<double[]> points = new List<double[]>();

        public Points(int count)
        {
            pointsCount = count;
        }

        private void Generate()
        {
            points.Clear();
            var numBase = (int)Math.Ceiling(Math.Pow(pointsCount, 1.0 / 3.0));
            var ceil = (int)Math.Pow(numBase, 3.0);
            for (int i = 0; i < ceil; i++)
            {
                points.Add(new[]
                {
                    Math.Floor(i/(double)(numBase*numBase))/ (numBase - 1.0),
                    Math.Floor((i/(double)numBase) % numBase)/ (numBase - 1.0),
                    Math.Floor((double)(i % numBase))/ (numBase - 1.0),
                });
            }
        }

        private double Distance(double[] p1)
        {
            double distance = 0;
            for (int i = 0; i < 3; i++)
            {
                distance += Math.Pow(p1[i] - picked[i], 2.0);
            }

            return distance;
        }

        private double[] Pick()
        {
            if (picked == null)
            {
                picked = points[0];
                points.RemoveAt(0);
                pickedCount = 1;
                return picked;
            }

            var d1 = Distance(points[0]);
            int i1 = 0, i2 = 0;
            foreach (var point in points)
            {
                var d2 = Distance(point);
                if (d1 < d2)
                {
                    i1 = i2;
                    d1 = d2;
                }

                i2 += 1;
            }

            var pick = points[i1];
            points.RemoveAt(i1);

            for (int i = 0; i < 3; i++)
            {
                picked[i] = (pickedCount * picked[i] + pick[i]) / (pickedCount + 1.0);
            }

            pickedCount += 1;
            return pick;
        }

        public IEnumerator<double[]> GetEnumerator()
        {
            Generate();
            for (int i = 0; i < pointsCount; i++)
            {
                yield return Pick();
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public static IEnumerable<Color> Generate(int numOfColors)
    {
        var points = new Points(numOfColors);

        foreach (var point in points)
        {
            var rgb = RYB.ToRgb(point[0], point[1], point[2]);
            yield return Color.FromArgb(
                (int)Math.Floor(255 * rgb[0]),
                (int)Math.Floor(255 * rgb[1]),
                (int)Math.Floor(255 * rgb[2]));
        }
    }
}

SQL: How do I SELECT only the rows with a unique value on certain column?

SELECT DISTINCT Col1,Col2 FROM Table GROUP BY Col1 HAVING COUNT( DISTINCT Col1 ) = 1

How to temporarily disable a click handler in jQuery?

I noticed this post was old but it appears top on google and this kind of solution was never offered so I decided to post it anyway.

You can just disable cursor-events and enable them again later via css. It is supported on all major browsers and may prove useful in some situations.

$("#button_id").click(function() {

   $("#button_id").css("pointer-events", "none");
   //do something
   $("#button_id").css("pointer-events", "auto");
}

Properties file in python (similar to Java Properties)

If you have an option of file formats I suggest using .ini and Python's ConfigParser as mentioned. If you need compatibility with Java .properties files I have written a library for it called jprops. We were using pyjavaproperties, but after encountering various limitations I ended up implementing my own. It has full support for the .properties format, including unicode support and better support for escape sequences. Jprops can also parse any file-like object while pyjavaproperties only works with real files on disk.

trace a particular IP and port

it can be done by using this command: tcptraceroute -p destination port destination IP. like: tcptraceroute -p 9100 10.0.0.50 but don't forget to install tcptraceroute package on your system. tcpdump and nc by default installed on the system. regards

Loop in Jade (currently known as "Pug") template engine

An unusual but pretty way of doing it

Without index:

each _ in Array(5)
  = 'a'

Will print: aaaaa

With index:

each _, i in Array(5)
  = i

Will print: 01234

Notes: In the examples above, I have assigned the val parameter of jade's each iteration syntax to _ because it is required, but will always return undefined.

How to take the nth digit of a number in python

I'm very sorry for necro-threading but I wanted to provide a solution without converting the integer to a string. Also I wanted to work with more computer-like thinking so that's why the answer from Chris Mueller wasn't good enough for me.

So without further ado,

import math

def count_number(number):
    counter = 0
    counter_number = number
    while counter_number > 0:
        counter_number //= 10
        counter += 1
    return counter


def digit_selector(number, selected_digit, total):
    total_counter = total
    calculated_select = total_counter - selected_digit
    number_selected = int(number / math.pow(10, calculated_select))
    while number_selected > 10:
        number_selected -= 10
    return number_selected


def main():
    x = 1548731588
    total_digits = count_number(x)
    digit_2 = digit_selector(x, 2, total_digits)
    return print(digit_2)


if __name__ == '__main__':
    main()

which will print:

5

Hopefully someone else might need this specific kind of code. Would love to have feedback on this aswell!

This should find any digit in a integer.

Flaws:

Works pretty ok but if you use this for long numbers then it'll take more and more time. I think that it would be possible to see if there are multiple thousands etc and then substract those from number_selected but that's maybe for another time ;)

Usage:

You need every line from 1-21. Then you can call first count_number to make it count your integer.

x = 1548731588
total_digits = count_number(x)

Then read/use the digit_selector function as follows:

digit_selector('insert your integer here', 'which digit do you want to have? (starting from the most left digit as 1)', 'How many digits are there in total?')

If we have 1234567890, and we need 4 selected, that is the 4th digit counting from left so we type '4'.

We know how many digits there are due to using total_digits. So that's pretty easy.

Hope that explains everything!

Han

PS: Special thanks for CodeVsColor for providing the count_number function. I used this link: https://www.codevscolor.com/count-number-digits-number-python to help me make the digit_selector work.

Log all queries in mysql

Quick way to enable MySQL General Query Log without restarting.

mysql> SET GLOBAL general_log = 'ON';
mysql> SET GLOBAL general_log_file = '/var/www/nanhe/log/all.log';

I have installed mysql through homebrew, mysql version : mysql Ver 14.14 Distrib 5.7.15, for osx10.11 (x86_64) using EditLine wrapper

How do I share a global variable between c files?

Use extern keyword in another .c file.

How to fill OpenCV image with one solid color?

Use numpy.full. Here's a Python that creates a gray, blue, green and red image and shows in a 2x2 grid.

import cv2
import numpy as np

gray_img = np.full((100, 100, 3), 127, np.uint8)

blue_img = np.full((100, 100, 3), 0, np.uint8)
green_img = np.full((100, 100, 3), 0, np.uint8)
red_img = np.full((100, 100, 3), 0, np.uint8)

full_layer = np.full((100, 100), 255, np.uint8)

# OpenCV goes in blue, green, red order
blue_img[:, :, 0] = full_layer
green_img[:, :, 1] = full_layer
red_img[:, :, 2] = full_layer

cv2.imshow('2x2_grid', np.vstack([
    np.hstack([gray_img, blue_img]), 
    np.hstack([green_img, red_img])
]))
cv2.waitKey(0)
cv2.destroyWindow('2x2_grid')

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

32-bit JVMs which expect to have a single large chunk of memory and use raw pointers cannot use more than 4 Gb (since that is the 32 bit limit which also applies to pointers). This includes Sun and - I'm pretty sure - also IBM implementations. I do not know if e.g. JRockit or others have a large memory option with their 32-bit implementations.

If you expect to be hitting this limit you should strongly consider starting a parallel track validating a 64-bit JVM for your production environment so you have that ready for when the 32-bit environment breaks down. Otherwise you will have to do that work under pressure, which is never nice.


Edit 2014-05-15: Oracle FAQ:

The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower. On most modern 32-bit Windows systems the maximum heap size will range from 1.4G to 1.6G. On 32-bit Solaris kernels the address space is limited to 2G. On 64-bit operating systems running the 32-bit VM, the max heap size can be higher, approaching 4G on many Solaris systems.

(http://www.oracle.com/technetwork/java/hotspotfaq-138619.html#gc_heap_32bit)

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

My setup:

  • Apache 2.4.10 (running off Debian)
  • Node.js (version 4.1.1) App running on port 3000 that accepts WebSockets at path /api/ws

As mentioned above by @Basj, make sure a2enmod proxy and ws_tunnel are enabled.

This is a screenshot of the Apache config file that solved my problem:

Apache config

The relevant part as text:

<VirtualHost *:80>
  ServerName *******
  ServerAlias *******
  ProxyPass / http://localhost:3000/
  ProxyPassReverse / http://localhost:3000/

  <Location "/api/ws">
      ProxyPass "ws://localhost:3000/api/ws"
  </Location>
</VirtualHost>

Hope that helps.

Can you get a Windows (AD) username in PHP?

No. But what you can do is have your Active Directory admin enable LDAP so that users can maintain one set of credentials

http://us2.php.net/ldap

vertical alignment of text element in SVG

The alignment-baseline property is what you're looking for it can take the following values

auto | baseline | before-edge | text-before-edge | 
middle | central | after-edge | text-after-edge | 
ideographic | alphabetic | hanging | mathematical | 
inherit

Description from w3c

This property specifies how an object is aligned with respect to its parent. This property specifies which baseline of this element is to be aligned with the corresponding baseline of the parent. For example, this allows alphabetic baselines in Roman text to stay aligned across font size changes. It defaults to the baseline with the same name as the computed value of the alignment-baseline property. That is, the position of "ideographic" alignment-point in the block-progression-direction is the position of the "ideographic" baseline in the baseline-table of the object being aligned.

W3C Source

Unfortunately, although this is the "correct" way of achieving what you're after it would appear Firefox have not implemented a lot of the presentation attributes for the SVG Text Module ('SVG in Firefox' MDN Documentation)

Do I need to pass the full path of a file in another directory to open()?

Yes, you need the full path.

log = open(os.path.join(root, f), 'r')

Is the quick fix. As the comment pointed out, os.walk decends into subdirs so you do need to use the current directory root rather than indir as the base for the path join.

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

In Weblogic 9.2 the configuration via console is as follows:

enter image description here

I believe the default value was 60. Remember to use Release Configuration button after you edit the field.

What is the reason for the error message "System cannot find the path specified"?

There is not only 1 %SystemRoot%\System32 on Windows x64. There are 2 such directories.

The real %SystemRoot%\System32 directory is for 64-bit applications. This directory contains a 64-bit cmd.exe.

But there is also %SystemRoot%\SysWOW64 for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32. It contains a 32-bit cmd.exe.

32-bit applications can access %SystemRoot%\System32 for 64-bit applications by using the alias %SystemRoot%\Sysnative in path.

For more details see the Microsoft documentation about File System Redirector.

So the subdirectory run was created either in %SystemRoot%\System32 for 64-bit applications and 32-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\SysWOW64 which is %SystemRoot%\System32 for 32-bit cmd.exe or the subdirectory run was created in %SystemRoot%\System32 for 32-bit applications and 64-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\System32 as this subdirectory exists only in %SystemRoot%\SysWOW64.

The following code could be used at top of the batch file in case of subdirectory run is in %SystemRoot%\System32 for 64-bit applications:

@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"

Every console application in System32\run directory must be executed with %SystemPath% in the batch file, for example %SystemPath%\run\YourApp.exe.

How it works?

There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32 as defined at top.

But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative. In this case the batch file is processed currently by 32-bit cmd.exe and only in this case %SystemRoot%\Sysnative needs to be used at all. Otherwise %SystemRoot%\System32 can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe, this is the directory containing the 64-bit console applications (and the subdirectory run).

Note: %SystemRoot%\Sysnative is not a directory! It is not possible to cd to %SystemRoot%\Sysnative or use if exist %SystemRoot%\Sysnative or if exist %SystemRoot%\Sysnative\. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe or more general if exist %SystemRoot%\Sysnative\*.

How do I make a checkbox required on an ASP.NET form?

If you want a true validator that does not rely on jquery and handles server side validation as well ( and you should. server side validation is the most important part) then here is a control

public class RequiredCheckBoxValidator : System.Web.UI.WebControls.BaseValidator
{
    private System.Web.UI.WebControls.CheckBox _ctrlToValidate = null;
    protected System.Web.UI.WebControls.CheckBox CheckBoxToValidate
    {
        get
        {
            if (_ctrlToValidate == null)
                _ctrlToValidate = FindControl(this.ControlToValidate) as System.Web.UI.WebControls.CheckBox;

            return _ctrlToValidate;
        }
    }

    protected override bool ControlPropertiesValid()
    {
        if (this.ControlToValidate.Length == 0)
            throw new System.Web.HttpException(string.Format("The ControlToValidate property of '{0}' is required.", this.ID));

        if (this.CheckBoxToValidate == null)
            throw new System.Web.HttpException(string.Format("This control can only validate CheckBox."));

        return true;
    }

    protected override bool EvaluateIsValid()
    {
        return CheckBoxToValidate.Checked;
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (this.Visible && this.Enabled)
        {
            System.Web.UI.ClientScriptManager cs = this.Page.ClientScript;
            if (this.DetermineRenderUplevel() && this.EnableClientScript)
            {
                cs.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "cb_verify", false);
            }
            if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType().FullName))
            {
                cs.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, GetClientSideScript());
            } 
        }
    }

    private string GetClientSideScript()
    {
        return @"<script language=""javascript"">function cb_verify(sender) {var cntrl = document.getElementById(sender.controltovalidate);return cntrl.checked;}</script>";
    }
}

Splitting a Java String by the pipe symbol using split("|")

Use proper escaping: string.split("\\|")

Or, in Java 5+, use the helper Pattern.quote() which has been created for exactly this purpose:

string.split(Pattern.quote("|"))

which works with arbitrary input strings. Very useful when you need to quote / escape user input.

Concatenate two PySpark dataframes

I would solve this in this way:

from pyspark.sql import SparkSession
df_1.createOrReplaceTempView("tab_1")
df_2.createOrReplaceTempView("tab_2")
df_concat=spark.sql("select tab_1.id,tab_1.uniform,tab_1.normal,tab_2.normal_2  from tab_1 tab_1 left join tab_2 tab_2 on tab_1.uniform=tab_2.uniform\
                union\
                select tab_2.id,tab_2.uniform,tab_1.normal,tab_2.normal_2  from tab_2 tab_2 left join tab_1 tab_1 on tab_1.uniform=tab_2.uniform")
df_concat.show()

linux find regex

Well, you may try this '.*[0-9]'

How do I mount a remote Linux folder in Windows through SSH?

Take a look at CIFS (http://www.samba.org/cifs/). It is a virtual file system you can run on your linux machine that will allow you to mount folders on your linux machine in windows using SMB.

CIFS on linux information can be found here: http://linux-cifs.samba.org/

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

always use 'r' to get a raw string when you want to avoid escape.

test_file=open(r'c:\Python27\test.txt','r')

I want to use CASE statement to update some records in sql server 2005

If you don't want to repeat the list twice (as per @J W's answer), then put the updates in a table variable and use a JOIN in the UPDATE:

declare @ToDo table (FromName varchar(10), ToName varchar(10))
insert into @ToDo(FromName,ToName) values
 ('AAA','BBB'),
 ('CCC','DDD'),
 ('EEE','FFF')

update ts set LastName = ToName
from dbo.TestStudents ts
       inner join
     @ToDo t
       on
         ts.LastName = t.FromName

COUNT / GROUP BY with active record?

I think you should count the results with FOUND_ROWS() and SQL_CALC_FOUND_ROWS. You'll need two queries: select, group_by, etc. You'll add a plus select: SQL_CALC_FOUND_ROWS user_id. After this query run a query: SELECT FOUND_ROWS(). This will return the desired number.

How to order a data frame by one descending and one ascending column?

The default sort is stable, so we sort twice: First by the minor key, then by the major key

rum1 <- rum[order(rum$I2, decreasing = FALSE),]
rum2 <- rum1[order(rum1$I1, decreasing = TRUE),]

Displaying the Error Messages in Laravel after being Redirected from controller

to Make it look nice you can use little bootstrap help

@if(count($errors) > 0 )
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <ul class="p-0 m-0" style="list-style: none;">
        @foreach($errors->all() as $error)
        <li>{{$error}}</li>
        @endforeach
    </ul>
</div>
@endif

Using AJAX to pass variable to PHP and retrieve those using AJAX again

$(document).ready(function() {
    $("#raaagh").click(function() {
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: 145}),
            success: function(data) {
                console.log(data);
                $.ajax({
                    url:'ajax.php',
                    data: data,
                    dataType:'json',
                    success:function(data1) {
                        var y1=data1;
                        console.log(data1);
                    }
                });
            }
        });
    });
});

Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call