Programs & Examples On #Springsource dm server

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

Usually what you choose will depend on which methods you need access to. In general - IEnumerable<> (MSDN: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx) for a list of objects that only needs to be iterated through, ICollection<> (MSDN: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) for a list of objects that needs to be iterated through and modified, List<> for a list of objects that needs to be iterated through, modified, sorted, etc (See here for a full list: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx).

From a more specific standpoint, lazy loading comes in to play with choosing the type. By default, navigation properties in Entity Framework come with change tracking and are proxies. In order for the dynamic proxy to be created as a navigation property, the virtual type must implement ICollection.

A navigation property that represents the "many" end of a relationship must return a type that implements ICollection, where T is the type of the object at the other end of the relationship. -Requirements for Creating POCO ProxiesMSDN

More information on Defining and Managing RelationshipsMSDN

Which port(s) does XMPP use?

According to Extensible Messaging and Presence Protocol (Wikipedia), the standard TCP port for the server is 5222.

The client would presumably use the same ports as the messaging protocol, but can also use http (port 80) and https (port 443) for message delivery. These have the advantage of working for users behind firewalls, so your network admin should not need to get involved.

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

How to create a new instance from a class object in Python

This is how you can dynamically create a class named Child in your code, assuming Parent already exists... even if you don't have an explicit Parent class, you could use object...

The code below defines __init__() and then associates it with the class.

>>> child_name = "Child"
>>> child_parents = (Parent,)
>>> child body = """
def __init__(self, arg1):
    # Initialization for the Child class
    self.foo = do_something(arg1)
"""
>>> child_dict = {}
>>> exec(child_body, globals(), child_dict)
>>> childobj = type(child_name, child_parents, child_dict)
>>> childobj.__name__
'Child'
>>> childobj.__bases__
(<type 'object'>,)
>>> # Instantiating the new Child object...
>>> childinst = childobj()
>>> childinst
<__main__.Child object at 0x1c91710>
>>>

Reading numbers from a text file into an array in C

change to

fscanf(myFile, "%1d", &numberArray[i]);

Convert a string representation of a hex dump to a byte array using Java?

public static byte[] hex2ba(String sHex) throws Hex2baException {
    if (1==sHex.length()%2) {
        throw(new Hex2baException("Hex string need even number of chars"));
    }

    byte[] ba = new byte[sHex.length()/2];
    for (int i=0;i<sHex.length()/2;i++) {
        ba[i] = (Integer.decode(
                "0x"+sHex.substring(i*2, (i+1)*2))).byteValue();
    }
    return ba;
}

convert string date to java.sql.Date

This works for me without throwing an exception:

package com.sandbox;

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

public class Sandbox {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date parsed = format.parse("20110210");
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
    }


}

generating variable names on fly in python

Though I don't see much point, here it is:

for i in xrange(0, len(prices)):
    exec("price%d = %s" % (i + 1, repr(prices[i])));

How to pass values across the pages in ASP.net without using Session

You can assign it to a hidden field, and retrieve it using

var value= Request.Form["value"]

GetFiles with multiple extensions

The following retrieves the jpg, tiff and bmp files and gives you an IEnumerable<FileInfo> over which you can iterate:

var files = dinfo.GetFiles("*.jpg")
    .Concat(dinfo.GetFiles("*.tiff"))
    .Concat(dinfo.GetFiles("*.bmp"));

If you really need an array, simply stick .ToArray() at the end of this.

Is it possible to display my iPhone on my computer monitor?

Release notes iOS 3.2 (External Display Support) and iOS 4.0 (Inherited Improvements) mentions that it should be possible to connect external displays to iOS 4.0 devices.
But you still have to jailbreak if you would mirror your iPhone screen...
Related SO Question with updates

How to store a dataframe using Pandas

You can use feather format file. It is extremely fast.

df.to_feather('filename.ft')

Change a Rails application to production

Please make sure you have done below in your environment.rb file.

ENV['RAILS_ENV'] ||= 'production'

If you application runs in shared hosting environment or phushion passenger, you might need to need make changes in .httaccess (inside public folder) and set mode as production.

php multidimensional array get values

This is the way to iterate on this array:

foreach($hotels as $row) {
       foreach($row['rooms'] as $k) {
             echo $k['boards']['board_id'];
             echo $k['boards']['price'];
       }
}

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

Getting current unixtimestamp using Moment.js

for UNIX time-stamp in milliseconds

moment().format('x') // lowerCase x

for UNIX time-stamp in seconds moment().format('X') // capital X

How to set different colors in HTML in one statement?

How about using FONT tag?

Like:

H<font color="red">E</font>LLO.

Can't show example here, because this site doesn't allow font tag use.

Span style is fast and easy too.

Best way to compare dates in Android

Sometimes we need to do a list with dates, like

today with hour

yesterday with yesterday

other days with 23/06/2017

To make this we need to compare current time with our data.

Public class DateUtil {

    Public static int getDateDayOfMonth (Date date) {
        Calendar calendar = Calendar.getInstance ();
        Calendar.setTime (date);
        Return calendar.get (Calendar.DAY_OF_MONTH);
    }

    Public static int getCurrentDayOfMonth () {
        Calendar calendar = Calendar.getInstance ();
        Return calendar.get (Calendar.DAY_OF_MONTH);
    }

    Public static String convertMillisSecondsToHourString (long millisSecond) {
        Date date = new Date (millisSecond);
        Format formatter = new SimpleDateFormat ("HH: mm");
        Return formatter.format (date);
    }

    Public static String convertMillisSecondsToDateString (long millisSecond) {
        Date date = new Date (millisSecond);
        Format formatter = new SimpleDateFormat ("dd / MM / yyyy");
        Return formatter.format (date);
    }

    Public static long convertToMillisSecond (Date date) {
        Return date.getTime ();
    }

    Public static String compare (String stringData, String yesterday) {

        String result = "";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss");
        Date date = null;

        Try {
            Date = simpleDateFormat.parse (stringData);
        } Catch (ParseException e) {
            E.printStackTrace ();
        }

        Long millisSecond = convertToMillisSecond (date);
        Long currencyMillisSecond = System.currentTimeMillis ();

        If (currencyMillisSecond> millisSecond) {
            Long diff = currencyMillisSecond - millisSecond;
            Long day = 86400000L;

            If (diff <day && getCurrentDayOfMonth () == getDateDayOfMonth (date)) {
                Result = convertMillisSecondsToHourString (millisSecond);

            } Else if (diff <(day * 2) && getCurrentDayOfMonth () -1 == getDateDayOfMonth (date)) {
                Result = yesterday;
            } Else {
                Result = convertMillisSecondsToDateString (millisSecond);
            }
        }

        Return result;
    }
}

Also you can check this example in GitHub and this post.

Read file-contents into a string in C++

Here's an iterator-based method.

ifstream file("file", ios::binary);
string fileStr;

istreambuf_iterator<char> inputIt(file), emptyInputIt
back_insert_iterator<string> stringInsert(fileStr);

copy(inputIt, emptyInputIt, stringInsert);

Run/install/debug Android applications over Wi-Fi?

The adb utility does have the ability to connect to a device over TCP/IP. However, adbd is not normally listening for TCP connections.

If you want to get it running, you need an engineering device (in other words, you need root). Then follow the directions in this post:

How can I connect to Android with ADB over TCP?

Since this only works on eng devices, it's not officially supported. Use at your own risk, expect bugs, etc.

How to create Python egg file

I think you should use python wheels for distribution instead of egg now.

Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

PHP combine two associative arrays into one array

There is also array_replace, where an original array is modified by other arrays preserving the key => value association without creating duplicate keys.

  • Same keys on other arrays will cause values to overwrite the original array
  • New keys on other arrays will be created on the original array

.includes() not working in Internet Explorer

If you want to keep using the Array.prototype.include() in javascript you can use this script: github-script-ie-include That converts automatically the include() to the match() function if it detects IE.

Other option is using always thestring.match(Regex(expression))

Get everything after and before certain character in SQL Server

I just did this in one of my reports and it was very simple.

Try this:

=MID(Fields!.Value,8,4)

Note: This worked for me because the value I was trying to get was a constant not sure it what you are trying to get is a constant as well.

Why is it OK to return a 'vector' from a function?

Pre C++11:

The function will not return the local variable, but rather a copy of it. Your compiler might however perform an optimization where no actual copy action is made.

See this question & answer for further details.

C++11:

The function will move the value. See this answer for further details.

Tensorflow: how to save/restore a model?

You can save the variables in the network using

saver = tf.train.Saver() 
saver.save(sess, 'path of save/fileName.ckpt')

To restore the network for reuse later or in another script, use:

saver = tf.train.Saver()
saver.restore(sess, tf.train.latest_checkpoint('path of save/')
sess.run(....) 

Important points:

  1. sess must be same between first and later runs (coherent structure).
  2. saver.restore needs the path of the folder of the saved files, not an individual file path.

How to calculate the median of an array?

Check out the Arrays.sort methods:

http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html

You should also really abstract finding the median into its own method, and just return the value to the calling method. This will make testing your code much easier.

How to generate a Dockerfile from an image?

Update Dec 2018 to BMW's answer

chenzj/dfimage - as described on hub.docker.com regenerates Dockerfile from other images. So you can use it as follows:

docker pull chenzj/dfimage
alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm chenzj/dfimage"
dfimage IMAGE_ID > Dockerfile

Determine on iPhone if user has enabled push notifications

This Swifty solution worked well for me (iOS8+),

Method:

func isNotificationEnabled(completion:@escaping (_ enabled:Bool)->()){
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
            let status =  (settings.authorizationStatus == .authorized)
            completion(status)
        })
    } else {
        if let status = UIApplication.shared.currentUserNotificationSettings?.types{
            let status = status.rawValue != UIUserNotificationType(rawValue: 0).rawValue
            completion(status)
        }else{
            completion(false)
        }
    }
}

Usage:

isNotificationEnabled { (isEnabled) in
            if isEnabled{
                print("Push notification enabled")
            }else{
                print("Push notification not enabled")
            }
        }

Ref

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

if you use Bootstrap 2.2.1 then maybe is this what you are looking for.

Sample file index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title></title>_x000D_
    <link href="Content/bootstrap.min.css" rel="stylesheet" />_x000D_
    <link href="Content/Site.css" rel="stylesheet" />_x000D_
</head>_x000D_
<body>_x000D_
    <menu>_x000D_
        <div class="navbar navbar-default navbar-fixed-top">_x000D_
            <div class="container">_x000D_
                <div class="navbar-header">_x000D_
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                    </button>_x000D_
                    <a class="navbar-brand" href="/">Application name</a>_x000D_
                </div>_x000D_
                <div class="navbar-collapse collapse">_x000D_
                    <ul class="nav navbar-nav">_x000D_
                        <li><a href="/">Home</a></li>_x000D_
                        <li><a href="/Home/About">About</a></li>_x000D_
                        <li><a href="/Home/Contact">Contact</a></li>_x000D_
                    </ul>_x000D_
                    <ul class="nav navbar-nav navbar-right">_x000D_
                        <li><a href="/Account/Register" id="registerLink">Register</a></li>_x000D_
                        <li><a href="/Account/Login" id="loginLink">Log in</a></li>_x000D_
                    </ul>_x000D_
_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </menu>_x000D_
_x000D_
    <nav>_x000D_
        <div class="col-md-2">_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
        </div>_x000D_
_x000D_
    </nav>_x000D_
    <content>_x000D_
       <div class="col-md-10">_x000D_
_x000D_
               <h2>About.</h2>_x000D_
               <h3>Your application description page.</h3>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <hr />_x000D_
       </div>_x000D_
    </content>_x000D_
_x000D_
    <footer>_x000D_
        <div class="navbar navbar-default navbar-fixed-bottom">_x000D_
            <div class="container" style="font-size: .8em">_x000D_
                <p class="navbar-text">_x000D_
                    &copy; Some info_x000D_
                </p>_x000D_
            </div>_x000D_
        </div>_x000D_
    </footer>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_ File Content/Site.css
_x000D_
_x000D_
body {_x000D_
    padding-bottom: 70px;_x000D_
    padding-top: 70px;_x000D_
}
_x000D_
_x000D_
_x000D_

How to remove all whitespace from a string?

I just learned about the "stringr" package to remove white space from the beginning and end of a string with str_trim( , side="both") but it also has a replacement function so that:

a <- " xx yy 11 22 33 " 
str_replace_all(string=a, pattern=" ", repl="")

[1] "xxyy112233"

How to get domain root url in Laravel 4?

My hint:

  1. FIND IF EXISTS in .env:

    APP_URL=http://yourhost.dev

  2. REPLACE TO (OR ADD)

    APP_DOMAIN=yourhost.dev

  3. FIND in config/app.php:

    'url' => env('APP_URL'),

  4. REPLACE TO

    'domain' => env('APP_DOMAIN'),

    'url' => 'http://' . env('APP_DOMAIN'),

  5. USE:

    Config::get('app.domain'); // yourhost.dev

    Config::get('app.url') // http://yourhost.dev

  6. Do your magic!

java.net.URL read stream to byte[]

I am very surprised that nobody here has mentioned the problem of connection and read timeout. It could happen (especially on Android and/or with some crappy network connectivity) that the request will hang and wait forever.

The following code (which also uses Apache IO Commons) takes this into account, and waits max. 5 seconds until it fails:

public static byte[] downloadFile(URL url)
{
    try {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.connect(); 

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(conn.getInputStream(), baos);

        return baos.toByteArray();
    }
    catch (IOException e)
    {
        // Log error and return null, some default or throw a runtime exception
    }
}

How do I calculate someone's age in Java?

With Java 8, we can calculate a person age with one line of code:

public int calCAge(int year, int month,int days){             
    return LocalDate.now().minus(Period.of(year, month, days)).getYear();         
}

Custom sort function in ng-repeat

The following link explains filters in Angular extremely well. It shows how it is possible to define custom sort logic within an ng-repeat. http://toddmotto.com/everything-about-custom-filters-in-angular-js

For sorting object with properties, this is the code I have used: (Note that this sort is the standard JavaScript sort method and not specific to angular) Column Name is the name of the property on which sorting is to be performed.

self.myArray.sort(function(itemA, itemB) {
    if (self.sortOrder === "ASC") {
        return itemA[columnName] > itemB[columnName];
    } else {
        return itemA[columnName] < itemB[columnName];
    }
});

Twig: in_array or similar possible within if statement?

Try this

{% if var in ['foo', 'bar', 'beer'] %}
    ...
{% endif %}

how to kill the tty in unix

In addition to AIXroot's answer, there is also a logout function that can be used to write a utmp logout record. So if you don't have any processes for user xxxx, but userdel says "userdel: account xxxx is currently in use", you can add a logout record manually. Create a file logout.c like this:

#include <stdio.h>
#include <utmp.h>

int main(int argc, char *argv[])
{
  if (argc == 2) {
    return logout(argv[1]);
  }
  else {
    fprintf(stderr, "Usage: logout device\n");
    return 1;
  }
}

Compile it:

gcc -lutil -o logout logout.c

And then run it for whatever it says in the output of finger's "On since" line(s) as a parameter:

# finger xxxx
Login: xxxx                             Name:
Directory: /home/xxxx                   Shell: /bin/bash
On since Sun Feb 26 11:06 (GMT) on 127.0.0.1:6 (messages off) from 127.0.0.1
On since Fri Feb 24 16:53 (GMT) on pts/6, idle 3 days 17:16, from 127.0.0.1
Last login Mon Feb 10 14:45 (GMT) on pts/11 from somehost.example.com
Mail last read Sun Feb 27 08:44 2014 (GMT)
No Plan.

# userdel xxxx
userdel: account `xxxx' is currently in use.
# ./logout 127.0.0.1:6
# ./logout pts/6
# userdel xxxx
no crontab for xxxx

String contains - ignore case

You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

Pattern.compile(Pattern.quote(strptrn), Pattern.CASE_INSENSITIVE).matcher(str1).find();

Is there a Google Voice API?

Be nice if there was a Javascript API version. That way can integrate w/ other AJAX apps or browser extensions/gadgets/widgets.

Right now, current APIs restrict to web app technologies that support Java, .NET, or Python, more for server side, unless may use Google Web Toolkit to translate Java code to Javascript.

glm rotate usage in Opengl

GLM has good example of rotation : http://glm.g-truc.net/code.html

glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);
glm::mat4 ViewTranslate = glm::translate(
    glm::mat4(1.0f),
    glm::vec3(0.0f, 0.0f, -Translate)
);
glm::mat4 ViewRotateX = glm::rotate(
    ViewTranslate,
    Rotate.y,
    glm::vec3(-1.0f, 0.0f, 0.0f)
);
glm::mat4 View = glm::rotate(
    ViewRotateX,
    Rotate.x,
    glm::vec3(0.0f, 1.0f, 0.0f)
);
glm::mat4 Model = glm::scale(
    glm::mat4(1.0f),
    glm::vec3(0.5f)
);
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(LocationMVP, 1, GL_FALSE, glm::value_ptr(MVP));

What are the git concepts of HEAD, master, origin?

I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.

HEAD: the current commit your repo is on. Most of the time HEAD points to the latest commit in your current branch, but that doesn't have to be the case. HEAD really just means "what is my repo currently pointing at".

In the event that the commit HEAD refers to is not the tip of any branch, this is called a "detached head".

master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.

origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.

HEAD is an official notion in git. HEAD always has a well-defined meaning. master and origin are common names usually used in git, but they don't have to be.

How to print variables without spaces between values

>>> value=42

>>> print "Value is %s"%('"'+str(value)+'"') 

Value is "42"

How do I read from parameters.yml in a controller in symfony2?

The Clean Way - 2018+, Symfony 3.4+

Since 2017 and Symfony 3.3 + 3.4 there is much cleaner way - easy to setup and use.

Instead of using container and service/parameter locator anti-pattern, you can pass parameters to class via it's constructor. Don't worry, it's not time-demanding work, but rather setup once & forget approach.

How to set it up in 2 steps?

1. app/config/services.yml

# config.yml

# config.yml
parameters:
    api_pass: 'secret_password'
    api_user: 'my_name'

services:
    _defaults:
        autowire: true
        bind:
            $apiPass: '%api_pass%'
            $apiUser: '%api_user%'

    App\:
        resource: ..

2. Any Controller

<?php declare(strict_types=1);

final class ApiController extends SymfonyController
{
    /**
     * @var string 
     */
    private $apiPass;

    /**
     * @var string
     */
    private $apiUser;

    public function __construct(string $apiPass, string $apiUser)
    {
        $this->apiPass = $apiPass;
        $this->apiUser = $apiUser;
    }

    public function registerAction(): void
    {
        var_dump($this->apiPass); // "secret_password"
        var_dump($this->apiUser); // "my_name"
    }
}

Instant Upgrade Ready!

In case you use older approach, you can automate it with Rector.

Read More

This is called constructor injection over services locator approach.

To read more about this, check my post How to Get Parameter in Symfony Controller the Clean Way.

(It's tested and I keep it updated for new Symfony major version (5, 6...)).

Android - How to regenerate R class?

You can use Eclipse's "Restore from local history" to restore your old R file if it has been deleted. After that you possibly see what keeps Eclipse from building your files (I've seen other errors than before which really helped fixing the problem).

how to change a selections options based on another select option selected?

I don't quote understand what you are trying to achieve, but you need an event listener. Something like:

$('#type').change(function() {
   alert('Value changed to ' + $(this).attr('value'));
});

This will give you the value of the selected option tag.

Convert from ASCII string encoded in Hex to plain ASCII?

A slightly simpler solution:

>>> "7061756c".decode("hex")
'paul'

printf format specifiers for uint32_t and size_t

Sounds like you're expecting size_t to be the same as unsigned long (possibly 64 bits) when it's actually an unsigned int (32 bits). Try using %zu in both cases.

I'm not entirely certain though.

How can I get the IP address from NIC in Python?

Find the IP address of the first eth/wlan entry in ifconfig that's RUNNING:

import itertools
import os
import re

def get_ip():
    f = os.popen('ifconfig')
    for iface in [' '.join(i) for i in iter(lambda: list(itertools.takewhile(lambda l: not l.isspace(),f)), [])]:
        if re.findall('^(eth|wlan)[0-9]',iface) and re.findall('RUNNING',iface):
            ip = re.findall('(?<=inet\saddr:)[0-9\.]+',iface)
            if ip:
                return ip[0]
    return False

How to compare binary files to check if they are the same?

For finding flash memory defects, I had to write this script which shows all 1K blocks which contain differences (not only the first one as cmp -b does)

#!/bin/sh

f1=testinput.dat
f2=testoutput.dat

size=$(stat -c%s $f1)
i=0
while [ $i -lt $size ]; do
  if ! r="`cmp -n 1024 -i $i -b $f1 $f2`"; then
    printf "%8x: %s\n" $i "$r"
  fi
  i=$(expr $i + 1024)
done

Output:

   2d400: testinput.dat testoutput.dat differ: byte 3, line 1 is 200 M-^@ 240 M- 
   2dc00: testinput.dat testoutput.dat differ: byte 8, line 1 is 327 M-W 127 W
   4d000: testinput.dat testoutput.dat differ: byte 37, line 1 is 270 M-8 260 M-0
   4d400: testinput.dat testoutput.dat differ: byte 19, line 1 is  46 &  44 $

Disclaimer: I hacked the script in 5 min. It doesn't support command line arguments nor does it support spaces in file names

How to use UTF-8 in resource properties with ResourceBundle

Here's a Java 7 solution that uses Guava's excellent support library and the try-with-resources construct. It reads and writes properties files using UTF-8 for the simplest overall experience.

To read a properties file as UTF-8:

File file =  new File("/path/to/example.properties");

// Create an empty set of properties
Properties properties = new Properties();

if (file.exists()) {

  // Use a UTF-8 reader from Guava
  try (Reader reader = Files.newReader(file, Charsets.UTF_8)) {
    properties.load(reader);
  } catch (IOException e) {
    // Do something
  }
}

To write a properties file as UTF-8:

File file =  new File("/path/to/example.properties");

// Use a UTF-8 writer from Guava
try (Writer writer = Files.newWriter(file, Charsets.UTF_8)) {
  properties.store(writer, "Your title here");
  writer.flush();
} catch (IOException e) {
  // Do something
}

When to use SELECT ... FOR UPDATE?

The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE.

However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE explicitly.


To solve this problem, Thread 1 should SELECT id FROM rooms FOR UPDATE, thereby preventing Thread 2 from deleting from rooms until Thread 1 is done. Is that correct?

This depends on the concurrency control your database system is using.

  • MyISAM in MySQL (and several other old systems) does lock the whole table for the duration of a query.

  • In SQL Server, SELECT queries place shared locks on the records / pages / tables they have examined, while DML queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT or DELETE query will lock until another session commits.

  • In databases which use MVCC (like Oracle, PostgreSQL, MySQL with InnoDB), a DML query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE would come handy: it would lock either SELECT or the DELETE query until another session commits, just as SQL Server does.

When should one use REPEATABLE_READ transaction isolation versus READ_COMMITTED with SELECT ... FOR UPDATE?

Generally, REPEATABLE READ does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)

  • In Oracle and earlier PostgreSQL versions, REPEATABLE READ is actually a synonym for SERIALIZABLE. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1 query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE

  • In InnoDB, REPEATABLE READ and SERIALIZABLE are different things: readers in SERIALIZABLE mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML on them. So you don't need a SELECT FOR UPDATE in serializable mode, but do need them in REPEATABLE READ or READ COMMITED.

Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC or otherwise).

When I say "you don't need SELECT FOR UPDATE" I really should have added "because of side effects of certain database engine implementation".

@ variables in Ruby on Rails

@variables are called instance variables in ruby. Which means you can access these variables in ANY METHOD inside the class. [Across all methods in the class]

Variables without the @ symbol are called local variables, which means you can access these local variables within THAT DECLARED METHOD only. Limited to the local scope.

Example of Instance Variables:

class Customer
  def initialize(id, name, addr)
    @cust_id = id
    @cust_name = name
    @cust_addr = addr
  end

  def display_details
    puts "Customer id #{@cust_id}"
    puts "Customer name #{@cust_name}"
    puts "Customer address #{@cust_addr}"
  end
end

In the above example @cust_id, @cust_name, @cust_addr are accessed in another method within the class. But the same thing would not be accessible with local variables.

How to pass data to all views in Laravel 5?

The best way would be sharing the variable using View::share('var', $value);

Problems with composing using "*":

Consider following approach:

<?php
// from AppServiceProvider::boot()
$viewFactory = $this->app->make(Factory::class);

$viewFacrory->compose('*', GlobalComposer::class);

From an example blade view:

  @for($i = 0; $i<1000; $i++)
    @include('some_partial_view_to_display_i', ['toDisplay' => $i])
  @endfor

What happens?

  • The GlobalComposer class is instantiated 1000 times using App::make.
  • The event composing:some_partial_view_to_display_i is handled 1000 times.
  • The compose function inside the GlobalComposer class is called 1000 times.

But the partial view some_partial_view_to_display_i has nothing to do with the variables composed by GlobalComposer but heavily increases render time.

Best approach?

Using View::share along a grouped middleware.

Route::group(['middleware' => 'WebMiddleware'], function(){
  // Web routes
});

Route::group(['prefix' => 'api'], function (){

});

class WebMiddleware {
  public function handle($request)
  {
    \View::share('user', auth()->user());
  }
}

Update

If you are using something that is computed over the middleware pipeline you can simply listen to the proper event or put the view share middleware at the last bottom of the pipeline.

Describe table structure

select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='<Table Name>'

You can get details like column datatype and size by this query

How to select an option from drop down using Selenium WebDriver C#?

If you are looking for just any selection from the drop-down box, I also find "select by index" method very useful.

if (IsElementPresent(By.XPath("//select[@id='Q43_0']")))
{
    new SelectElement(driver.FindElement(By.Id("Q43_0")))**.SelectByIndex(1);** // This is selecting first value of the drop-down list
    WaitForAjax();
    Thread.Sleep(3000);
}
else
{
     Console.WriteLine("Your comment here);
}

What's the difference between passing by reference vs. passing by value?

Before understanding the 2 terms, you MUST understand the following. Every object, has 2 things that can make it be distinguished.

  • Its value.
  • Its address.

So if you say employee.name = "John"

know that there are 2 things about name. Its value which is "John" and also its location in the memory which is some hexadecimal number maybe like this: 0x7fd5d258dd00.

Depending on the language's architecture or the type (class, struct, etc.) of your object, you would be either transferring "John" or 0x7fd5d258dd00

Passing "John" is known as passing by value. Passing 0x7fd5d258dd00 is known as passing by reference. Anyone who is pointing to this memory location will have access to the value of "John".

For more on this, I recommend you to read about dereferencing a pointer and also why choose struct (value type) over class (reference type)

CSS: How to position two elements on top of each other, without specifying a height?

Due to absolute positioning removing the elements from the document flow position: absolute is not the right tool for the job. Depending on the exact layout you want to create you will be successful using negative margins, position:relative or maybe even transform: translate. Show us a sample of what you want to do we can help you better.

Using CSS td width absolute, position

My crazy solution.)

$(document).ready(function() {
    $("td").each(function(index) { 
    var htmlText = "<div style='width:300px;'>" + $(this).text() +"</div>";
    $(this).html(htmlText);
  });
});

How can I safely create a nested directory?

import os
if os.path.isfile(filename):
    print "file exists"
else:
    "Your code here"

Where your code here is use the (touch) command

This will check if the file is there if it is not then it will create it.

How can I rename a conda environment?

You can rename your Conda env by just renaming the env folder. Here is the proof:

Conda env renaming

You can find your Conda env folder inside of C:\ProgramData\Anaconda3\envs or you can enter conda env list to see the list of conda envs and its location.

How to round up a number to nearest 10?

We can "cheat" via round with

$rounded = round($roundee / 10) * 10;

We can also avoid going through floating point division with

function roundToTen($roundee)
{
  $r = $roundee % 10;
  return ($r <= 5) : $roundee - $r : $roundee + (10 - $r);
}

Edit: I didn't know (and it's not well documented on the site) that round now supports "negative" precision, so you can more easily use

$round = round($roundee, -1);

Edit again: If you always want to round up, you can try

function roundUpToTen($roundee)
{
  $r = $roundee % 10;
  if ($r == 0)
    return $roundee;
  return $roundee + 10 - $r;    
}

Declare and assign multiple string variables at the same time

All the information is in the existing answers, but I personally wished for a concise summary, so here's an attempt at it; the commands use int variables for brevity, but they apply analogously to any type, including string.

To declare multiple variables and:

  • either: initialize them each:
int i = 0, j = 1; // declare and initialize each; `var` is NOT supported as of C# 8.0
  • or: initialize them all to the same value:
int i, j;    // *declare* first (`var` is NOT supported)
i = j = 42;  // then *initialize* 

// Single-statement alternative that is perhaps visually less obvious:
// Initialize the first variable with the desired value, then use 
// the first variable to initialize the remaining ones.
int i = 42, j = i, k = i;

What doesn't work:

  • You cannot use var in the above statements, because var only works with (a) a declaration that has an initialization value (from which the type can be inferred), and (b), as of C# 8.0, if that declaration is the only one in the statement (otherwise you'll get compilation error error CS0819: Implicitly-typed variables cannot have multiple declarators).

  • Placing an initialization value only after the last variable in a multiple-declarations statement initializes the last variable only:

    int i, j = 1;// initializes *only* j

How can I write text on a HTML5 canvas element?

Canvas text support is actually pretty good - you can control font, size, color, horizontal alignment, vertical alignment, and you can also get text metrics to get the text width in pixels. In addition, you can also use canvas transforms to rotate, stretch and even invert text.

How to parse a CSV file in Bash?

You need to use IFS instead of -d:

while IFS=, read -r col1 col2
do
    echo "I got:$col1|$col2"
done < myfile.csv

Note that for general purpose CSV parsing you should use a specialized tool which can handle quoted fields with internal commas, among other issues that Bash can't handle by itself. Examples of such tools are cvstool and csvkit.

How to implement a FSM - Finite State Machine in Java

EasyFSM is a dynamic Java Library which can be used to implement an FSM.

You can find documentation for the same at : Finite State Machine in Java

Also, you can download the library at : Java FSM Library : DynamicEasyFSM

C# int to enum conversion

I'm pretty sure you can do explicit casting here.

foo f = (foo)value;

So long as you say the enum inherits(?) from int, which you have.

enum foo : int

EDIT Yes it turns out that by default, an enums underlying type is int. You can however use any integral type except char.

You can also cast from a value that's not in the enum, producing an invalid enum. I suspect this works by just changing the type of the reference and not actually changing the value in memory.

enum (C# Reference)
Enumeration Types (C# Programming Guide)

Determining the path that a yum package installed to

yum uses RPM, so the following command will list the contents of the installed package:

$ rpm -ql package-name

Read response headers from API response - Angular 5 + TypeScript

Have you exposed the X-Token from server side using access-control-expose-headers? because not all headers are allowed to be accessed from the client side, you need to expose them from the server side

Also in your frontend, you can use new HTTP module to get a full response using {observe: 'response'} like

http
  .get<any>('url', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.headers.get('X-Token'));
  });

Sequelize, convert entity to plain object

If I get you right, you want to add the sensors collection to the node. If you have a mapping between both models you can either use the include functionality explained here or the values getter defined on every instance. You can find the docs for that here.

The latter can be used like this:

db.Sensors.findAll({
  where: {
    nodeid: node.nodeid
  }
}).success(function (sensors) {
  var nodedata = node.values;

  nodedata.sensors = sensors.map(function(sensor){ return sensor.values });
  // or
  nodedata.sensors = sensors.map(function(sensor){ return sensor.toJSON() });

  nodesensors.push(nodedata);
  response.json(nodesensors);
});

There is chance that nodedata.sensors = sensors could work as well.

Get a JSON object from a HTTP response

For the sake of a complete solution to this problem (yes, I know that this post died long ago...) :

If you want a JSONObject, then first get a String from the result:

String jsonString = EntityUtils.toString(response.getEntity());

Then you can get your JSONObject:

JSONObject jsonObject = new JSONObject(jsonString);

ScalaTest in sbt: is there a way to run a single test without tags?

Here's the Scalatest page on using the runner and the extended discussion on the -t and -z options.

This post shows what commands work for a test file that uses FunSpec.

Here's the test file:

package com.github.mrpowers.scalatest.example

import org.scalatest.FunSpec

class CardiBSpec extends FunSpec {

  describe("realName") {

    it("returns her birth name") {
      assert(CardiB.realName() === "Belcalis Almanzar")
    }

  }

  describe("iLike") {

    it("works with a single argument") {
      assert(CardiB.iLike("dollars") === "I like dollars")
    }

    it("works with multiple arguments") {
      assert(CardiB.iLike("dollars", "diamonds") === "I like dollars, diamonds")
    }

    it("throws an error if an integer argument is supplied") {
      assertThrows[java.lang.IllegalArgumentException]{
        CardiB.iLike()
      }
    }

    it("does not compile with integer arguments") {
      assertDoesNotCompile("""CardiB.iLike(1, 2, 3)""")
    }

  }

}

This command runs the four tests in the iLike describe block (from the SBT command line):

testOnly *CardiBSpec -- -z iLike

You can also use quotation marks, so this will also work:

testOnly *CardiBSpec -- -z "iLike"

This will run a single test:

testOnly *CardiBSpec -- -z "works with multiple arguments"

This will run the two tests that start with "works with":

testOnly *CardiBSpec -- -z "works with"

I can't get the -t option to run any tests in the CardiBSpec file. This command doesn't run any tests:

testOnly *CardiBSpec -- -t "works with multiple arguments"

Looks like the -t option works when tests aren't nested in describe blocks. Let's take a look at another test file:

class CalculatorSpec extends FunSpec {
  it("adds two numbers") {
    assert(Calculator.addNumbers(3, 4) === 7)
  }
}

-t can be used to run the single test:

testOnly *CalculatorSpec -- -t "adds two numbers"

-z can also be used to run the single test:

testOnly *CalculatorSpec -- -z "adds two numbers"

See this repo if you'd like to run these examples. You can find more info on running tests here.

Java array reflection: isArray vs. instanceof

getClass().isArray() is significantly slower on Sun Java 5 or 6 JRE than on IBM.

So much that using clazz.getName().charAt(0) == '[' is faster on Sun JVM.

How to center a checkbox in a table cell?

My problem was that there was a parent style with position: absolute !important which I was not allowed to edit.

So I gave my specific checkbox position: relative !important and it fixed the vertical misalignment issue.

Map implementation with duplicate keys

I used this:

java.util.List<java.util.Map.Entry<String,Integer>> pairList= new java.util.ArrayList<>();

SSRS expression to format two decimal places does not show zeros

You need to make sure that the first numeral to the right of the decimal point is always displayed. In custom format strings, # means display the number if it exists, and 0 means always display something, with 0 as the placeholder.

So in your case you will need something like:

=Format(Fields!CUL1.Value, "#,##0.##")

This saying: display 2 DP if they exist, for the non-zero part always display the lowest part, and use , as the grouping separator.

This is how it looks on your data (I've added a large value as well for reference):

enter image description here

If you're not interested in separating thousands, millions, etc, just use #0.## as Paul-Jan suggested.

The standard docs for Custom Numeric Format Strings are your best reference here.

Changing datagridview cell color based on condition

Let's say you have to color certain cell (not all cells of the row) by knowing two things:

  1. Name or index of the column.
  2. Value which is gonna be inside of the cell.

In thas case you have to use event CellFormatting

In my case I use like this

private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
     foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
     {
       if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) > 0)
       {
          row.Cells["Decade1Hours"].Style.BackColor = Color.LightGreen;
       }
       else if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) < 0)
       {
          // row.DefaultCellStyle.BackColor = Color.LightSalmon; // Use it in order to colorize all cells of the row

          row.Cells["Decade1Hours"].Style.BackColor = Color.LightSalmon;
       }
     }
}

And result you can see here

enter image description here

So here you can access certain cell of the row in column by its name row.Cells["Decade1Hours"]

How do you know this name? Well in my case i create column of DataGridView like this.

var Decade1Hours = new DataGridViewTextBoxColumn()
{
   Name = "Decade1Hours",
   Width = 50,
   DataPropertyName = "Decade1Hours",
   ReadOnly = true,
   DefaultCellStyle = new DataGridViewCellStyle()
       {
        Alignment = DataGridViewContentAlignment.MiddleCenter,
        ForeColor = System.Drawing.Color.Black,
        Font = new Font(font, FontStyle.Bold),
        Format = "n2"
      },
   HeaderCell = new DataGridViewColumnHeaderCell()
      {
          Style = new DataGridViewCellStyle()
               {
                 Alignment = DataGridViewContentAlignment.MiddleCenter,
                 BackColor = System.Drawing.Color.Blue
               }
       }
};
Decade1Hours.HeaderText = "???.1";
dgvTrucksMaster.Columns.Add(Decade1Hours);

And well... you you need for instance colorize some of the cells in the row like ##1 4 5 and 8 you have to use cell index (it starts from 0).

And code will lok like

 private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
  {
    if (Convert.ToInt32(row.Cells[1].Value) > 0 )
    {
      row.Cells[1].Style.BackColor = Color.LightGreen;
    }
  }
}

Switch: Multiple values in one case?

you can try this.

switch (Valor)
            {
                case (Valor1 & Valor2):

                    break;               
            }

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

I faced same problem worked on it around 3 days. I noticed as our number of records are not much our senior developer keeps 2 images and Fingerprint in database. When I try to fetch this hex values it taking long time, I calculate average time to execute my procedure its around 38 seconds. The default commandtimeout is 30 seconds so its less than average time required to run my stored procedure. I set my commandtimeout like below

cmd.CommandTimeout = 50

and its working fine but sometimes if your query takes more than 50 seconds it will prompt same error.

Document Root PHP

Just / refers to the root of your website from the public html folder. DOCUMENT_ROOT refers to the local path to the folder on the server that contains your website.

For example, I have EasyPHP setup on a machine...

$_SERVER["DOCUMENT_ROOT"] gives me file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www but any file I link to with just / will be relative to my www folder.

If you want to give the absolute path to a file on your server (from the server's root) you can use DOCUMENT_ROOT. if you want to give the absolute path to a file from your website's root, use just /.

What's the best way to store Phone number in Django models

Validation is easy, text them a little code to type in. A CharField is a great way to store it. I wouldn't worry too much about canonicalizing phone numbers.

How to print binary tree diagram?

Here is another way to visualize your tree: save the nodes as an xml file and then let your browser show you the hierarchy:

class treeNode{
    int key;
    treeNode left;
    treeNode right;

    public treeNode(int key){
        this.key = key;
        left = right = null;
    }

    public void printNode(StringBuilder output, String dir){
        output.append("<node key='" + key + "' dir='" + dir + "'>");
        if(left != null)
            left.printNode(output, "l");
        if(right != null)
            right.printNode(output, "r");
        output.append("</node>");
    }
}

class tree{
    private treeNode treeRoot;

    public tree(int key){
        treeRoot = new treeNode(key);
    }

    public void insert(int key){
        insert(treeRoot, key);
    }

    private treeNode insert(treeNode root, int key){
        if(root == null){
            treeNode child = new treeNode(key);
            return child;
        }

        if(key < root.key)
            root.left = insert(root.left, key);
        else if(key > root.key)
            root.right = insert(root.right, key);

        return root;
    }

    public void saveTreeAsXml(){
        StringBuilder strOutput = new StringBuilder();
        strOutput.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        treeRoot.printNode(strOutput, "root");
        try {
            PrintWriter writer = new PrintWriter("C:/tree.xml", "UTF-8");
            writer.write(strOutput.toString());
            writer.close();
        }
        catch (FileNotFoundException e){

        }
        catch(UnsupportedEncodingException e){

        }
    }
}

Here is code to test it:

    tree t = new tree(1);
    t.insert(10);
    t.insert(5);
    t.insert(4);
    t.insert(20);
    t.insert(40);
    t.insert(30);
    t.insert(80);
    t.insert(60);
    t.insert(50);

    t.saveTreeAsXml();

And the output looks like this:

enter image description here

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Java: Replace all ' in a string with \'

This doesn't say how to "fix" the problem - that's already been done in other answers; it exists to draw out the details and applicable documentation references.


When using String.replaceAll or any of the applicable Matcher replacers, pay attention to the replacement string and how it is handled:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

As pointed out by isnot2bad in a comment, Matcher.quoteReplacement may be useful here:

Returns a literal replacement String for the specified String. .. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes (\) and dollar signs ($) will be given no special meaning.

html table cell width for different rows

with 5 columns and colspan, this is possible (click here) (but doesn't make much sense to me):

<table width="100%" border="1" bgcolor="#ffffff">
    <colgroup>
        <col width="25%">
        <col width="25%">
        <col width="25%">
        <col width="5%">
        <col width="20%">
    </colgroup>
    <tr>
        <td>25</td>
        <td colspan="2">50</td>
        <td colspan="2">25</td>     
    </tr>
    <tr>
        <td colspan="2">50</td>
        <td colspan="2">30</td>
        <td>20</td>
    </tr>
</table>

How to disable Compatibility View in IE

All you need is to force disable C.M. in IE - Just paste This code (in IE9 and under c.m. will be disabled):

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

Source: http://twigstechtips.blogspot.com/2010/03/css-ie8-meta-tag-to-disable.html

How to get the root dir of the Symfony2 application?

You can also use regular expression in addition to this:

    $directoryPath = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/yourbundle/';
    $directoryPath = preg_replace("/app..../i", "", $directoryPath);
    echo $directoryPath;

How to convert a single char into an int

By this way You can convert char to int and int to char easily:

int charToInt(char c)
{
   int arr[]={0,1,2,3,4,5,6,7,8,9};
   return arr[c-'0'];
}

How do I define global variables in CoffeeScript?

I think what you are trying to achieve can simply be done like this :

While you are compiling the coffeescript, use the "-b" parameter.

-b / --bare Compile the JavaScript without the top-level function safety wrapper.

So something like this : coffee -b --compile somefile.coffee whatever.js

This will output your code just like in the CoffeeScript.org site.

How to have a default option in Angular.js select box

Simply use ng-selected="true" as follows:

<select ng-model="myModel">
        <option value="a" ng-selected="true">A</option>
        <option value="b">B</option>
</select>

number_format() with MySQL

At least as far back as MySQL 5.5 you can use format:

SELECT FORMAT(123456789.123456789,2);
/* produces 123,456,789.12 */

SELECT FORMAT(123456789.123456789,2,'de_DE');
/* 
    produces 123.456.789,12
    note the swapped . and , for the de_DE locale (German-Germany) 
*/

From the MySQL docs: https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_format

Available locales are listed elsewhere in the docs: https://dev.mysql.com/doc/refman/5.5/en/locale-support.html

Using awk to print all columns from the nth to the last

Awk examples looks complex here, here is simple Bash shell syntax:

command | while read -a cols; do echo ${cols[@]:1}; done

Where 1 is your nth column counting from 0.


Example

Given this content of file (in.txt):

c1
c1 c2
c1 c2 c3
c1 c2 c3 c4
c1 c2 c3 c4 c5

here is the output:

$ while read -a cols; do echo ${cols[@]:1}; done < in.txt 

c2
c2 c3
c2 c3 c4
c2 c3 c4 c5

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

I had this error today with Amazon Cloudfront. It was because the cname I used (e.g cdn.example.com) was not added to the distribution settings under "alternate cnames", I only had cdn.example.com forwarded to the cloudfront domain in my site/hosting control panel, but you need to add it to Amazon CloudFront panel too.

Unstaged changes left after git reset --hard

None of these methods worked for me, the only solution was to nuke the whole repo and re-clone it. This includes stashing, resetting, adding then resetting, clrf settings, case sensitivity etc. Sigh..

How to convert empty spaces into null values, using SQL Server?

This code generates some SQL which can achieve this on every table and column in the database:

SELECT
   'UPDATE ['+T.TABLE_SCHEMA+'].[' + T.TABLE_NAME + '] SET [' + COLUMN_NAME + '] = NULL 
   WHERE [' + COLUMN_NAME + '] = '''''
FROM 
    INFORMATION_SCHEMA.columns C
INNER JOIN
    INFORMATION_SCHEMA.TABLES T ON C.TABLE_NAME=T.TABLE_NAME AND C.TABLE_SCHEMA=T.TABLE_SCHEMA
WHERE 
    DATA_TYPE IN ('char','nchar','varchar','nvarchar')
AND C.IS_NULLABLE='YES'
AND T.TABLE_TYPE='BASE TABLE'

How to set 00:00:00 using moment.js

You've not shown how you're creating the string 2016-01-12T23:00:00.000Z, but I assume via .format().

Anyway, .set() is using your local time zone, but the Z in the time string indicates zero time, otherwise known as UTC.

https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators

So I assume your local timezone is 23 hours from UTC?

saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format() call that outputs using your local timezone, rather than UTC.

http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/

How to read a file without newlines?

You can read the whole file and split lines using str.splitlines:

temp = file.read().splitlines()

Or you can strip the newline by hand:

temp = [line[:-1] for line in file]

Note: this last solution only works if the file ends with a newline, otherwise the last line will lose a character.

This assumption is true in most cases (especially for files created by text editors, which often do add an ending newline anyway).

If you want to avoid this you can add a newline at the end of file:

with open(the_file, 'r+') as f:
    f.seek(-1, 2)  # go at the end of the file
    if f.read(1) != '\n':
        # add missing newline if not already present
        f.write('\n')
        f.flush()
        f.seek(0)
    lines = [line[:-1] for line in f]

Or a simpler alternative is to strip the newline instead:

[line.rstrip('\n') for line in file]

Or even, although pretty unreadable:

[line[:-(line[-1] == '\n') or len(line)+1] for line in file]

Which exploits the fact that the return value of or isn't a boolean, but the object that was evaluated true or false.


The readlines method is actually equivalent to:

def readlines(self):
    lines = []
    for line in iter(self.readline, ''):
        lines.append(line)
    return lines

# or equivalently

def readlines(self):
    lines = []
    while True:
        line = self.readline()
        if not line:
            break
        lines.append(line)
    return lines

Since readline() keeps the newline also readlines() keeps it.

Note: for symmetry to readlines() the writelines() method does not add ending newlines, so f2.writelines(f.readlines()) produces an exact copy of f in f2.

Write lines of text to a file in R

tidyverse edition with pipe and write_lines() from readr

library(tidyverse)
c('Hello', 'World') %>% write_lines( "output.txt")

Pandas: Creating DataFrame from Series

No need to initialize an empty DataFrame (you weren't even doing that, you'd need pd.DataFrame() with the parens).

Instead, to create a DataFrame where each series is a column,

  1. make a list of Series, series, and
  2. concatenate them horizontally with df = pd.concat(series, axis=1)

Something like:

series = [pd.Series(mat[name][:, 1]) for name in Variables]
df = pd.concat(series, axis=1)

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

The model backing the 'ApplicationDbContext' context has changed since the database was created

Below was the similar kind of error i encountered

The model backing the 'PsnlContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

I added the below section in the Application Start event of the Global.asax to solve the error

Database.SetInitializer (null);

This fixed the issue

Find a value anywhere in a database

This might help you. - from Narayana Vyas. It searches all columns of all tables in a given database. I have used it before and it works.

This is the Stored Proc from the above link - the only change I made was substituting the temp table for a table variable so you don't have to remember to drop it each time.

CREATE PROC SearchAllTables
(
    @SearchStr nvarchar(100)
)
AS
BEGIN

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT

DECLARE @Results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END 
END

SELECT ColumnName, ColumnValue FROM @Results
END

Jquery If radio button is checked

jQuery('input[name="inputName"]:checked').val()

How do you sort a dictionary by value?

You can sort the Dictionary by value and get the result in dictionary using the code below:

Dictionary <<string, string>> ShareUserNewCopy = 
       ShareUserCopy.OrderBy(x => x.Value).ToDictionary(pair => pair.Key,
                                                        pair => pair.Value);                                          

Getting checkbox values on submit

A good method which is a favorite of mine and for many I'm sure, is to make use of foreach which will output each color you chose, and appear on screen one underneath each other.

When it comes to using checkboxes, you kind of do not have a choice but to use foreach, and that's why you only get one value returned from your array.

Here is an example using $_GET. You can however use $_POST and would need to make both directives match in both files in order to work properly.

###HTML FORM

<form action="third.php" method="get">
    Red<input type="checkbox" name="color[]" value="red">
    Green<input type="checkbox" name="color[]" value="green">
    Blue<input type="checkbox" name="color[]" value="blue">
    Cyan<input type="checkbox" name="color[]" value="cyan">
    Magenta<input type="checkbox" name="color[]" value="Magenta">
    Yellow<input type="checkbox" name="color[]" value="yellow">
    Black<input type="checkbox" name="color[]" value="black">
    <input type="submit" value="submit">
</form>

###PHP (using $_GET) using third.php as your handler

<?php

$name = $_GET['color'];

// optional
// echo "You chose the following color(s): <br>";

foreach ($name as $color){ 
    echo $color."<br />";
}

?>

Assuming having chosen red, green, blue and cyan as colors, will appear like this:

red
green
blue
cyan


##OPTION #2

You can also check if a color was chosen. If none are chosen, then a seperate message will appear.

<?php

$name = $_GET['color'];

if (isset($_GET['color'])) {
    echo "You chose the following color(s): <br>";

    foreach ($name as $color){
        echo $color."<br />";
    }
} else {
    echo "You did not choose a color.";
}

?>

##Additional options: To appear as a list: (<ul></ul> can be replaced by <ol></ol>)

<?php

$name = $_GET['color'];

if (isset($_GET['color'])) {
    echo "You chose the following color(s): <br>";
    echo "<ul>";
    foreach ($name as $color){
        echo "<li>" .$color."</li>";
    }
    echo "</ul>";
} else {
    echo "You did not choose a color.";
}

?>

Ruby Array find_first object?

Guess you just missed the find method in the docs:

my_array.find {|e| e.satisfies_condition? }

Is there an onSelect event or equivalent for HTML <select>?

what about changing the value of the select when the element gains focus, e.g (with jquery):

$("#locationtype").focus(function() {
    $("#locationtype").val('');
});

$("#locationtype").change(function() {
    if($("#locationtype").val() == 1) {
        $(".bd #mapphp").addClass('show');
        $("#invoerform").addClass('hide');
    }
    if($("#locationtype").val() == 2) {
        $(".lat").val('');
        $(".lon").val('');
    }
});

What is the best way to trigger onchange event in react js

You can simulate events using ReactTestUtils but that's designed for unit testing.

I'd recommend not using valueLink for this case and simply listening to change events fired by the plugin and updating the input's state in response. The two-way binding utils more as a demo than anything else; they're included in addons only to emphasize the fact that pure two-way binding isn't appropriate for most applications and that you usually need more application logic to describe the interactions in your app.

Disable all Database related auto configuration in Spring Boot

Also if you use Spring Actuator org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthContributorAutoConfiguration might be initializing DataSource as well.

How to update a record using sequelize for node?

I think using UPDATE ... WHERE as explained here and here is a lean approach

Project.update(
      { title: 'a very different title no' } /* set attributes' value */, 
      { where: { _id : 1 }} /* where criteria */
).then(function(affectedRows) {
Project.findAll().then(function(Projects) {
     console.log(Projects) 
})

Unresolved Import Issues with PyDev and Eclipse

In the properties for your pydev project, there's a pane called "PyDev - PYTHONPATH", with a sub-pane called "External Libraries". You can add source folders (any folder that has an __init__.py) to the path using that pane. Your project code will then be able to import modules from those source folders.

How do you Sort a DataTable given column and direction?

I assume "direction" is "ASC" or "DESC" and dt contains a column named "colName"

public static DataTable resort(DataTable dt, string colName, string direction)
{
    DataTable dtOut = null;
    dt.DefaultView.Sort = colName + " " + direction;
    dtOut = dt.DefaultView.ToTable();
    return dtOut;
}

OR without creating dtOut

public static DataTable resort(DataTable dt, string colName, string direction)
{
    dt.DefaultView.Sort = colName + " " + direction;
    dt = dt.DefaultView.ToTable();
    return dt;
}

Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--    

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
</head>
<body>

<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
Address:        <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form> 
</p>
</pre>
</body>
</html>

How do I bind the enter key to a function in tkinter?

I found one good thing about using bind is that you get to know the trigger event: something like: "You clicked with event = [ButtonPress event state=Mod1 num=1 x=43 y=20]" due to the code below:

self.submit.bind('<Button-1>', self.parse)
def parse(self, trigger_event):
        print("You clicked with event = {}".format(trigger_event))

Comparing the following two ways of coding a button click:

btn = Button(root, text="Click me to submit", command=(lambda: reply(ent.get())))
btn = Button(root, text="Click me to submit")
btn.bind('<Button-1>', (lambda event: reply(ent.get(), e=event)))
def reply(name, e = None):
    messagebox.showinfo(title="Reply", message = "Hello {0}!\nevent = {1}".format(name, e))

The first one is using the command function which doesn't take an argument, so no event pass-in is possible. The second one is a bind function which can take an event pass-in and print something like "Hello Charles! event = [ButtonPress event state=Mod1 num=1 x=68 y=12]"

We can left click, middle click or right click a mouse which corresponds to the event number of 1, 2 and 3, respectively. Code:

btn = Button(root, text="Click me to submit")
buttonClicks = ["<Button-1>", "<Button-2>", "<Button-3>"]
for bc in buttonClicks:
    btn.bind(bc, lambda e : print("Button clicked with event = {}".format(e.num)))

Output:

Button clicked with event = 1
Button clicked with event = 2
Button clicked with event = 3

How to margin the body of the page (html)?

Yeah a CSS primer will not hurt here so you can do two things: 1 - within the tags of your html you can open a style tag like this:

<style type="text/css">
  body {
   margin: 0px;
  }
  /*
   * this is the same as writing
   * body { margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px;}
   * I'm adding px here for clarity sake but the unit is not really needed if you have 0
   * look into em, pt and % for other unit types 
   * the rules are always clockwise: top, right, bottom, left
  */
</style>

2- the above though will only work on the page you have this code embeded, so if if you wanted to reuse this in 10 files, then you will have to copy it over on all 10 files, and if you wanted to make a change let's say have a margin of 5px instead, you would have to open all those files and make the edit. That's why using an external style sheet is a golden rule in front end coding. So save the body declaration in a separate file named style.css for example and from your add this to your html instead:

<link rel="stylesheet" type="text/css" href="style.css"/>

Now you can put this in the of all pages that will benefit from these styles and whenever needed to change them you will only need to do so in one place. Hope it helps. Cheers

How to add percent sign to NSString

If that helps in some cases, it is possible to use the unicode character:

NSLog(@"Test percentage \uFF05");

Capturing window.onbeforeunload

Yes what everybody says above.

For your immediate situation, instead of onChange, you can use onInput, new in html5. The input event is the same, but it'll fire upon every keystroke, regardless of the focus. Also works on selects and all the rest just like onChange.

Linear regression with matplotlib / numpy

This code:

from scipy.stats import linregress

linregress(x,y) #x and y are arrays or lists.

gives out a list with the following:

slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate

Source

How to create a zip archive of a directory in Python?

# import required python modules
# You have to install zipfile package using pip install

import os,zipfile

# Change the directory where you want your new zip file to be

os.chdir('Type your destination')

# Create a new zipfile ( I called it myfile )

zf = zipfile.ZipFile('myfile.zip','w')

# os.walk gives a directory tree. Access the files using a for loop

for dirnames,folders,files in os.walk('Type your directory'):
    zf.write('Type your Directory')
    for file in files:
        zf.write(os.path.join('Type your directory',file))

Why should I use an IDE?

I have used Emacs as my primary environment for both development and mail/news for about 10 year (1994-2004). I discovered the power of IDEs when I forced myself to learn Java in 2004, and to my surprise that I actually liked the IDE (IntelliJ IDEA).

I will not go into specific reasons since a lot of them have already been mentioned here -- just remember that the different people love different features. Me and a colleague used the same IDE, both of us used just a fraction of the features available, and we disliked each others way of using the IDE (but we both liked the IDE itself).

But there is one advantage with IDEs over Emacs/Vim related environments I want to focus on: You spend less time installing/configuring the features you want.

With Wing IDE (for Python) I'm ready to start developing 15-20 minutes after installation. No idea how many hours I would need to get the features I use up and running with Emacs/Vim. :)

vbscript output to console

I came across this post and went back to an approach that I used some time ago which is similar to @MadAntrax's.

The main difference is that it uses a VBScript user-defined class to wrap all the logic for switching to CScript and outputting text to the console, so it makes the main script a bit cleaner.

This assumes that your objective is to stream output to the console, rather than having output go to message boxes.

The cCONSOLE class is below. To use it, include the complete class at the end of your script, and then instantiate it right at the beginning of the script. Here is an example:

    Option Explicit

'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE

'// Now we can use the Consol object to write to and read from the console
With CONS

    '// Simply write a line
     .print "CSCRIPT Console demo script"

     '// Arguments are passed through correctly, if present
     .Print "Arg count=" & wscript.arguments.count

     '// List all the arguments on the console log
     dim ix
     for ix = 0 to wscript.arguments.count -1
        .print "Arg(" & ix & ")=" & wscript.arguments(ix)
     next

     '// Prompt for some text from the user
     dim sMsg : sMsg = .prompt( "Enter any text:" )

     '// Write out the text in a box
     .Box sMsg

     '// Pause with the message "Hit enter to continue"
     .Pause

End With     




'= =========== End of script - the cCONSOLE class code follows here

Here is the code for the cCONSOLE class

     CLASS cCONSOLE
 '= =================================================================
 '= 
 '=    This class provides automatic switch to CScript and has methods
 '=    to write to and read from the CSCript console. It transparently
 '=    switches to CScript if the script has been started in WScript.
 '=
 '= =================================================================

    Private oOUT
    Private oIN


    Private Sub Class_Initialize()
    '= Run on creation of the cCONSOLE object, checks for cScript operation


        '= Check to make sure we are running under CScript, if not restart
        '= then run using CScript and terminate this instance.
        dim oShell
        set oShell = CreateObject("WScript.Shell")

        If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
            '= Not running under CSCRIPT

            '= Get the arguments on the command line and build an argument list
            dim ArgList, IX
            ArgList = ""

            For IX = 0 to wscript.arguments.count - 1
                '= Add the argument to the list, enclosing it in quotes
                argList = argList & " """ & wscript.arguments.item(IX) & """"
            next

            '= Now restart with CScript and terminate this instance
            oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
            WScript.Quit

        End If

        '= Running under CScript so OK to continue
        set oShell = Nothing

        '= Save references to stdout and stdin for use with Print, Read and Prompt
        set oOUT = WScript.StdOut
        set oIN = WScript.StdIn

        '= Print out the startup box 
            StartBox
            BoxLine Wscript.ScriptName
            BoxLine "Started at " & Now()
            EndBox


    End Sub

    '= Utility methods for writing a box to the console with text in it

            Public Sub StartBox()

                Print "  " & String(73, "_") 
                Print " |" & Space(73) & "|"
            End Sub

            Public Sub BoxLine(sText)

                Print Left(" |" & Centre( sText, 74) , 75) & "|"
            End Sub

            Public Sub EndBox()
                Print " |" & String(73, "_") & "|"
                Print ""
            End Sub

            Public Sub Box(sMsg)
                StartBox
                BoxLine sMsg
                EndBox
            End Sub

    '= END OF Box utility methods


            '= Utility to center given text padded out to a certain width of text
            '= assuming font is monospaced
            Public Function Centre(sText, nWidth)
                dim iLen
                iLen = len(sText)

                '= Check for overflow
                if ilen > nwidth then Centre = sText : exit Function

                '= Calculate padding either side
                iLen = ( nWidth - iLen ) / 2

                '= Generate text with padding
                Centre = left( space(iLen) & sText & space(ilen), nWidth )
            End Function



    '= Method to write a line of text to the console
    Public Sub Print( sText )

        oOUT.WriteLine sText
    End Sub

    '= Method to prompt user input from the console with a message
    Public Function Prompt( sText )
        oOUT.Write sText
        Prompt = Read()
    End Function

    '= Method to read input from the console with no prompting
    Public Function Read()
        Read = oIN.ReadLine
    End Function

    '= Method to provide wait for n seconds
    Public Sub Wait(nSeconds)
        WScript.Sleep  nSeconds * 1000 
    End Sub

    '= Method to pause for user to continue
    Public Sub Pause
        Prompt "Hit enter to continue..."
    End Sub


 END CLASS

Set default host and port for ng serve in config file

If your are on windows you can do it this way :

  1. In your project root directory, Create file run.bat
  2. Add your command with your choice of configurations in this file. For Example

ng serve --host 192.168.1.2 --open

  1. Now you can click and open this file whenever you want to serve.

This not standard way but comfortable to use (which I feel).

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

In my case it was a bit different

In the Prefix Header there was a define missing

#ifdef DEBUG
#   define TWDLog(fmt, ...) NSLog((@"\n%s\n" fmt), __PRETTY_FUNCTION__, ##__VA_ARGS__)
#else
#   define TWDLog(...)
#endif

So search for PROJECTNAME-Prefix.pch and check if it has something missing in both projects

Fastest way to convert an iterator to a list

since python 3.5 you can use * iterable unpacking operator:

user_list = [*your_iterator]

but the pythonic way to do it is:

user_list  = list(your_iterator)

How to uncheck a checkbox in pure JavaScript?

There is another way to do this:

//elem - get the checkbox element and then
elem.setAttribute('checked', 'checked'); //check
elem.removeAttribute('checked'); //uncheck

What's the function like sum() but for multiplication? product()?

There's a prod() in numpy that does what you're asking for.

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

I had this same error while trying to include a PHP file in my Wordpress theme. I was able to get around it by referencing the file name using dirname(__FILE__). I couldn't use relative paths since my file was going to be included in different places throughout the theme, so something like require_once '../path-to/my-file' wouldn't work.

Replacing require_once get_template_directory_uri() . '/path-to/my-file' with require_once dirname( __FILE__ ) . '/path-to/my-file' did the trick.

R: Select values from data table in range

One should also consider another intuitive way to do this using filter() from dplyr. Here are some examples:

set.seed(123)
df <- data.frame(name = sample(letters, 100, TRUE),
                 date = sample(1:500, 100, TRUE))
library(dplyr)
filter(df, date < 50) # date less than 50
filter(df, date %in% 50:100) # date between 50 and 100
filter(df, date %in% 1:50 & name == "r") # date between 1 and 50 AND name is "r"
filter(df, date %in% 1:50 | name == "r") # date between 1 and 50 OR name is "r"

# You can also use the pipe (%>%) operator
df %>% filter(date %in% 1:50 | name == "r")

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

I had the same error and I started the SQL Server Express service and it worked. Hope this helps.

How to INNER JOIN 3 tables using CodeIgniter

I believe that using CodeIgniters active record framework that you would just use two join statements one after the other.
eg:

$this->db->select('*');
$this->db->from('table1');
$this->db->join('table1', 'table1.id = table2.id');
$this->db->join('table1', 'table1.id = table3.id');
$query = $this->db->get();

Give that a try and see how it goes.

How can I extract all values from a dictionary in Python?

If you want all of the values, use this:

dict_name_goes_here.values()

If you want all of the keys, use this:

dict_name_goes_here.keys()

IF you want all of the items (both keys and values), I would use this:

dict_name_goes_here.items()

Clear listview content?

It's simple .First you should clear your collection and after clear list like this code :

 yourCollection.clear();
 setListAdapter(null);

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

How can bcrypt have built-in salts?

To make things even more clearer,

Registeration/Login direction ->

The password + salt is encrypted with a key generated from the: cost, salt and the password. we call that encrypted value the cipher text. then we attach the salt to this value and encoding it using base64. attaching the cost to it and this is the produced string from bcrypt:

$2a$COST$BASE64

This value is stored eventually.

What the attacker would need to do in order to find the password ? (other direction <- )

In case the attacker got control over the DB, the attacker will decode easily the base64 value, and then he will be able to see the salt. the salt is not secret. though it is random. Then he will need to decrypt the cipher text.

What is more important : There is no hashing in this process, rather CPU expensive encryption - decryption. thus rainbow tables are less relevant here.

CMake does not find Visual C++ compiler

In my case there was an environment variable set which was the reason for this error. The problem was solved after deleting cxx_flags from the environment variables.

How do I use Linq to obtain a unique list of properties from a list of objects?

Using straight Linq, with the Distinct() extension:

var idList = (from x in yourList select x.ID).Distinct();

How to connect to a secure website using SSL in Java with a pkcs12 file?

I cannot comment because of the 50pts threshhold, but I don't think that the answer provided in https://stackoverflow.com/a/537344/1341220 is correct. What you are actually describing is how you insert server certificates into the systems default truststore:

$JAVA_HOME/jre/lib/security/cacerts, password: changeit)

This works, indeed, but it means that you did not really specify a trust store local to your project, but rather accepted the certificate universially in your system.

You actually never use your own truststore that you defined here:

System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

Distinct pair of values SQL

If you just want a count of the distinct pairs.

The simplest way to do that is as follows SELECT COUNT(DISTINCT a,b) FROM pairs

The previous solutions would list all the pairs and then you'd have to do a second query to count them.

Install a Windows service using a Windows command prompt?

Perform the following:

  1. Start up the command prompt (CMD) with administrator rights.
  2. Type c:\windows\microsoft.net\framework\v4.0.30319\installutil.exe [your windows service path to exe]
  3. Press return and that's that!

It's important to open with administrator rights otherwise you may find errors that come up that don't make sense. If you get any, check you've opened it with admin rights first!

To open with admin rights, right click 'Command Prompt' and select 'Run as administrator'.

Source: http://coderamblings.wordpress.com/2012/07/24/how-to-install-a-windows-service-using-the-command-prompt/

Getting the Username from the HKEY_USERS values

for /f "tokens=8 delims=\" %a in ('reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist" ^| find "UsrClass.dat"') do echo %a

PHP Regex to get youtube video ID?

I think you are trying to do this.

<?php
  $video = 'https://www.youtube.com/watch?v=u00FY9vADfQ';
  $parsed_video = parse_url($video, PHP_URL_QUERY);
  parse_str($parsed_video, $arr);
?>
<iframe
src="https://www.youtube.com/embed/<?php echo $arr['v'];  ?>"
frameborder="0">
</iframe>

Bootstrap - How to add a logo to navbar class?

<a class="navbar-brand" href="#" style="padding:0px;">
  <img src="mylogo.png" style="height:100%;">
</a>

For including a text:

<a class="navbar-brand" href="#" style="padding:0px;">
  <img src="mylogo.png" style="height:100%;display:inline-block;"><span>text</span>
</a>

What is the difference between VFAT and FAT32 file systems?

FAT32 along with FAT16 and FAT12 are File System Types, but vfat along with umsdos and msdos are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos driver don't have long filenames (they are 8.3 format). vfat is the most common driver for mounting FAT32 file systems nowadays.

Source: this wikipedia article

Output of commands like df and lsblk indeed show vfat as the File System Type. But sudo file -sL /dev/<partition> shows FAT (32 bit) if a File System is FAT32.

You can confirm vfat is a module and not a File System Type by running modinfo vfat.

Subtract a value from every number in a list in Python?

To clarify an already posted solution due to questions in the comments

import numpy

array = numpy.array([49, 51, 53, 56])
array = array - 13

will output:

array([36, 38, 40, 43])

How can I convert JSON to a HashMap using Gson?

This code works:

Gson gson = new Gson(); 
String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
Map<String,Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(json, map.getClass());

Enter export password to generate a P12 certificate

OpenSSL command line app does not display any characters when you are entering your password. Just type it then press enter and you will see that it is working.

You can also use openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -password pass:YourPassword to pass the password YourPassword from command line. Please take a look at section Pass Phrase Options in OpenSSL manual for more information.

List of IP Space used by Facebook

The list from 2020-05-23 is:

31.13.24.0/21
31.13.64.0/18
45.64.40.0/22
66.220.144.0/20
69.63.176.0/20
69.171.224.0/19
74.119.76.0/22
102.132.96.0/20
103.4.96.0/22
129.134.0.0/16
147.75.208.0/20
157.240.0.0/16
173.252.64.0/18
179.60.192.0/22
185.60.216.0/22
185.89.216.0/22
199.201.64.0/22
204.15.20.0/22

The method to fetch this list is already documented on Facebook's Developer site, you can make a whois call to see all IPs assigned to Facebook:

whois -h whois.radb.net -- '-i origin AS32934' | grep ^route

How to rename a directory/folder on GitHub website?

As a newer user to git, I took the following approach. From the command line, I was able to rename a folder by creating a new folder, copying the files to it, adding and commiting locally and pushing. These are my steps:

$mkdir newfolder 
$cp oldfolder/* newfolder
$git add newfolder 
$git commit -m 'start rename'     
$git push                             #New Folder appears on Github      
$git rm -r oldfolder
$git commit -m 'rename complete' 
$git push                             #Old Folder disappears on Github  

Probably a better way, but it worked for me.

How to use sed to remove the last n lines of a file

In docker, this worked for me:

head --lines=-N file_path >> file_path

How to apply filters to *ngFor?

A simple solution that works with Angular 6 for filtering a ngFor, it's the following:

_x000D_
_x000D_
<span *ngFor="item of itemsList"  >_x000D_
  <div *ngIf="yourCondition(item)">_x000D_
    _x000D_
    your code_x000D_
    _x000D_
  </div>_x000D_
</span
_x000D_
_x000D_
_x000D_

Spans are useful because does not inherently represent anything.

Git adding files to repo

After adding files to the stage, you need to commit them with git commit -m "comment" after git add .. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>.

Does Android support near real time push notification?

XMPP is a good solution. I have used it for a push enabled, realtime, Android application. XMPP is powerful, highly extensible and easy to integrate and use.

There are loads of free XMPP servers (though out of courtesy you shouldn't abuse them) and there are open source servers you can run on one of your own boxes. OpenFire is an excellent choice.

The library you want isn't Smack as noted above, it's aSmack. But note, this is a build environment - you will have to build the library.

This is a calculation I did on battery life impact of an XMPP solution:

The Android client must maintain a persistent TCP connection by waking up periodically to send a heartbeat to the XMPP server.
This clearly imposes a cost in terms of power usage. An estimate of this cost is provided below:

  • Using a 1400mAh battery (as supplied in the Nexus One and HTC Desire)
  • An idle device, connected to an 3G network, uses approximately 5mA
  • The wake-up, heartbeat, sleep cycle occurs every 5 minutes, takes three seconds to complete and uses 300mA
  • The cost in battery usage per hour is therefore:
    • 36 seconds 300mA = 3mAh sending heartbeat
    • 3600 seconds 5mA = 5mAh at idle
    • 4:95 + 3 = 7:95mAh combined
  • A 1400mAh battery lasts approximately 11.6 days at idle and 7.3 days when running the application, which represents an approximate 37% reduction in battery life.
  • However, a reduction in battery life of 37% represents the absolute worst case in practice given that devices are rarely completely idle.

What is meant by the term "hook" in programming?

A chain of hooks is a set of functions in which each function calls the next. What is significant about a chain of hooks is that a programmer can add another function to the chain at run time. One way to do this is to look for a known location where the address of the first function in a chain is kept. You then save the value of that function pointer and overwrite the value at the initial address with the address of the function you wish to insert into the hook chain. The function then gets called, does its business and calls the next function in the chain (unless you decide otherwise). Naturally, there are a number of other ways to create a chain of hooks, from writing directly to memory to using the metaprogramming facilities of languages like Ruby or Python.

An example of a chain of hooks is the way that an MS Windows application processes messages. Each function in the processing chain either processes a message or sends it to the next function in the chain.

How to communicate between Docker containers via "hostname"

The new networking feature allows you to connect to containers by their name, so if you create a new network, any container connected to that network can reach other containers by their name. Example:

1) Create new network

$ docker network create <network-name>       

2) Connect containers to network

$ docker run --net=<network-name> ...

or

$ docker network connect <network-name> <container-name>

3) Ping container by name

docker exec -ti <container-name-A> ping <container-name-B> 

64 bytes from c1 (172.18.0.4): icmp_seq=1 ttl=64 time=0.137 ms
64 bytes from c1 (172.18.0.4): icmp_seq=2 ttl=64 time=0.073 ms
64 bytes from c1 (172.18.0.4): icmp_seq=3 ttl=64 time=0.074 ms
64 bytes from c1 (172.18.0.4): icmp_seq=4 ttl=64 time=0.074 ms

See this section of the documentation;

Note: Unlike legacy links the new networking will not create environment variables, nor share environment variables with other containers.

This feature currently doesn't support aliases

Use jQuery to change value of a label

I seem to have a blind spot as regards your html structure, but I think that this is what you're looking for. It should find the currently-selected option from the select input, assign its text to the newVal variable and then apply that variable to the value attribute of the #costLabel label:

jQuery

$(document).ready(
  function() {
    $('select[name=package]').change(
      function(){
        var newText = $('option:selected',this).text();
        $('#costLabel').text('Total price: ' + newText);
      }
      );
  }
  );

html:

  <form name="thisForm" id="thisForm" action="#" method="post">
  <fieldset>
    <select name="package" id="package">
        <option value="standard">Standard - &euro;55 Monthly</option>
        <option value="standardAnn">Standard - &euro;49 Monthly</option>            
        <option value="premium">Premium - &euro;99 Monthly</option>
        <option value="premiumAnn" selected="selected">Premium - &euro;89 Monthly</option>            
        <option value="platinum">Platinum - &euro;149 Monthly</option>
        <option value="platinumAnn">Platinum - &euro;134 Monthly</option>   
    </select>
  </fieldset>
    
    <fieldset>
      <label id="costLabel" name="costLabel">Total price: </label>
    </fieldset>
  </form>

Working demo of the above at: JS Bin

Convert string to List<string> in one line?

string given="Welcome To Programming";
List<string> listItem= given.Split(' ').ToList();//Split according to space in the string and added into the list

output:

Welcome

To 

Programming

Alternating Row Colors in Bootstrap 3 - No Table

Since you are using bootstrap and you want alternating row colors for every screen sizes you need to write separate style rules for all the screen sizes.

/* For small screen */
.row :nth-child(even){
  background-color: #dcdcdc;
}
.row :nth-child(odd){
  background-color: #aaaaaa;
}

/* For medium screen */    
@media (min-width: 768px) {
    .row :nth-child(4n), .row :nth-child(4n-1) {
        background: #dcdcdc;
    }
    .row :nth-child(4n-2), .row :nth-child(4n-3) {
        background: #aaaaaa;
    }
}

/* For large screen */
@media (min-width: 992px) {
    .row :nth-child(6n), .row :nth-child(6n-1), .row :nth-child(6n-2) {
        background: #dcdcdc;
    }
    .row :nth-child(6n-3), .row :nth-child(6n-4), .row :nth-child(6n-5) {
        background: #aaaaaa;
    }
}

Working FIDDLE
I have also included the bootstrap CSS here.

Environment variable in Jenkins Pipeline

You can access the same environment variables from groovy using the same names (e.g. JOB_NAME or env.JOB_NAME).

From the documentation:

Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):

env.MYTOOL_VERSION = '1.33'
node {
  sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}

These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.

For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job enter image description here

Enabling/installing GD extension? --without-gd

I've PHP 7.3 and Nginx 1.14 on Ubuntu 18.

# it installs php7.3-gd for the moment
# and restarts PHP 7.3 FastCGI Process Manager: php-fpm7.3.
sudo apt-get install php-gd

# after I've restarted Nginx
sudo /etc/init.d/nginx restart

Works!

How to get nth jQuery element

If I understand your question correctly, you can always just wrap the get function like so:

var $someJqueryEl = $($('.myJqueryEls').get(3));

How do I kill background processes / jobs when my shell script exits?

To clean up some mess, trap can be used. It can provide a list of stuff executed when a specific signal arrives:

trap "echo hello" SIGINT

but can also be used to execute something if the shell exits:

trap "killall background" EXIT

It's a builtin, so help trap will give you information (works with bash). If you only want to kill background jobs, you can do

trap 'kill $(jobs -p)' EXIT

Watch out to use single ', to prevent the shell from substituting the $() immediately.

Sass Variable in CSS calc() function

I have tried this then i fixed my issue. It will calculate all media-breakpoint automatically by given rate (base-size/rate-size)


$base-size: 16;
$rate-size-xl: 24;

    // set default size for all cases;
    :root {
      --size: #{$base-size};
    }

    // if it's smaller then LG it will set size rate to 16/16;
    // example: if size set to 14px, it will be 14px * 16 / 16 = 14px
    @include media-breakpoint-down(lg) {
      :root {
        --size: #{$base-size};
      }
    }

    // if it is bigger then XL it will set size rate to 24/16;
    // example: if size set to 14px, it will be 14px * 24 / 16 = 21px
    @include media-breakpoint-up(xl) {
      :root {
        --size: #{$rate-size-xl};
      }
    }

@function size($px) {
   @return calc(#{$px} / $base-size * var(--size));
}

div {
  font-size: size(14px);
  width: size(150px);
}

How do I format XML in Notepad++?

All the previous answers do not define how to add the plugin manager in your Notepad++ installation.

This is for the folks who do not see the the plugin manager in the plugin tab

Download the plugin manager from this link - this is for the 64-bit plugin manager. Once you download the plugin manager, paste in the plugin folder. This is was my location of plugin folder: C:\Program Files\Notepad++\plugins

Enter image description here

After pasting the .dll file restart Notepad++. Now you can install any plugin. To install a plugin, click on the plugin tab, then go to plugin manager and select the plugin whatever you want.

Docker is installed but Docker Compose is not ? why?

I suggest using the official pkg on Mac. I guess docker-compose is no longer included with docker by default: https://docs.docker.com/toolbox/toolbox_install_mac/

How to select data where a field has a min value in MySQL?

this will give you result that has the minimum price on all records.

SELECT *
FROM pieces
WHERE price =  ( SELECT MIN(price) FROM pieces )

Where do I find the current C or C++ standard documents?

ISO standards cost money, from a moderate amount (for a PDF version), to a bit more (for a book version).

While they aren't finalised however, they can usually be found online, as drafts. Most of the times the final version doesn't differ significantly from the last draft, so while not perfect, they'll suit just fine.

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

For me what worked in ubuntu image:

FROM ubuntu:xenial
USER root
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && apt-get install --no-install-recommends -y locales && rm -rf /var/lib/apt/lists/*
RUN echo "LC_ALL=en_US.UTF-8" >> /etc/environment
RUN echo "en_US.UTF-8 UTF-8" >> /etc/locale.gen
RUN echo "LANG=en_US.UTF-8" > /etc/locale.conf

How do I pull files from remote without overwriting local files?

You can stash your local changes first, then pull, then pop the stash.

git stash
git pull origin master
git stash pop

Anything that overrides changes from remote will have conflicts which you will have to manually resolve.

How to resize an image to fit in the browser window?

Resize Image to Fit the Screen by the Longest Side maintaining its Aspect Ratio

img[src$="#fit"] {
    width: 100vw;
    height: auto;
    max-width: none;
    max-height: 100vh;
    object-fit: contain;
}
  • width: 100vw - image width will be 100% of view port

  • height: auto - image height will be scaled proportionally

  • max-height: 100vw - if image height would become more than view port it will be decreased to fit the screen, consequently image width will be decreased because of the following property

  • object-fit: contain - the replaced content is scaled to maintain its aspect ratio while fitting within the element's content box

    Note: object-fit is fully supported only since IE 16.0

Send XML data to webservice using php curl

Check this one. It will work.

function fetch($i1,$i2,$i3,$i4)
{
$input_data = '<I> 
                <i1>'.$i1.'</i1> 
                <i2>'.$i2.'</i2> 
                <i3>'.$i2.'</i3> 
                <i4>'.$i3.'</i4> 
              </I>';
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_PORT => "8080",
  CURLOPT_URL => "http://192.168.1.100:8080/avaliablity",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $input_data,
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache",
    "Content-Type: application/xml"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
}

fetch('i1','i2','i3','i4');

How to set an HTTP proxy in Python 2.7?

You can try downloading the Windows binaries for pip from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip.

For using pip to download other modules, see @Ben Burn's answer.

Number of elements in a javascript object

AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.

Probably the closest you'll get is something like this

// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this ) i++;
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3

But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?

Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this )
  {
      if ( 'function' == typeof this[p] ) continue;
      i++;
  }
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2

In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Error is that you are using 'ID' in lower case like 'checkbox1' but when you loop json object its return in upper case. So you need to replace checkbox1 to CHECKBOX1.

In my case :-

var response = jQuery.parseJSON(response);

$.each(response, function(key, value) {
   $.each(value, function(key, value){
        $('#'+key).val(value);
   });
});

Before

  <input type="text" name="abc" id="abc" value="">

I am getting the same error but when i replace the id in html code its work fine.

After

<input type="text" name="abc" id="ABC" value="">

Fixed positioning in Mobile Safari

This may interest you. It's Apple Dev support page.
http://developer.apple.com/library/ios/#technotes/tn2010/tn2262/

Read the point "4. Modify code that relies on CSS fixed positioning" and you will find out that there is very good reason why Apple made the conscious decision to handle fixed position as static.

Express.js - app.listen vs server.listen

Just for punctuality purpose and extend a bit Tim answer.
From official documentation:

The app returned by express() is in fact a JavaScript Function, DESIGNED TO BE PASSED to Node’s HTTP servers as a callback to handle requests.

This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

app.listen = function() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Ruby combining an array into one string

Here's my solution:

@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>

Proxies with Python 'Requests' module

If you'd like to persisist cookies and session data, you'd best do it like this:

import requests

proxies = {
    'http': 'http://user:[email protected]:3128',
    'https': 'https://user:[email protected]:3128',
}

# Create the session and set the proxies.
s = requests.Session()
s.proxies = proxies

# Make the HTTP request through the session.
r = s.get('http://www.showmemyip.com/')

Eloquent ORM laravel 5 Get Array of ids

read about the lists() method

$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()

What steps are needed to stream RTSP from FFmpeg?

You can use FFserver to stream a video using RTSP.

Just change console syntax to something like this:

ffmpeg -i space.mp4 -vcodec libx264 -tune zerolatency -crf 18 http://localhost:1234/feed1.ffm

Create a ffserver.config file (sample) where you declare HTTPPort, RTSPPort and SDP stream. Your config file could look like this (some important stuff might be missing):

HTTPPort 1234
RTSPPort 1235

<Feed feed1.ffm>
        File /tmp/feed1.ffm
        FileMaxSize 2M
        ACL allow 127.0.0.1
</Feed>

<Stream test1.sdp>
    Feed feed1.ffm
    Format rtp
    Noaudio
    VideoCodec libx264
    AVOptionVideo flags +global_header
    AVOptionVideo me_range 16
    AVOptionVideo qdiff 4
    AVOptionVideo qmin 10
    AVOptionVideo qmax 51
    ACL allow 192.168.0.0 192.168.255.255
</Stream>

With such setup you can watch the stream with i.e. VLC by typing:

rtsp://192.168.0.xxx:1235/test1.sdp

Here is the FFserver documentation.

How to remove the URL from the printing page?

@media print { a[href]:after { content: none !important; } }

JavaScript: set dropdown selected item based on option text

This works in latest Chrome, FireFox and Edge, but not IE11:

document.evaluate('//option[text()="Yahoo"]', document).iterateNext().selected = 'selected';

And if you want to ignore spaces around the title:

document.evaluate('//option[normalize-space(text())="Yahoo"]', document).iterateNext().selected = 'selected'

" app-release.apk" how to change this default generated apk name

(EDITED to work with Android Studio 3.0 and Gradle 4)

I was looking for a more complex apk filename renaming option and I wrote this solution that renames the apk with the following data:

  • flavor
  • build type
  • version
  • date

You would get an apk like this: myProject_dev_debug_1.3.6_131016_1047.apk.

You can find the whole answer here. Hope it helps!

In the build.gradle:

android {

    ...

    buildTypes {
        release {
            minifyEnabled true
            ...
        }
        debug {
            minifyEnabled false
        }
    }

    productFlavors {
        prod {
            applicationId "com.feraguiba.myproject"
            versionCode 3
            versionName "1.2.0"
        }
        dev {
            applicationId "com.feraguiba.myproject.dev"
            versionCode 15
            versionName "1.3.6"
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            def project = "myProject"
            def SEP = "_"
            def flavor = variant.productFlavors[0].name
            def buildType = variant.variantData.variantConfiguration.buildType.name
            def version = variant.versionName
            def date = new Date();
            def formattedDate = date.format('ddMMyy_HHmm')

            def newApkName = project + SEP + flavor + SEP + buildType + SEP + version + SEP + formattedDate + ".apk"

            outputFileName = new File(newApkName)
        }
    }
}

Do fragments really need an empty constructor?

Yes, as you can see the support-package instantiates the fragments too (when they get destroyed and re-opened). Your Fragment subclasses need a public empty constructor as this is what's being called by the framework.

How to find out which processes are using swap space in Linux?

I suppose you could get a good guess by running top and looking for active processes using a lot of memory. Doing this programatically is harder---just look at the endless debates about the Linux OOM killer heuristics.

Swapping is a function of having more memory in active use than is installed, so it is usually hard to blame it on a single process. If it is an ongoing problem, the best solution is to install more memory, or make other systemic changes.

MySQL high CPU usage

First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.

Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.

Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.

Some other things you can check would be to run the following query while the CPU load is high:

SHOW PROCESSLIST;

This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).

You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.

You'll also probably want to give the following a read over as they contain some good information.

It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.

CodeIgniter htaccess and URL rewrite issues

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /dmizone_bkp
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond $1 !^(index\.php|images|robots\.txt|css|docs|js|system)
   RewriteRule ^(.*)$ /dmizone_bkp/index.php?/$1 [L]
</IfModule> 

How can I explicitly free memory in Python?

(del can be your friend, as it marks objects as being deletable when there no other references to them. Now, often the CPython interpreter keeps this memory for later use, so your operating system might not see the "freed" memory.)

Maybe you would not run into any memory problem in the first place by using a more compact structure for your data. Thus, lists of numbers are much less memory-efficient than the format used by the standard array module or the third-party numpy module. You would save memory by putting your vertices in a NumPy 3xN array and your triangles in an N-element array.

How to use AND in IF Statement

I think you should append .value in IF statement:

If Cells(i, "A").Value <> "Miami" And Cells(i, "D").Value <> "Florida" Then
    Cells(i, "C").Value = "BA"
End IF

Close Bootstrap modal on form submit

You can use one of this two options:

1) Add data-dismiss to the submit button i.e.

<button type="submit" class="btn btn-success" data-dismiss="modal"><i class="glyphicon glyphicon-ok"></i> Save</button>

2) Do it in JS like

$('#frmStudent').submit(function() {
    $('#StudentModal').modal('hide');
});

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes. So when you set

myObject.prop = '123';

It doesn't look up the chain, but when you set

myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

Based on kynan's answer, here are the same aliases, modified so they can handle spaces and initial dashes in filenames:

accept-ours = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --ours -- \"$@\"; git add -u -- \"$@\"; }; f"
accept-theirs = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --theirs -- \"$@\"; git add -u -- \"$@\"; }; f"

Cannot stop or restart a docker container

All the docker: start | restart | stop | rm --force | kill commands may not work if the container is stuck. You can always restart the docker daemon. However, if you have other containers running, that may not be the option. What you can do is:

ps aux | grep <<container id>> | awk '{print $1 $2}'

The output contains:

<<user>><<process id>>

Then kill the process associated with the container like so:

sudo kill -9 <<process id from above command>>

That will kill the container and you can start a new container with the right image.

How do getters and setters work?

You may also want to read "Why getter and setter methods are evil":

Though getter/setter methods are commonplace in Java, they are not particularly object oriented (OO). In fact, they can damage your code's maintainability. Moreover, the presence of numerous getter and setter methods is a red flag that the program isn't necessarily well designed from an OO perspective.

This article explains why you shouldn't use getters and setters (and when you can use them) and suggests a design methodology that will help you break out of the getter/setter mentality.

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});
});

CSS:

#loading-img {
    background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;
}

And a demo with animated image.

What does HTTP/1.1 302 mean exactly?

A 302 status code is HTTP response status code indicating that the requested resource has been temporarily moved to a different URI. Since the location or current redirection directive might be changed in the future, a client that receives a 302 Found response code should continue to use the original URI for future requests.

An HTTP response with this status code will additionally provide a URL in the header field Location. This is an invitation to the user agent (e.g. a web browser) to make a second, otherwise identical, request to the new URL specified in the location field. The end result is a redirection to the new URL.

"Could not find or load main class" Error while running java program using cmd prompt

For a lot of us, at least for me, I think the class path hierarchy is not intuitive since I'm working inside a directory structure and it feels like that ought to be it.

Java is looking at the name of the class based on it's package path, not just the file path.

It doesn't matter if: i'm in the local directory ./packagefoo/MainClass, or a directory up ./packagefoo/, or one down ./packagefoo/MainClass/foo.

The command "java packagefoo.MainClass" is running off the root %CLASSPATH% which means something significant to Java. Then from there it traverses package names, not path names like us lay coders would expect.

So if my CLASSPATH is set to %CWD%/, then "java packagefoo.MainClass" will work. If I set the CLASSPATH to %CWD%/packagefoo/ then packagefoo.MainClass can't be found. Always "java MainClass" means nothing, if it is a member of "package", until I rip out the java code "package packagefoo;" and move the Class File up a directory.

In fact if I change "package packagefoo;" to "package foopackage;" I have to create a subfolder under CLASSPATH/foopackage or foopackage.MainClass stops working again.

To make matters worse, Between PATH, CLASSPATH, JAVAHOME, for Windows, JDeveloper, Oracle Database, and every user name it was installed under, I think a coder trying to just get something up fast ends up brute forcing path variables and structure until something works without understanding what it means.

at least i did.

HTML5 Canvas Rotate Image

Why not do it for the entire page. At page load detect all images and continuously rotate all of them.

 var RotationCollection = {
    rotators: [],
    start_action: function (showBorders, isoverlap) {
        try {
            var canvasTemplate = '<canvas id="_ID_" width="350" height="350"  ></canvas>';

            var ja = 5;
            $.each($("img"), function (index, val) {
                var newID = "can_" + index;
                var can = canvasTemplate.replace("_ID_", newID);

                if (showBorders == true) $(can).insertAfter($(val)).css({ "border": "solid thin black", "box-shadow": "5px 5px 10px 2px black", "border-raduis": "15px" });
                else $(can).insertAfter($(val));
                $(val).remove();

                var curRot = new RotationClass(newID, $(val).attr('src'), ja  * ((0 == index % 2) ? -1 : 1), isoverlap);
                RotationCollection.rotators[index] = curRot;
                ja += 5;
                //return false;
            });
            window.setInterval(function () {
                $.each(RotationCollection.rotators, function (index, value) {
                    value.drawRotatedImage();
                })
            }, 500);
        }
        catch (err) {
            console.log(err.message);
        }
    }
};
function RotationClass(canvasID, imgSrc, jumgAngle, overlap) {
    var self = this;
    self.overlap = overlap;
    self.angle = parseInt(45);
    self.image = {};
    self.src = imgSrc;
    self.canvasID = canvasID;
    self.jump = parseInt(jumgAngle);
    self.start_action = function () {
        var image = new Image();
        var canvas = document.getElementById(self.canvasID);
        image.onload = function () {
            self.image = image;
            canvas.height = canvas.width = Math.sqrt(image.width * image.width + image.height * image.height);
            self.drawRotatedImage(self);
        };
        image.src = self.src;
    }
    self.start_action();
    this.drawRotatedImage = function () {
        var self = this;
        self.angle += self.jump;
        var canvas = document.getElementById(self.canvasID);
        var ctx = canvas.getContext("2d");
        ctx.save();
        if (self.overlap) ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.translate(canvas.width / 2, canvas.height / 2);
        ctx.rotate(self.angle * Math.PI / 180);
        ctx.drawImage(self.image, -self.image.width / 2, -self.image.height / 2);
        ctx.restore();
    }
}
var theApp = {
    start_Action: function () {
        RotationCollection.start_action(true, true);
    }
};
$(document).ready(theApp.start_Action);

Please check out for theApp.start_Action where all action begins The HTML can be as follows:

 <p>
    Deepika Padukone.<br />
    <img alt="deepika" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSExIWFhUXFRUVFRYVFRUVFRUVFxUWFxUVFRYYHSggGBolHRUVITEhJSkrLi4uFx8zODMsNygtLisBCgoKDg0OGhAQGi8lHyUtLSstLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIAK0BJAMBIgACEQEDEQH/xAAcAAAABwEBAAAAAAAAAAAAAAABAgMEBQYHAAj/xAA+EAABAwEFBAcGBQMDBQAAAAABAAIRAwQFEiExBkFRYRMicYGRobEHMkJSwdEjYnKC8BUz4RRD8RckU6LS/8QAGQEAAwEBAQAAAAAAAAAAAAAAAAIDAQQF/8QAIhEAAgICAgIDAQEAAAAAAAAAA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F60V5f1sQX94j/5Jn90T2NR7WxV/RO90Kf1jIyPSXZ5z6G/EI79q/rs/uUv8T6mF0oP2b/9qZ7FbejBugjIyC9/9+QPYqMjNQ6fCNj4oyMjz59sqj0MbP4RGRkZD10JZ//Z" />
</p>

Some options to overlap rotations, borders are also added

How To: Best way to draw table in console app (C#)

Use MarkDownLog library (you can find it on NuGet)

you can simply use the extension ToMarkdownTable() to any collection, it does all the formatting for you.

 Console.WriteLine(
    yourCollection.Select(s => new
                    {
                        column1 = s.col1,
                        column2 = s.col2,
                        column3 = s.col3,
                        StaticColumn = "X"
                    })
                    .ToMarkdownTable());

Output looks something like this:

Column1  | Column2   | Column3   | StaticColumn   
--------:| ---------:| ---------:| --------------
         |           |           | X              

Tuple unpacking in for loops

Take this code as an example:

elements = ['a', 'b', 'c', 'd', 'e']
index = 0

for element in elements:
  print element, index
  index += 1

You loop over the list and store an index variable as well. enumerate() does the same thing, but more concisely:

elements = ['a', 'b', 'c', 'd', 'e']

for index, element in enumerate(elements):
  print element, index

The index, element notation is required because enumerate returns a tuple ((1, 'a'), (2, 'b'), ...) that is unpacked into two different variables.