Programs & Examples On #Kohana orm

ORM module of Kohana HMVC PHP5 Framework

Create thumbnail image

The following code will write an image in proportional to the response, you can modify the code for your purpose:

public void WriteImage(string path, int width, int height)
{
    Bitmap srcBmp = new Bitmap(path);
    float ratio = srcBmp.Width / srcBmp.Height;
    SizeF newSize = new SizeF(width, height * ratio);
    Bitmap target = new Bitmap((int) newSize.Width,(int) newSize.Height);
    HttpContext.Response.Clear();
    HttpContext.Response.ContentType = "image/jpeg";
    using (Graphics graphics = Graphics.FromImage(target))
    {
        graphics.CompositingQuality = CompositingQuality.HighSpeed;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height);
        using (MemoryStream memoryStream = new MemoryStream()) 
        {
            target.Save(memoryStream, ImageFormat.Jpeg);
            memoryStream.WriteTo(HttpContext.Response.OutputStream);
        }
    }
    Response.End();
}

JavaScript "cannot read property "bar" of undefined

Just check for it before you pass to your function. So you would pass:

thing.foo ? thing.foo.bar : undefined

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

jQuery multiselect drop down menu

You could hack your own, not relying on jQuery plugins... though you'd need to keep track externally (in JS) of selected items since the transition would remove the selected state info:

<head>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
  <script type='text/javascript'>
    $(window).load(function(){
      $('#transactionType').focusin(function(){
        $('#transactionType').attr('multiple', true);
      });
      $('#transactionType').focusout(function(){
        $('#transactionType').attr('multiple', false);
      });
    });>  
  </script>
</head>
<body>
  <select id="transactionType">
    <option value="ALLOC">ALLOC</option>
    <option value="LOAD1">LOAD1</option>
    <option value="LOAD2">LOAD2</option>
  </select>  
</body>

Why is this rsync connection unexpectedly closed on Windows?

i get the solution. i've using cygwin and this is the problem the rsync command for Windows work only in windows shell and works in the windows powershell.

A few times it has happened the same error between two linux boxes. and appears to be by incompatible versions of rsync

Use SELECT inside an UPDATE query

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

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

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

How to add action listener that listens to multiple buttons

The first problem is that button1 is a local variable of the main method, so the actionPerformed method doesn't have access to it.

The second problem is that the ActionListener interface is implemented by the class calc, but no instance of this class is created in the main method.

The usual way to do what you want is to create an instance of calc and make button1 a field of the calc class.

How to use Jackson to deserialise an array of objects

here is an utility which is up to transform json2object or Object2json, whatever your pojo (entity T)

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 
 * @author TIAGO.MEDICI
 * 
 */
public class JsonUtils {

    public static boolean isJSONValid(String jsonInString) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            mapper.readTree(jsonInString);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public static String serializeAsJsonString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objMapper = new ObjectMapper();
        objMapper.enable(SerializationFeature.INDENT_OUTPUT);
        objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        StringWriter sw = new StringWriter();
        objMapper.writeValue(sw, object);
        return sw.toString();
    }

    public static String serializeAsJsonString(Object object, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objMapper = new ObjectMapper();
        if (indent == true) {
            objMapper.enable(SerializationFeature.INDENT_OUTPUT);
            objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        }

        StringWriter stringWriter = new StringWriter();
        objMapper.writeValue(stringWriter, object);
        return stringWriter.toString();
    }

    public static <T> T jsonStringToObject(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper objMapper = new ObjectMapper();
        obj = objMapper.readValue(content, clazz);
        return obj;
    }

    @SuppressWarnings("rawtypes")
    public static <T> T jsonStringToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper mapper = new ObjectMapper();
        obj = mapper.readValue(content, new TypeReference<List>() {
        });
        return obj;
    }

    public static <T> T jsonStringToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper mapper = new ObjectMapper();
        mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
        return obj;
    }

How can you create pop up messages in a batch script?

With regard to LittleBobbyTable's answer - NET SEND does not work on Vista or Windows 7. It has been replaced by MSG.EXE

There is a crude solution that works on all versions of Windows - A crude popup message can be sent by STARTing a new cmd.exe window that closes once a key is pressed.

start "" cmd /c "echo Hello world!&echo(&pause"

If you want your script to pause until the message box is dismissed, then you can add the /WAIT option.

start "" /wait cmd /c "echo Hello world!&echo(&pause"

Regular expression - starting and ending with a character string

This should do it for you ^wp.*php$

Matches

wp-comments-post.php
wp.something.php
wp.php

Doesn't match

something-wp.php
wp.php.txt

How to create a label inside an <input> element?

Here is a simple example, all it does is overlay an image (with whatever wording you want). I saw this technique somewhere. I am using the prototype library so you would need to modify if using something else. With the image loading after window.load it fails gracefully if javascript is disabled.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1;" />
    <meta http-equiv="Expires" content="Fri, Jan 1 1981 08:00:00 GMT" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Cache-Control" content="no-cache" />
    <style type="text/css" >

        input.searcher
        {
            background-image: url(/images/search_back.png);
            background-repeat: no-repeat;
            background-attachment: scroll;
            background-x-position: left;
            background-y-position: center;
        }

    </style>

    <script type="text/javascript" src="/logist/include/scripts/js/prototype.js" ></script>
</head>
<body>
    <input type="text" id="q" name="q" value="" />

    <script type="text/javascript" language="JavaScript" >
    //  <![CDATA[
        function f(e){
            $('q').removeClassName('searcher');
        }

        function b(e){
            if ( $F('q') == '' )
            {
                $('q').addClassName('searcher');
            }
        }

        Event.observe( 'q', 'focus', f);
        Event.observe( 'q', 'blur', b);
        Event.observe( window, 'load', b);

    //  ]]>
    </script>
</body>
</html>

Redirecting to authentication dialog - "An error occurred. Please try again later"

Came here with a similar problem and, yes, my Sandbox was enabled. I disabled it and, voila, the login problem went away. I must warn that this problem does not affect developers and website administrators as Facebook allows those users to see the app. For this reason, I couldn't even believe that users complained about not being able to login, as I was able to login with no problems at all.

Python Progress Bar

With tqdm (conda install tqdm or pip install tqdm) you can add a progress meter to your loops in a second:

from time import sleep
from tqdm import tqdm
for i in tqdm(range(10)):
    sleep(3)

 60%|¦¦¦¦¦¦    | 6/10 [00:18<00:12,  0.33 it/s]

Also, there is a notebook version:

from tqdm.notebook import tqdm
for i in tqdm(range(100)):
    sleep(3)

You can use tqdm.auto instead of tqdm.notebook to work in both a terminal and notebooks.

tqdm.contrib contains some helper functions to do things like enumerate, map, and zip. There are concurrent maps in tqdm.contrib.concurrent.

You can even get progress sent to your phone after disconnecting from a jupyter notebook using tqdm.contrib.telegram or tqdm.contrib.discord.

C++ create string of text and variables

See also boost::format:

#include <boost/format.hpp>

std::string var = (boost::format("somtext %s sometext %s") % somevar % somevar).str();

Get first row of dataframe in Python Pandas based on criteria

This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:

>>> df[condition]

This will return a slice of your dataframe which you can index using iloc. Here are your examples:

  1. Get first row where A > 3 (returns row 2)

    >>> df[df.A > 3].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

If what you actually want is the row number, rather than using iloc, it would be df[df.A > 3].index[0].

  1. Get first row where A > 4 AND B > 3:

    >>> df[(df.A > 4) & (df.B > 3)].iloc[0]
    A    5
    B    4
    C    5
    Name: 4, dtype: int64
    
  2. Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)

    >>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:

>>> def series_or_default(X, condition, default_col, ascending=False):
...     sliced = X[condition]
...     if sliced.shape[0] == 0:
...         return X.sort_values(default_col, ascending=ascending).iloc[0]
...     return sliced.iloc[0]
>>> 
>>> series_or_default(df, df.A > 6, 'A')
A    5
B    4
C    5
Name: 4, dtype: int64

As expected, it returns row 4.

Apache: The requested URL / was not found on this server. Apache

Non-trivial reasons:

  • if your .htaccess is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert )
  • if your .htaccess is in UTF8 Without-BOM, make it WITH BOM.

Java string split with "." (dot)

I believe you should escape the dot. Try:

String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split("\\.")[0];

Otherwise dot is interpreted as any character in regular expressions.

Swift double to string

let double = 1.5 
let string = double.description

update Xcode 7.1 • Swift 2.1:

Now Double is also convertible to String so you can simply use it as you wish:

let double = 1.5
let doubleString = String(double)   // "1.5"

Swift 3 or later we can extend LosslessStringConvertible and make it generic

Xcode 11.3 • Swift 5.1 or later

extension LosslessStringConvertible { 
    var string: String { .init(self) } 
}

let double = 1.5 
let string = double.string  //  "1.5"

For a fixed number of fraction digits we can extend FloatingPoint protocol:

extension FloatingPoint where Self: CVarArg {
    func fixedFraction(digits: Int) -> String {
        .init(format: "%.*f", digits, self)
    }
}

If you need more control over your number format (minimum and maximum fraction digits and rounding mode) you can use NumberFormatter:

extension Formatter {
    static let number = NumberFormatter()
}

extension FloatingPoint {
    func fractionDigits(min: Int = 2, max: Int = 2, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
        Formatter.number.minimumFractionDigits = min
        Formatter.number.maximumFractionDigits = max
        Formatter.number.roundingMode = roundingMode
        Formatter.number.numberStyle = .decimal
        return Formatter.number.string(for: self) ?? ""
    }
}

2.12345.fractionDigits()                                    // "2.12"
2.12345.fractionDigits(min: 3, max: 3, roundingMode: .up)   // "2.124"

Basic http file downloading and saving to disk in python?

Exotic Windows Solution

import subprocess

subprocess.run("powershell Invoke-WebRequest {} -OutFile {}".format(your_url, filename), shell=True)

Using async/await with a forEach loop

In addition to @Bergi’s answer, I’d like to offer a third alternative. It's very similar to @Bergi’s 2nd example, but instead of awaiting each readFile individually, you create an array of promises, each which you await at the end.

import fs from 'fs-promise';
async function printFiles () {
  const files = await getFilePaths();

  const promises = files.map((file) => fs.readFile(file, 'utf8'))

  const contents = await Promise.all(promises)

  contents.forEach(console.log);
}

Note that the function passed to .map() does not need to be async, since fs.readFile returns a Promise object anyway. Therefore promises is an array of Promise objects, which can be sent to Promise.all().

In @Bergi’s answer, the console may log file contents in the order they’re read. For example if a really small file finishes reading before a really large file, it will be logged first, even if the small file comes after the large file in the files array. However, in my method above, you are guaranteed the console will log the files in the same order as the provided array.

How to create a Date in SQL Server given the Day, Month and Year as Integers

In SQL Server 2012+, you can use DATEFROMPARTS():

DECLARE @Year int = 2016, @Month int = 10, @Day int = 25;
SELECT DATEFROMPARTS (@Year, @Month, @Day);

In earlier versions, one method is to create and convert a string.

There are a few string date formats which SQL Server reliably interprets regardless of the date, language, or internationalization settings.

A six- or eight-digit string is always interpreted as ymd. The month and day must always be two digits.

https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql

So a string in the format 'yyyymmdd' will always be properly interpreted.

(ISO 8601-- YYYY-MM-DDThh:mm:ss-- also works, but you have to specify time and therefore it's more complicated than you need.)

While you can simply CAST this string as a date, you must use CONVERT in order to specify a style, and you must specify a style in order to be deterministic (if that matters to you).

The "yyyymmdd" format is style 112, so your conversion looks like this:

DECLARE @Year int = 2016, @Month int = 10, @Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),112);

And it results in:

2016-10-25

Technically, the ISO/112/yyyymmdd format works even with other styles specified. For example, using that text format with style 104 (German, dd.mm.yyyy):

DECLARE @Year int = 2016, @Month int = 10, @Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),104);

Also still results in:

2016-10-25

Other formats are not as robust. For example this:

SELECT CASE WHEN CONVERT(date,'01-02-1900',110) = CONVERT(date,'01-02-1900',105) THEN 1 ELSE 0 END;

Results in:

0

As a side note, with this method, beware that nonsense inputs can yield valid but incorrect dates:

DECLARE @Year int = 2016, @Month int = 0, @Day int = 1025;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),112);

Also yields:

2016-10-25

DATEFROMPARTS protects you from invalid inputs. This:

DECLARE @Year int = 2016, @Month int = 10, @Day int = 32;
SELECT DATEFROMPARTS (@Year, @Month, @Day);

Yields:

Msg 289, Level 16, State 1, Line 2 Cannot construct data type date, some of the arguments have values which are not valid.

Also beware that this method does not work for dates prior to 1000-01-01. For example:

DECLARE @Year int = 900, @Month int = 1, @Day int = 1;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),112);

Yields:

Msg 241, Level 16, State 1, Line 2 Conversion failed when converting date and/or time from character string.

That's because the resulting string, '9000101', is not in the 'yyyymmdd' format. To ensure proper formatting, you'd have to pad it with leading zeroes, at the sacrifice of some small amount of performance. For example:

DECLARE @Year int = 900, @Month int = 1, @Day int = 1;
SELECT CONVERT(date,RIGHT('000' + CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),8),112);

Results in:

0900-01-01

There are other methods aside from string conversion. Several are provided in answers to "Create a date with T-SQL". A notable example involves creating the date by adding years, months, and days to the "zero date".

(This answer was inspired by Gordon Linoff's answer, which I expanded on and provided additional documentation and notes.)

How to filter by string in JSONPath?

Drop the quotes:

List<Object> bugs = JsonPath.read(githubIssues, "$..labels[?(@.name==bug)]");

See also this Json Path Example page

GroupBy pandas DataFrame and select most common value

The problem here is the performance, if you have a lot of rows it will be a problem.

If it is your case, please try with this:

import pandas as pd

source = pd.DataFrame({'Country' : ['USA', 'USA', 'Russia','USA'], 
              'City' : ['New-York', 'New-York', 'Sankt-Petersburg', 'New-York'],
              'Short_name' : ['NY','New','Spb','NY']})

source.groupby(['Country','City']).agg(lambda x:x.value_counts().index[0])

source.groupby(['Country','City']).Short_name.value_counts().groupby['Country','City']).first()

Converting XDocument to XmlDocument and vice versa

There is a discussion on http://blogs.msdn.com/marcelolr/archive/2009/03/13/fast-way-to-convert-xmldocument-into-xdocument.aspx

It seems that reading an XDocument via an XmlNodeReader is the fastest method. See the blog for more details.

How to use the switch statement in R functions?

those various ways of switch ...

# by index
switch(1, "one", "two")
## [1] "one"


# by index with complex expressions
switch(2, {"one"}, {"two"})
## [1] "two"


# by index with complex named expression
switch(1, foo={"one"}, bar={"two"})
## [1] "one"


# by name with complex named expression
switch("bar", foo={"one"}, bar={"two"})
## [1] "two"

Delete column from pandas DataFrame

The dot syntax works in JavaScript, but not in Python.

  • Python: del df['column_name']
  • JavaScript: del df['column_name'] or del df.column_name

What is the use of rt.jar file in java?

rt.jar contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.

For MacOS it is called classes.jar and located under /System/Library/Frameworks/<java_version>/Classes . Same not messing with it rule applies there as well :).

http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html

Gradle proxy configuration

In case my I try to set up proxy from android studio Appearance & Behaviour => System Settings => HTTP Proxy. But the proxy did not worked out so I click no proxy.

Checking NO PROXY will not remove the proxy setting from the gradle.properties(Global). You need to manually remove it.

So I remove all the properties starting with systemProp for example - systemProp.http.nonProxyHosts=*.local, localhost

How to get the path of the batch script in Windows?

%~dp0 - return the path from where script executed

But, important to know also below one:

%CD% - return the current path in runtime, for example if you get into other folders using "cd folder1", and then "cd folder2", it will return the full path until folder2 and not the original path where script located

ESLint - "window" is not defined. How to allow global variables in package.json

I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:

Make sure ESLint is not run with the --no-inline-config flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):

/* eslint-env browser */

This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.

There are plenty of environments, and you can declare more than one at the same time, for example, in-line:

/* eslint-env browser, node */

If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.

From their docs:

An environment defines global variables that are predefined. The available environments are:

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node and Browser.

[...]

Besides environments, you can make it ignore anything you want. If it warns you about using console.log() but you don't want to be warned about it, just inline:

/* eslint-disable no-console */

You can see the list of all rules, including recommended rules to have for best coding practices.

How to draw a filled triangle in android canvas?

you can also use vertice :

private static final int verticesColors[] = {
    Color.LTGRAY, Color.LTGRAY, Color.LTGRAY, 0xFF000000, 0xFF000000, 0xFF000000
};
float verts[] = {
    point1.x, point1.y, point2.x, point2.y, point3.x, point3.y
};
canvas.drawVertices(Canvas.VertexMode.TRIANGLES, verts.length, verts, 0, null, 0, verticesColors,   0, null, 0, 0, new Paint());

Returning data from Axios API

    async handleResponse(){
      const result = await this.axiosTest();
    }

    async axiosTest () {
    return await axios.get(url)
    .then(function (response) {
            console.log(response.data);
            return response.data;})
.catch(function (error) {
    console.log(error);
});
}

You can find check https://flaviocopes.com/axios/#post-requests url and find some relevant information in the GET section of this post.

.NET: Simplest way to send POST with data and read response

   using (WebClient client = new WebClient())
   {

       byte[] response =
       client.UploadValues("http://dork.com/service", new NameValueCollection()
       {
           { "home", "Cosby" },
           { "favorite+flavor", "flies" }
       });

       string result = System.Text.Encoding.UTF8.GetString(response);
   }

You will need these includes:

using System;
using System.Collections.Specialized;
using System.Net;

If you're insistent on using a static method/class:

public static class Http
{
    public static byte[] Post(string uri, NameValueCollection pairs)
    {
        byte[] response = null;
        using (WebClient client = new WebClient())
        {
            response = client.UploadValues(uri, pairs);
        }
        return response;
    }
}

Then simply:

var response = Http.Post("http://dork.com/service", new NameValueCollection() {
    { "home", "Cosby" },
    { "favorite+flavor", "flies" }
});

Escaping ampersand in URL

I would like to add a minor comment on Blender solution.

You can do the following:

var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M');

That outputs:

http://example.com?candy_name=M%26M

The great thing about this it does not only work for & but for any especial character.

For instance:

var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M?><')

Outputs:

"http://example.com?candy_name=M%26M%3F%3E%3C"

How to get the groups of a user in Active Directory? (c#, asp.net)

The answer depends on what kind of groups you want to retrieve. The System.DirectoryServices.AccountManagement namespace provides two group retrieval methods:

GetGroups - Returns a collection of group objects that specify the groups of which the current principal is a member.

This overloaded method only returns the groups of which the principal is directly a member; no recursive searches are performed.

GetAuthorizationGroups - Returns a collection of principal objects that contains all the authorization groups of which this user is a member. This function only returns groups that are security groups; distribution groups are not returned.

This method searches all groups recursively and returns the groups in which the user is a member. The returned set may also include additional groups that system would consider the user a member of for authorization purposes.

So GetGroups gets all groups of which the user is a direct member, and GetAuthorizationGroups gets all authorization groups of which the user is a direct or indirect member.

Despite the way they are named, one is not a subset of the other. There may be groups returned by GetGroups not returned by GetAuthorizationGroups, and vice versa.

Here's a usage example:

PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "MyDomain", "OU=AllUsers,DC=MyDomain,DC=Local");
UserPrincipal inputUser = new UserPrincipal(domainContext);
inputUser.SamAccountName = "bsmith";
PrincipalSearcher adSearcher = new PrincipalSearcher(inputUser);
inputUser = (UserPrincipal)adSearcher.FindAll().ElementAt(0);
var userGroups = inputUser.GetGroups();

How to call any method asynchronously in c#

If you use action.BeginInvoke(), you have to call EndInvoke somewhere - else the framework has to hold the result of the async call on the heap, resulting in a memory leak.

If you don't want to jump to C# 5 with the async/await keywords, you can just use the Task Parallels library in .Net 4. It's much, much nicer than using BeginInvoke/EndInvoke, and gives a clean way to fire-and-forget for async jobs:

using System.Threading.Tasks;
...
void Foo(){}
...
new Task(Foo).Start();

If you have methods to call that take parameters, you can use a lambda to simplify the call without having to create delegates:

void Foo2(int x, string y)
{
    return;
}
...
new Task(() => { Foo2(42, "life, the universe, and everything");}).Start();

I'm pretty sure (but admittedly not positive) that the C# 5 async/await syntax is just syntactic sugar around the Task library.

How to store arbitrary data for some HTML tags

At my previous employer, we used custom HTML tags all the time to hold info about the form elements. The catch: We knew that the user was forced to use IE.

It didn't work well for FireFox at the time. I don't know if FireFox has changed this or not, but be aware that adding your own attributes to HTML elements may or may-not be supported by your reader's browser.

If you can control which browser your reader is using (i.e. an internal web applet for a corporation), then by all means, try it. What can it hurt, right?

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

Note that if the problem is being caused by appearing scrollbars, putting

body {
  overflow: hidden;
}

in your CSS might be an easy fix (if you don't need the page to scroll).

Eclipse plugin for generating a class diagram

Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.

php: how to get associative array key from numeric index?

You don't. Your array doesn't have a key [1]. You could:

  • Make a new array, which contains the keys:

    $newArray = array_keys($array);
    echo $newArray[0];
    

    But the value "one" is at $newArray[0], not [1].
    A shortcut would be:

    echo current(array_keys($array));
    
  • Get the first key of the array:

     reset($array);
     echo key($array);
    
  • Get the key corresponding to the value "value":

    echo array_search('value', $array);
    

This all depends on what it is exactly you want to do. The fact is, [1] doesn't correspond to "one" any which way you turn it.

key_load_public: invalid format

@uvsmtid Your post finally lead me into the right direction: simply deleting (actually renaming) the public key file id_rsa.pub solved the problem for me, that git was working though nagging about invalid format. Not quite sure, yet the file is not actually needed, since the pub key can be extracted from private key file id_rsa anyway.

Where does MAMP keep its php.ini?

I was struggling with this too. My changes weren't being reflected in phpInfo. It wasn't until I stopped my servers and then restarted them again that my changes actually took effect.

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

How do I install a NuGet package .nupkg file locally?

If you have a .nupkg file and just need the .dll file all you have to do is change the extension to .zip and find the lib directory.

"Unable to find remote helper for 'https'" during git clone

CentOS Minimal usually install version 1.8 git by yum install gitcommand.

The best way is to build & install it from source code. Current version is 2.18.0.

  1. Download the source code from https://mirrors.edge.kernel.org/pub/software/scm/git/ or curl -o git-2.18.0.tar.gz https://mirrors.edge.kernel.org/pub/software/scm/git/git-2.18.0.tar.gz

  2. Unzip by tar -zxf git-2.18.0.tar.gz && cd git-2.18.0

  3. Install the dependency package by executing yum install autoconf curl-devel expat-devel gettext-devel openssl-devel perl-devel zlib-devel asciidoc xmlto openjade perl* texinfo

  4. Install docbook2X, it's not in the rpm repository. Download and install by

    $ curl -o docbook2X-0.8.8-17.el7.x86_64.rpm http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/d/docbook2X-0.8.8-17.el7.x86_64.rpm $ rpm -Uvh docbook2X-0.8.8-17.el7.x86_64.rpm

And make a unix link name:

ln -s /usr/bin/db2x_docbook2texi /usr/bin/docbook2x-texi
  1. Compile and install, reference to https://git-scm.com/book/en/v2/Getting-Started-Installing-Git

    $ make configure $ ./configure --prefix=/usr $ make all doc info $ sudo make install install-doc install-html install-info

  2. Reboot your server (If not, you may encounter Unable to find remote helper for 'https' error)

    $ reboot now

  3. Test:

    $ git clone https://github.com/volnet/v-labs.git $ cd v-labs $ touch test.txt $ git add . $ git commit -m "test git install" $ git push -u

Adding items in a Listbox with multiple columns

select propety

Row Source Type => Value List

Code :

ListbName.ColumnCount=2

ListbName.AddItem "value column1;value column2"

Android Preventing Double Click On A Button

for any one using data-binding :

@BindingAdapter("onClickWithDebounce")
fun onClickWithDebounce(view: View, listener: android.view.View.OnClickListener) {
    view.setClickWithDebounce {
        listener.onClick(view)
    }
}

object LastClickTimeSingleton {
    var lastClickTime: Long = 0
}

fun View.setClickWithDebounce(action: () -> Unit) {
    setOnClickListener(object : View.OnClickListener {

        override fun onClick(v: View) {
            if (SystemClock.elapsedRealtime() - LastClickTimeSingleton.lastClickTime < 500L) return
            else action()
            LastClickTimeSingleton.lastClickTime = SystemClock.elapsedRealtime()
        }
    })
}



<androidx.appcompat.widget.AppCompatButton
                    ..
  android:text="@string/signup_signin"
  app:onClickWithDebounce="@{() -> viewModel.onSignUpClicked()}"
                   ... />

Different ways of loading a file as an InputStream

Plain old Java on plain old Java 7 and no other dependencies demonstrates the difference...

I put file.txt in c:\temp\ and I put c:\temp\ on the classpath.

There is only one case where there is a difference between the two call.

class J {

 public static void main(String[] a) {
    // as "absolute"

    // ok   
    System.err.println(J.class.getResourceAsStream("/file.txt") != null); 

    // pop            
    System.err.println(J.class.getClassLoader().getResourceAsStream("/file.txt") != null); 

    // as relative

    // ok
    System.err.println(J.class.getResourceAsStream("./file.txt") != null); 

    // ok
    System.err.println(J.class.getClassLoader().getResourceAsStream("./file.txt") != null); 

    // no path

    // ok
    System.err.println(J.class.getResourceAsStream("file.txt") != null); 

   // ok
   System.err.println(J.class.getClassLoader().getResourceAsStream("file.txt") != null); 
  }
}

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).

How can I find the OWNER of an object in Oracle?

I found this question as the top result while Googling how to find the owner of a table in Oracle, so I thought that I would contribute a table specific answer for others' convenience.

To find the owner of a specific table in an Oracle DB, use the following query:

select owner from ALL_TABLES where TABLE_NAME ='<MY-TABLE-NAME>';

How can I programmatically generate keypress events in C#?

Easily! (because someone else already did the work for us...)

After spending a lot of time trying to this with the suggested answers I came across this codeplex project Windows Input Simulator which made it simple as can be to simulate a key press:

  1. Install the package, can be done or from the NuGet package manager or from the package manager console like:

    Install-Package InputSimulator

  2. Use this 2 lines of code:

    inputSimulator = new InputSimulator() inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)

And that's it!

-------EDIT--------

The project page on codeplex is flagged for some reason, this is the link to the NuGet gallery.

How to bind an enum to a combobox control in WPF?

I just kept it simple. I created a list of items with the enum values in my ViewModel:

public enum InputsOutputsBoth
{
    Inputs,
    Outputs,
    Both
}

private IList<InputsOutputsBoth> _ioTypes = new List<InputsOutputsBoth>() 
{ 
    InputsOutputsBoth.Both, 
    InputsOutputsBoth.Inputs, 
    InputsOutputsBoth.Outputs 
};

public IEnumerable<InputsOutputsBoth> IoTypes
{
    get { return _ioTypes; }
    set { }
}

private InputsOutputsBoth _selectedIoType;

public InputsOutputsBoth SelectedIoType
{
    get { return _selectedIoType; }
    set
    {
        _selectedIoType = value;
        OnPropertyChanged("SelectedIoType");
        OnSelectionChanged();
    }
}

In my xaml code I just need this:

<ComboBox ItemsSource="{Binding IoTypes}" SelectedItem="{Binding SelectedIoType, Mode=TwoWay}">

Removing items from a list

You can't and shouldn't modify a list while iterating over it. You can solve this by temporarely saving the objects to remove:

List<Object> toRemove = new ArrayList<Object>();
for(Object a: list){
    if(a.getXXX().equalsIgnoreCase("AAA")){
        toRemove.add(a);
    }
}
list.removeAll(toRemove);

How to undo a successful "git cherry-pick"?

A cherry-pick is basically a commit, so if you want to undo it, you just undo the commit.

when I have other local changes

Stash your current changes so you can reapply them after resetting the commit.

$ git stash
$ git reset --hard HEAD^
$ git stash pop  # or `git stash apply`, if you want to keep the changeset in the stash

when I have no other local changes

$ git reset --hard HEAD^

How can I find matching values in two arrays?

I found a slight alteration on what @jota3 suggested worked perfectly for me.

var intersections = array1.filter(e => array2.indexOf(e) !== -1);

Hope this helps!

How can I verify a Google authentication API access token?

I need to somehow query Google and ask: Is this access token valid for [email protected]?

No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.

The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.

So you need be from same domain as 'public interface'.

And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.

How to abort makefile if variable not set?

TL;DR: Use the error function:

ifndef MY_FLAG
$(error MY_FLAG is not set)
endif

Note that the lines must not be indented. More precisely, no tabs must precede these lines.


Generic solution

In case you're going to test many variables, it's worth defining an auxiliary function for that:

# Check that given variables are set and all have non-empty values,
# die with an error otherwise.
#
# Params:
#   1. Variable name(s) to test.
#   2. (optional) Error message to print.
check_defined = \
    $(strip $(foreach 1,$1, \
        $(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
    $(if $(value $1),, \
      $(error Undefined $1$(if $2, ($2))))

And here is how to use it:

$(call check_defined, MY_FLAG)

$(call check_defined, OUT_DIR, build directory)
$(call check_defined, BIN_DIR, where to put binary artifacts)
$(call check_defined, \
            LIB_INCLUDE_DIR \
            LIB_SOURCE_DIR, \
        library path)


This would output an error like this:

Makefile:17: *** Undefined OUT_DIR (build directory).  Stop.

Notes:

The real check is done here:

$(if $(value $1),,$(error ...))

This reflects the behavior of the ifndef conditional, so that a variable defined to an empty value is also considered "undefined". But this is only true for simple variables and explicitly empty recursive variables:

# ifndef and check_defined consider these UNDEFINED:
explicitly_empty =
simple_empty := $(explicitly_empty)

# ifndef and check_defined consider it OK (defined):
recursive_empty = $(explicitly_empty)

As suggested by @VictorSergienko in the comments, a slightly different behavior may be desired:

$(if $(value $1) tests if the value is non-empty. It's sometimes OK if the variable is defined with an empty value. I'd use $(if $(filter undefined,$(origin $1)) ...

And:

Moreover, if it's a directory and it must exist when the check is run, I'd use $(if $(wildcard $1)). But would be another function.

Target-specific check

It is also possible to extend the solution so that one can require a variable only if a certain target is invoked.

$(call check_defined, ...) from inside the recipe

Just move the check into the recipe:

foo :
    @:$(call check_defined, BAR, baz value)

The leading @ sign turns off command echoing and : is the actual command, a shell no-op stub.

Showing target name

The check_defined function can be improved to also output the target name (provided through the $@ variable):

check_defined = \
    $(strip $(foreach 1,$1, \
        $(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
    $(if $(value $1),, \
        $(error Undefined $1$(if $2, ($2))$(if $(value @), \
                required by target `$@')))

So that, now a failed check produces a nicely formatted output:

Makefile:7: *** Undefined BAR (baz value) required by target `foo'.  Stop.

check-defined-MY_FLAG special target

Personally I would use the simple and straightforward solution above. However, for example, this answer suggests using a special target to perform the actual check. One could try to generalize that and define the target as an implicit pattern rule:

# Check that a variable specified through the stem is defined and has
# a non-empty value, die with an error otherwise.
#
#   %: The name of the variable to test.
#   
check-defined-% : __check_defined_FORCE
    @:$(call check_defined, $*, target-specific)

# Since pattern rules can't be listed as prerequisites of .PHONY,
# we use the old-school and hackish FORCE workaround.
# You could go without this, but otherwise a check can be missed
# in case a file named like `check-defined-...` exists in the root 
# directory, e.g. left by an accidental `make -t` invocation.
.PHONY : __check_defined_FORCE
__check_defined_FORCE :

Usage:

foo :|check-defined-BAR

Notice that the check-defined-BAR is listed as the order-only (|...) prerequisite.

Pros:

  • (arguably) a more clean syntax

Cons:

I believe, these limitations can be overcome using some eval magic and secondary expansion hacks, although I'm not sure it's worth it.

Running SSH Agent when starting Git Bash on Windows

Create a new .bashrc file in your ~ directory.

There you can put your commands that you want executed everytime you start the bash

Left Outer Join using + sign in Oracle 11g

I saw some contradictions in the answers above, I just tried the following on Oracle 12c and the following is correct :

LEFT OUTER JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT *
FROM A, B
WHERE B.column(+) = A.column

Bootstrap 3 with remote Modal

As much as I dislike modifying Bootstrap code (makes upgrading more difficult), you can simply add ".find('.modal-body') to the load statement in modal.js as follows:

// original code
// if (this.options.remote) this.$element.load(this.options.remote)

// modified code
if (this.options.remote) this.$element.find('.modal-body').load(this.options.remote)

Auto refresh page every 30 seconds

If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.

javascript:

<script language="javascript">
setTimeout(function(){
   window.location.reload(1);
}, 30000);
</script>

Split varchar into separate columns in Oracle

With REGEXP_SUBSTR is as simple as:

SELECT REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 1) col_one,
       REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 2) col_two
FROM YOUR_TABLE t;

How to play video with AVPlayerViewController (AVKit) in Swift

Swift 3.x - 5.x

Necessary: import AVKit, import AVFoundation

AVFoundation framework is needed even if you use AVPlayer

If you want to use AVPlayerViewController:

let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
    playerViewController.player!.play()
}

or just AVPlayer:

let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL!)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()

It's better to put this code into the method: override func viewDidAppear(_ animated: Bool) or somewhere after.


Objective-C

AVPlayerViewController:

NSURL *videoURL = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
playerViewController.player = player;
[self presentViewController:playerViewController animated:YES completion:^{
  [playerViewController.player play];
}];

or just AVPlayer:

NSURL *videoURL = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
playerLayer.frame = self.view.bounds;
[self.view.layer addSublayer:playerLayer];
[player play];

What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

What about

int highest_bit(unsigned int a) {
    int count;
    std::frexp(a, &count);
    return count - 1;
}

?

"ImportError: No module named" when trying to run Python script

The main reason is the sys.paths of Python and IPython are different.

Please refer to lucypark link, the solution works in my case. It happen when install opencv by

conda install opencv

And got import error in iPython, There are three steps to solve this issue:

import cv2
ImportError: ...

1. Check path in Python and iPython with following command

import sys
sys.path

You will find different result from Python and Jupyter. Second step, just use sys.path.append to fix the missed path by try-and-error.

2. Temporary solution

In iPython:

import sys
sys.path.append('/home/osboxes/miniconda2/lib/python2.7/site-packages')
import cv2

the ImportError:.. issue solved

3. Permanent solution

Create an iPython profile and set initial append:

In bash shell:

ipython profile create
... CHECK the path prompted , and edit the prompted config file like my case
vi /home/osboxes/.ipython/profile_default/ipython_kernel_config.py

In vi, append to the file:

c.InteractiveShellApp.exec_lines = [
 'import sys; sys.path.append("/home/osboxes/miniconda2/lib/python2.7/site-packages")'
]

DONE

Changing CSS for last <li>

$('li').last().addClass('someClass');

if you have multiple

  • group it will only select the last li.

  • Store boolean value in SQLite

    Another way to do it is a TEXT column. And then convert the boolean value between Boolean and String before/after saving/reading the value from the database.

    Ex. You have "boolValue = true;"

    To String:

    //convert to the string "TRUE"
    string StringValue = boolValue.ToString;  
    

    And back to boolean:

    //convert the string back to boolean
    bool Boolvalue = Convert.ToBoolean(StringValue);
    

    How to disable/enable a button with a checkbox if checked

    You can use onchangeevent of the checkbox to enable/disable button based on checked value

    <input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
    
    <input type="checkbox"  onchange="document.getElementById('sendNewSms').disabled = !this.checked;" />
    

    How do I convert between ISO-8859-1 and UTF-8 in Java?

    Apache Commons IO Charsets class can come in handy:

    String utf8String = new String(org.apache.commons.io.Charsets.ISO_8859_1.encode(latinString).array())
    

    Python timedelta in years

    import datetime
    
    def check_if_old_enough(years_needed, old_date):
    
        limit_date = datetime.date(old_date.year + years_needed,  old_date.month, old_date.day)
    
        today = datetime.datetime.now().date()
    
        old_enough = False
    
        if limit_date <= today:
            old_enough = True
    
        return old_enough
    
    
    
    def test_ages():
    
        years_needed = 30
    
        born_date_Logan = datetime.datetime(1988, 3, 5)
    
        if check_if_old_enough(years_needed, born_date_Logan):
            print("Logan is old enough")
        else:
            print("Logan is not old enough")
    
    
        born_date_Jessica = datetime.datetime(1997, 3, 6)
    
        if check_if_old_enough(years_needed, born_date_Jessica):
            print("Jessica is old enough")
        else:
            print("Jessica is not old enough")
    
    
    test_ages()
    

    This is the code that the Carrousel operator was running in Logan's Run film ;)

    https://en.wikipedia.org/wiki/Logan%27s_Run_(film)

    Can't choose class as main class in IntelliJ

    Here is the complete procedure for IDEA IntelliJ 2019.3:

    1. File > Project Structure

    2. Under Project Settings > Modules

    3. Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.

    4. Apply changes.

    How to make an ImageView with rounded corners?

    If any of you are facing this problem

    enter image description here

    Most probably , you are using Android Studio. Due to image re-size and all in Android Studio ,you may encounter this problem. An easy fix to this problem is to decrease the radius of circle in drawCircle(). In my case i use this fix

    Using canvas.drawCircle(100, 100, 90, paint); instead of canvas.drawCircle(100, 100, 100, paint); this will definitely solve your problem.

    Here is finally edited code:-

      public class Profile extends ActionBarActivity {
    
    
        TextView username;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.profile);
    
    
            username= (TextView) findViewById(R.id.txt);
    
            String recievedusername=getIntent().getExtras().getString("toname");
            username.setText(recievedusername);
    
    
            Bitmap bm = BitmapFactory.decodeResource(getResources(),
                    R.mipmap.gomez);
    
            Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm, 200,200, false);
            Bitmap conv_bm=getCircleBitmap(resizedBitmap,100);
            // set circle bitmap
            ImageView mImage = (ImageView) findViewById(R.id.profile_image);
            mImage.setImageBitmap(conv_bm);
            // TODO Auto-generated method stub
        }
        private Bitmap getCircleBitmap(Bitmap bitmap , int pixels) {
            final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            final Canvas canvas = new Canvas(output);
            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),bitmap.getHeight());
            final RectF rectF = new RectF(rect);
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawCircle(100,100, 90, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
            bitmap.recycle();
            return output;
        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu_apploud, menu);
            return super.onCreateOptionsMenu(menu);
        }
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_addnew) {
                Intent i;
                i=new Intent(Profile.this,ApplaudSomeone.class);
                startActivity(i);
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
    

    powershell 2.0 try catch how to access the exception

    Try something like this:

    try {
        $w = New-Object net.WebClient
        $d = $w.downloadString('http://foo')
    }
    catch [Net.WebException] {
        Write-Host $_.Exception.ToString()
    }
    

    The exception is in the $_ variable. You might explore $_ like this:

    try {
        $w = New-Object net.WebClient
        $d = $w.downloadString('http://foo')
    }
    catch [Net.WebException] {
        $_ | fl * -Force
    }
    

    I think it will give you all the info you need.

    My rule: if there is some data that is not displayed, try to use -force.

    Difference between Parameters.Add(string, object) and Parameters.AddWithValue

    The difference is the implicit conversion when using AddWithValue. If you know that your executing SQL query (stored procedure) is accepting a value of type int, nvarchar, etc, there's no reason in re-declaring it in your code.

    For complex type scenarios (example would be DateTime, float), I'll probably use Add since it's more explicit but AddWithValue for more straight-forward type scenarios (Int to Int).

    How to set the default value of an attribute on a Laravel model

    You should set default values in migrations:

    $table->tinyInteger('role')->default(1);
    

    Addition for BigDecimal

    BigDecimal demo = new BigDecimal(15);
    

    It is immutable beacuse it internally store you input i.e (15) as final private final BigInteger intVal; and same concept use at the time of string creation every input finally store in private final char value[];.So there is no implmented bug.

    javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

    My problem was with TIMEZONE in emulator genymotion. Change TIMEZONE ANDROID EMULATOR equal TIMEZONE SERVER, solved problem.

    reference

    How can I declare a Boolean parameter in SQL statement?

    SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

    declare @var bit
    set @var = 'true'
    print @var
    

    That returns 1.

    How to force table cell <td> content to wrap?

    Use table-layout:fixed in the table and word-wrap:break-word in the td.

    See this example:

    <html>
    <head>
       <style>
       table {border-collapse:collapse; table-layout:fixed; width:310px;}
       table td {border:solid 1px #fab; width:100px; word-wrap:break-word;}
       </style>
    </head>
    
    <body>
       <table>
          <tr>
             <td>1</td>
             <td>Lorem Ipsum</td>
             <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>
          </tr>
          <tr>
             <td>2</td>
             <td>LoremIpsumhasbeentheindustry'sstandarddummytexteversincethe1500s,whenanunknown</td>
             <td>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>
          </tr>
          <tr>
             <td>3</td>
             <td></td>
             <td>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna...</td>
          </tr>
       </table>
    </body>
    </html>
    

    DEMO:

    _x000D_
    _x000D_
    table {border-collapse:collapse; table-layout:fixed; width:310px;}_x000D_
           table td {border:solid 1px #fab; width:100px; word-wrap:break-word;}
    _x000D_
           <table>_x000D_
              <tr>_x000D_
                 <td>1</td>_x000D_
                 <td>Lorem Ipsum</td>_x000D_
                 <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                 <td>2</td>_x000D_
                 <td>LoremIpsumhasbeentheindustry'sstandarddummytexteversincethe1500s,whenanunknown</td>_x000D_
                 <td>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                 <td>3</td>_x000D_
                 <td></td>_x000D_
                 <td>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna...</td>_x000D_
              </tr>_x000D_
           </table>_x000D_
        
    _x000D_
    _x000D_
    _x000D_

    How to parse a JSON string into JsonNode in Jackson?

    A slight variation on Richards answer but readTree can take a string so you can simplify it to:

    ObjectMapper mapper = new ObjectMapper();
    JsonNode actualObj = mapper.readTree("{\"k1\":\"v1\"}");
    

    How to kill a while loop with a keystroke?

    pip install keyboard
    
    import keyboard
    
    while True:
        # do something
        if keyboard.is_pressed("q"):
            print("q pressed, ending loop")
            break
    

    How to use struct timeval to get the execution time?

    Change:

    struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                              delcare a variable with
                                              no name. */
    

    to:

    struct timeval tvalBefore, tvalAfter;
    

    It is less likely (IMO) to make this mistake if there is a single declaration per line:

    struct timeval tvalBefore;
    struct timeval tvalAfter;
    

    It becomes more error prone when declaring pointers to types on a single line:

    struct timeval* tvalBefore, tvalAfter;
    

    tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

    C - reading command line parameters

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char **argv) {
      int i, parameter = 0;
      if (argc >= 2) {
        /* there is 1 parameter (or more) in the command line used */
        /* argv[0] may point to the program name */
        /* argv[1] points to the 1st parameter */
        /* argv[argc] is NULL */
        parameter = atoi(argv[1]); /* better to use strtol */
        if (parameter > 0) {
          for (i = 0; i < parameter; i++) printf("%d ", i);
        } else {
          fprintf(stderr, "Please use a positive integer.\n");
        }
      }
      return 0;
    }
    

    echo that outputs to stderr

    Make a script

    #!/bin/sh
    echo $* 1>&2
    

    that would be your tool.

    Or make a function if you don't want to have a script in separate file.

    Hibernate: "Field 'id' doesn't have a default value"

    i have got such error in GCP cloud sql when model field didn't match correct table field in db. Example: when in model field is fieldName
    table in db should have field field_name Fixing table field name helped me.

    Find and replace string values in list

    You can use, for example:

    words = [word.replace('[br]','<br />') for word in words]
    

    Run parallel multiple commands at once in the same terminal

    Use GNU Parallel:

    (echo command1; echo command2) | parallel
    parallel ::: command1 command2
    

    To kill:

    parallel ::: command1 command2 &
    PID=$!
    kill -TERM $PID
    kill -TERM $PID
    

    Can I set subject/content of email using mailto:?

    Here's a runnable snippet to help you generate mailto: links with optional subject and body.

    _x000D_
    _x000D_
    function generate() {_x000D_
      var email = $('#email').val();_x000D_
      var subject = $('#subject').val();_x000D_
      var body = $('#body').val();_x000D_
    _x000D_
      var mailto = 'mailto:' + email;_x000D_
      var params = {};_x000D_
      if (subject) {_x000D_
        params.subject = subject;_x000D_
      }_x000D_
      if (body) {_x000D_
        params.body = body;_x000D_
      }_x000D_
      if (params) {_x000D_
        mailto += '?' + $.param(params);_x000D_
      }_x000D_
    _x000D_
      var $output = $('#output');_x000D_
      $output.val(mailto);_x000D_
      $output.focus();_x000D_
      $output.select();_x000D_
      document.execCommand('copy');_x000D_
    }_x000D_
    _x000D_
    $(document).ready(function() {_x000D_
      $('#generate').on('click', generate);_x000D_
    });
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <input type="text" id="email" placeholder="email address" /><br/>_x000D_
    <input type="text" id="subject" placeholder="Subject" /><br/>_x000D_
    <textarea id="body" placeholder="Body"></textarea><br/>_x000D_
    <button type="button" id="generate">Generate & copy to clipboard</button><br/>_x000D_
    <textarea id="output">Output</textarea>
    _x000D_
    _x000D_
    _x000D_

    Adjust UILabel height to text

    Swift 4.0

    Instead of calculating the text/label height, I just resize the label after inserting the (dynamic) text.

    Assuming that myLabel is the UILabel in question:

    let myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: *somewidth*, height: *placeholder, e.g. 20*))
    myLabel.numberOfLines = 0
    myLabel.lineBreakMode = .byWordWrapping
    ...
    

    And now comes the fun part:

    var myLabelText: String = "" {
       didSet {
          myLabel.text = myLabelText
          myLabel.sizeToFit()
       }
    }
    

    How does strcmp() work?

    Here is the BSD implementation:

    int
    strcmp(s1, s2)
        register const char *s1, *s2;
    {
        while (*s1 == *s2++)
            if (*s1++ == 0)
                return (0);
        return (*(const unsigned char *)s1 - *(const unsigned char *)(s2 - 1));
    }
    

    Once there is a mismatch between two characters, it just returns the difference between those two characters.

    Why can't I inherit static classes?

    You can do something that will look like static inheritance.

    Here is the trick:

    public abstract class StaticBase<TSuccessor>
        where TSuccessor : StaticBase<TSuccessor>, new()
    {
        protected static readonly TSuccessor Instance = new TSuccessor();
    }
    

    Then you can do this:

    public class Base : StaticBase<Base>
    {
        public Base()
        {
        }
    
        public void MethodA()
        {
        }
    }
    
    public class Inherited : Base
    {
        private Inherited()
        {
        }
    
        public new static void MethodA()
        {
            Instance.MethodA();
        }
    }
    

    The Inherited class is not static itself, but we don't allow to create it. It actually has inherited static constructor which builds Base, and all properties and methods of Base available as static. Now the only thing left to do make static wrappers for each method and property you need to expose to your static context.

    There are downsides like the need for manual creation of static wrapper methods and new keyword. But this approach helps support something that is really similar to static inheritance.

    P.S. We used this for creating compiled queries, and this actually can be replaced with ConcurrentDictionary, but a static read-only field with its thread safety was good enough.

    How do I change the font size and color in an Excel Drop Down List?

    I created a custom view that is at 100%. Use the dropdowns then click to view page layout to go back to a smaller view.

    How to create a inner border for a box in html?

    IE doesn't support outline-offset so another solution would be to create 2 div tags, one nested into the other one. The inner one would have a border and be slightly smaller than the container.

    _x000D_
    _x000D_
    .container {_x000D_
      position: relative;_x000D_
      overflow: hidden;_x000D_
      width: 400px;_x000D_
      height: 100px;_x000D_
      background: #000000;_x000D_
      padding: 10px;_x000D_
    }_x000D_
    .inner {_x000D_
      position: relative;_x000D_
      overflow: hidden;_x000D_
      width: 100%;_x000D_
      height: 100%;_x000D_
      background: #000000;_x000D_
      border: 1px dashed #ffffff;_x000D_
    }
    _x000D_
    <div class="container">_x000D_
      <div class="inner"></div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    What is the difference between include and require in Ruby?

    require(name)
    

    It will return bolean true/false

    The name which is passed as parameter to the require, ruby will try to find the source file with that name in your load path. The require method will return ‘false’ if you try to load the same library after the first time. The require method only needs to be used if library you are loading is defined in a separate file. So it keeps track of whether that library was already loaded or not.

    include module_name
    

    Suppose if you have some methods that you need to have in two different classes. Then you don't have to write them in both the classes. Instead what you can do is, define it in module. And then include this module in other classes. It is provided by Ruby just to ensure DRY principle. It’s used to DRY up your code to avoid duplication

    File path issues in R using Windows ("Hex digits in character string" error)

    replace all the \ with \\.

    it's trying to escape the next character in this case the U so to insert a \ you need to insert an escaped \ which is \\

    How to cast List<Object> to List<MyClass>

    As others have pointed out, you cannot savely cast them, since a List<Object> isn't a List<Customer>. What you could do, is to define a view on the list that does in-place type checking. Using Google Collections that would be:

    return Lists.transform(list, new Function<Object, Customer>() {
      public Customer apply(Object from) {
        if (from instanceof Customer) {
          return (Customer)from;
        }
        return null; // or throw an exception, or do something else that makes sense.
      }
    });
    

    How to Call a Function inside a Render in React/Jsx

    _x000D_
    _x000D_
    class App extends React.Component {_x000D_
      _x000D_
      buttonClick(){_x000D_
        console.log("came here")_x000D_
        _x000D_
      }_x000D_
      _x000D_
      subComponent() {_x000D_
        return (<div>Hello World</div>);_x000D_
      }_x000D_
      _x000D_
      render() {_x000D_
        return ( _x000D_
          <div className="patient-container">_x000D_
              <button onClick={this.buttonClick.bind(this)}>Click me</button>_x000D_
              {this.subComponent()}_x000D_
           </div>_x000D_
         )_x000D_
      }_x000D_
      _x000D_
    _x000D_
    _x000D_
    }_x000D_
    _x000D_
    ReactDOM.render(<App/>, document.getElementById('app'));
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
    <div id="app"></div>
    _x000D_
    _x000D_
    _x000D_

    it depends on your need, u can use either this.renderIcon() or bind this.renderIcon.bind(this)

    UPDATE

    This is how you call a method outside the render.

    buttonClick(){
        console.log("came here")
    }
    
    render() {
       return (
           <div className="patient-container">
              <button onClick={this.buttonClick.bind(this)}>Click me</button>
           </div>
       );
    }
    

    The recommended way is to write a separate component and import it.

    Retrieve CPU usage and memory usage of a single process on Linux?

    Based on @Neon answer, my two cents here:

    pidstat -h -r -u -v -p $(ps aux | grep <process name> | awk '{print $2}' | tr '\n' ',')
    

    SOAP vs REST (differences)

    REST(REpresentational State Transfer)
    REpresentational State of an Object is Transferred is REST i.e. we don't send Object, we send state of Object. REST is an architectural style. It doesn’t define so many standards like SOAP. REST is for exposing Public APIs(i.e. Facebook API, Google Maps API) over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

    SOAP(Simple Object Access Protocol)
    SOAP brings its own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each operation implement some business logic. Though SOAP is commonly referred to as web services this is misnomer. SOAP has a very little if anything to do with the Web. REST provides true Web services based on URIs and HTTP.

    Why REST?

    • Since REST uses standard HTTP it is much simpler in just about ever way.
    • REST is easier to implement, requires less bandwidth and resources.
    • REST permits many different data formats where as SOAP only permits XML.
    • REST allows better support for browser clients due to its support for JSON.
    • REST has better performance and scalability. REST reads can be cached, SOAP based reads cannot be cached.
    • If security is not a major concern and we have limited resources. Or we want to create an API that will be easily used by other developers publicly then we should go with REST.
    • If we need Stateless CRUD operations then go with REST.
    • REST is commonly used in social media, web chat, mobile services and Public APIs like Google Maps.
    • RESTful service return various MediaTypes for the same resource, depending on the request header parameter "Accept" as application/xml or application/json for POST and /user/1234.json or GET /user/1234.xml for GET.
    • REST services are meant to be called by the client-side application and not the end user directly.
    • ST in REST comes from State Transfer. You transfer the state around instead of having the server store it, this makes REST services scalable.

    Why SOAP?

    • SOAP is not very easy to implement and requires more bandwidth and resources.
    • SOAP message request is processed slower as compared to REST and it does not use web caching mechanism.
    • WS-Security: While SOAP supports SSL (just like REST) it also supports WS-Security which adds some enterprise security features.
    • WS-AtomicTransaction: Need ACID Transactions over a service, you’re going to need SOAP.
    • WS-ReliableMessaging: If your application needs Asynchronous processing and a guaranteed level of reliability and security. Rest doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying.
    • If the security is a major concern and the resources are not limited then we should use SOAP web services. Like if we are creating a web service for payment gateways, financial and telecommunication related work then we should go with SOAP as here high security is needed.

    enter image description here

    source1
    source2

    Oracle REPLACE() function isn't handling carriage-returns & line-feeds

    Ahah! Cade is on the money.

    An artifact in TOAD prints \r\n as two placeholder 'blob' characters, but prints a single \r also as two placeholders. The 1st step toward a solution is to use ..

    REPLACE( col_name, CHR(13) || CHR(10) )
    

    .. but I opted for the slightly more robust ..

    REPLACE(REPLACE( col_name, CHR(10) ), CHR(13) )
    

    .. which catches offending characters in any order. My many thanks to Cade.

    M.

    Transform DateTime into simple Date in Ruby on Rails

    I recently wrote a gem to simplify this process and to neaten up your views, etc etc.

    Check it out at: http://github.com/platform45/easy_dates

    How to programmatically take a screenshot on Android?

    From Android 11 (API level 30) you can take screen shot with the accessibility service:

    takeScreenshot - Takes a screenshot of the specified display and returns it via an AccessibilityService.ScreenshotResult.

    How to use Redirect in the new react-router-dom of Reactjs

    Alternatively, you can use React conditional rendering.

    import { Redirect } from "react-router";
    import React, { Component } from 'react';
    
    class UserSignup extends Component {
      constructor(props) {
        super(props);
        this.state = {
          redirect: false
        }
      }
    render() {
     <React.Fragment>
       { this.state.redirect && <Redirect to="/signin" /> }   // you will be redirected to signin route
    }
    </React.Fragment>
    }
    

    How to return a value from a Form in C#?

    First you have to define attribute in form2(child) you will update this attribute in form2 and also from form1(parent) :

     public string Response { get; set; }
    
     private void OkButton_Click(object sender, EventArgs e)
     {
        Response = "ok";
     }
    
     private void CancelButton_Click(object sender, EventArgs e)
     {
        Response = "Cancel";
     }
    

    Calling of form2(child) from form1(parent):

      using (Form2 formObject= new Form2() )
      {
         formObject.ShowDialog();
    
          string result = formObject.Response; 
          //to update response of form2 after saving in result
          formObject.Response="";
    
          // do what ever with result...
          MessageBox.Show("Response from form2: "+result); 
      }
    

    How to get http headers in flask?

    Let's see how we get the params, headers and body in Flask. I'm gonna explain with the help of postman.

    enter image description here

    The params keys and values are reflected in the API endpoint. for example key1 and key2 in the endpoint : https://127.0.0.1/upload?key1=value1&key2=value2

    from flask import Flask, request
    app = Flask(__name__)
    
    @app.route('/upload')
    def upload():
    
      key_1 = request.args.get('key1')
      key_2 = request.args.get('key2')
      print(key_1)
      #--> value1
      print(key_2)
      #--> value2
    

    After params, let's now see how to get the headers:

    enter image description here

      header_1 = request.headers.get('header1')
      header_2 = request.headers.get('header2')
      print(header_1)
      #--> header_value1
      print(header_2)
      #--> header_value2
    

    Now let's see how to get the body

    enter image description here

      file_name = request.files['file'].filename
      ref_id = request.form['referenceId']
      print(ref_id)
      #--> WWB9838yb3r47484
    

    so we fetch the uploaded files with request.files and text with request.form

    Maximum number of records in a MySQL database table

    Link http://dev.mysql.com/doc/refman/5.7/en/column-count-limit.html

    Row Size Limits

    The maximum row size for a given table is determined by several factors:

    The internal representation of a MySQL table has a maximum row size limit of 65,535 bytes, even if the storage engine is capable of supporting larger rows. BLOB and TEXT columns only contribute 9 to 12 bytes toward the row size limit because their contents are stored separately from the rest of the row.

    The maximum row size for an InnoDB table, which applies to data stored locally within a database page, is slightly less than half a page for 4KB, 8KB, 16KB, and 32KB innodb_page_size settings. For example, the maximum row size is slightly less than 8KB for the default 16KB InnoDB page size. For 64KB pages, the maximum row size is slightly less than 16KB. See Section 15.8.8, “Limits on InnoDB Tables”.

    If a row containing variable-length columns exceeds the InnoDB maximum row size, InnoDB selects variable-length columns for external off-page storage until the row fits within the InnoDB row size limit. The amount of data stored locally for variable-length columns that are stored off-page differs by row format. For more information, see Section 15.11, “InnoDB Row Storage and Row Formats”.

    Different storage formats use different amounts of page header and trailer data, which affects the amount of storage available for rows.

    For information about InnoDB row formats, see Section 15.11, “InnoDB Row Storage and Row Formats”, and Section 15.8.3, “Physical Row Structure of InnoDB Tables”.

    For information about MyISAM storage formats, see Section 16.2.3, “MyISAM Table Storage Formats”.

    http://dev.mysql.com/doc/refman/5.7/en/innodb-restrictions.html

    How do I change the default library path for R packages

    See help(Startup) and help(.libPaths) as you have several possibilities where this may have gotten set. Among them are

    • setting R_LIBS_USER
    • assigning .libPaths() in .Rprofile or Rprofile.site

    and more.

    In this particular case you need to go backwards and unset whereever \\\\The library/path/I/don't/want is set.

    To otherwise ignore it you need to override it use explicitly i.e. via

    library("somePackage", lib.loc=.libPaths()[-1])
    

    when loading a package.

    check all socket opened in linux OS

    /proc/net/tcp -a list of open tcp sockets

    /proc/net/udp -a list of open udp sockets

    /proc/net/raw -a list all the 'raw' sockets

    These are the files, use cat command to view them. For example:

    cat /proc/net/tcp

    You can also use the lsof command.

    lsof is a command meaning "list open files", which is used in many Unix-like systems to report a list of all open files and the processes that opened them.

    SVN remains in conflict?

    I use the following command in order to remove conflict using command line

    svn revert "location of conflict folder" -R
    svn cleanup
    svn update
    

    for reverting current directory

    svn revert . -R
    

    Error: vector does not name a type

    You need to either qualify vector with its namespace (which is std), or import the namespace at the top of your CPP file:

    using namespace std;
    

    How can I check if a string is a number?

    Regex.IsMatch(stringToBeChecked, @"^\d+$")
    
    Regex.IsMatch("141241", @"^\d+$")  // True
    
    Regex.IsMatch("232a23", @"^\d+$")  // False
    
    Regex.IsMatch("12412a", @"^\d+$")  // False
    

    unique() for more than one variable

    This dplyr method works nicely when piping.

    For selected columns:

    library(dplyr)
    iris %>% 
      select(Sepal.Width, Species) %>% 
      t %>% c %>% unique
    
     [1] "3.5"        "setosa"     "3.0"        "3.2"        "3.1"       
     [6] "3.6"        "3.9"        "3.4"        "2.9"        "3.7"       
    [11] "4.0"        "4.4"        "3.8"        "3.3"        "4.1"       
    [16] "4.2"        "2.3"        "versicolor" "2.8"        "2.4"       
    [21] "2.7"        "2.0"        "2.2"        "2.5"        "2.6"       
    [26] "virginica" 
    

    Or for the whole dataframe:

    iris %>% t %>% c %>% unique 
    
     [1] "5.1"        "3.5"        "1.4"        "0.2"        "setosa"     "4.9"       
     [7] "3.0"        "4.7"        "3.2"        "1.3"        "4.6"        "3.1"       
    [13] "1.5"        "5.0"        "3.6"        "5.4"        "3.9"        "1.7"       
    [19] "0.4"        "3.4"        "0.3"        "4.4"        "2.9"        "0.1"       
    [25] "3.7"        "4.8"        "1.6"        "4.3"        "1.1"        "5.8"       
    [31] "4.0"        "1.2"        "5.7"        "3.8"        "1.0"        "3.3"       
    [37] "0.5"        "1.9"        "5.2"        "4.1"        "5.5"        "4.2"       
    [43] "4.5"        "2.3"        "0.6"        "5.3"        "7.0"        "versicolor"
    [49] "6.4"        "6.9"        "6.5"        "2.8"        "6.3"        "2.4"       
    [55] "6.6"        "2.7"        "2.0"        "5.9"        "6.0"        "2.2"       
    [61] "6.1"        "5.6"        "6.7"        "6.2"        "2.5"        "1.8"       
    [67] "6.8"        "2.6"        "virginica"  "7.1"        "2.1"        "7.6"       
    [73] "7.3"        "7.2"        "7.7"        "7.4"        "7.9" 
    

    Should I use 'border: none' or 'border: 0'?

    They are equivalent in effect, pointing to different shortcuts:

    border: 0;
    //short for..
    border-width: 0;
    

    And the other..

    border: none;
    //short for...
    border-style: none;
    

    Both work, just pick one and go with it :)

    Laravel: PDOException: could not find driver

    in ubuntu or windows

    • path php.ini

    • php -i enter image description here

    • Remove the ; from ;extension=pdo_mysql or extension=php_pdo_mysql.dll and add extension=pdo_mysql.so

      restart xampp or wampp

    • install sudo apt-get install php-mysql

    and

    php artisan migrate

    Run a PHP file in a cron job using CPanel

    In crontab system :

    • /usr/bin/php is php binary path (different in some systems ex: freebsd /usr/local/bin/php, linux: /usr/bin/php)
    • /home/username/public_html/cron/cron.php should be your php script path
    • /dev/null should be cron output , ex: /home/username/stdoutx.txt

    So you can monitor your cron by viewing cron output /home/username/stdoutx.txt

    How to use querySelectorAll only for elements that have a specific attribute set?

    With your example:

    <input type="checkbox" id="c2" name="c2" value="DE039230952"/>
    

    Replace $$ with document.querySelectorAll in the examples:

    $$('input') //Every input
    $$('[id]') //Every element with id
    $$('[id="c2"]') //Every element with id="c2"
    $$('input,[id]') //Every input + every element with id
    $$('input[id]') //Every input including id
    $$('input[id="c2"]') //Every input including id="c2"
    $$('input#c2') //Every input including id="c2" (same as above)
    $$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
    $$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
    $$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
    $$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230
    

    Use the examples directly with:

    const $$ = document.querySelectorAll.bind(document);
    

    Some additions:

    $$(.) //The same as $([class])
    $$(div > input) //div is parent tag to input
    document.querySelector() //equals to $$()[0] or $()
    

    TransactionRequiredException Executing an update/delete query

    If the previous answers fail, make sure you use @Service stereotype for the class where you call the update method on your repository. I originally used @Component instead and it was not working, the simple change to @Service made it work.

    How to set the max value and min value of <input> in html5 by javascript or jquery?

    Try this:

    <input type="number" max="???" min="???" step="0.5" id="myInput"/>
    
    $("#myInput").attr({
       "max" : 10,
       "min" : 2
    });
    

    Note:This will set max and min value only to single input

    Running a cron every 30 seconds

    in dir /etc/cron.d/

    new create a file excute_per_30s

    * * * * * yourusername  /bin/date >> /home/yourusername/temp/date.txt
    * * * * * yourusername sleep 30; /bin/date >> /home/yourusername/temp/date.txt
    

    will run cron every 30 seconds

    What does this GCC error "... relocation truncated to fit..." mean?

    You are attempting to link your project in such a way that the target of a relative addressing scheme is further away than can be supported with the 32-bit displacement of the chosen relative addressing mode. This could be because the current project is larger, because it is linking object files in a different order, or because there's an unnecessarily expansive mapping scheme in play.

    This question is a perfect example of why it's often productive to do a web search on the generic portion of an error message - you find things like this:

    http://www.technovelty.org/code/c/relocation-truncated.html

    Which offers some curative suggestions.

    Importing two classes with same name. How to handle?

    You can omit the import statements and refer to them using the entire path. Eg:

    java.util.Date javaDate = new java.util.Date()
    my.own.Date myDate = new my.own.Date();
    

    But I would say that using two classes with the same name and a similiar function is usually not the best idea unless you can make it really clear which is which.

    Catching errors in Angular HttpClient

    Angular 8 HttpClient Error Handling Service Example

    enter image description here

    api.service.ts

        import { Injectable } from '@angular/core';
        import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
        import { Student } from '../model/student';
        import { Observable, throwError } from 'rxjs';
        import { retry, catchError } from 'rxjs/operators';
    
        @Injectable({
          providedIn: 'root'
        })
        export class ApiService {
    
          // API path
          base_path = 'http://localhost:3000/students';
    
          constructor(private http: HttpClient) { }
    
          // Http Options
          httpOptions = {
            headers: new HttpHeaders({
              'Content-Type': 'application/json'
            })
          }
    
          // Handle API errors
          handleError(error: HttpErrorResponse) {
            if (error.error instanceof ErrorEvent) {
              // A client-side or network error occurred. Handle it accordingly.
              console.error('An error occurred:', error.error.message);
            } else {
              // The backend returned an unsuccessful response code.
              // The response body may contain clues as to what went wrong,
              console.error(
                `Backend returned code ${error.status}, ` +
                `body was: ${error.error}`);
            }
            // return an observable with a user-facing error message
            return throwError(
              'Something bad happened; please try again later.');
          };
    
    
          // Create a new item
          createItem(item): Observable<Student> {
            return this.http
              .post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
              .pipe(
                retry(2),
                catchError(this.handleError)
              )
          }
    
         ........
         ........
    
        }
    

    When does socket.recv(recv_size) return?

    Yes, your conclusion is correct. socket.recv is a blocking call.

    socket.recv(1024) will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv won't block.

    socket.recv will also end with an empty string if the connection is closed or there is an error.

    If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking.

    I had issues with socket.setblocking in the past, but feel free to try it if you want.

    Updating an object with setState in React

    You can try with this: (Note: name of input tag === field of object)

    <input name="myField" type="text" 
          value={this.state.myObject.myField} 
         onChange={this.handleChangeInpForm}>
    </input>
    
    -----------------------------------------------------------
    handleChangeInpForm = (e) => {
       let newObject = this.state.myObject;
       newObject[e.target.name] = e.target.value;
       this.setState({
         myObject: newObject 
       })
    }
    

    How to use readline() method in Java?

    In summary: I would be careful as to what code you copy. It is possible you are copying code which happens to work, rather than well chosen code.

    In intnumber, parseInt is used and in floatnumber valueOf is used why so?

    There is no good reason I can see. It's an inconsistent use of the APIs as you suspect.


    Java is case sensitive, and there isn't any Readline() method. Perhaps you mean readLine().

    DataInputStream.readLine() is deprecated in favour of using BufferedReader.readLine();

    However, for your case, I would use the Scanner class.

    Scanner sc = new Scanner(System.in);
    int intNum = sc.nextInt();
    float floatNum = sc.nextFloat();
    

    If you want to know what a class does I suggest you have a quick look at the Javadoc.

    Retrieve specific commit from a remote Git repository

    If the requested commit is in the pull requests of the remote repo, you can get it by its ID:

    # Add the remote repo path, let's call it 'upstream':
    git remote add upstream https://github.com/repo/project.git
    
    # checkout the pull ID, for example ID '60':
    git fetch upstream pull/60/head && git checkout FETCH_HEAD
    

    Make ABC Ordered List Items Have Bold Style

    Are you sure you correctly applied the styles, or that there isn't another stylesheet interfering with your lists? I tried this:

    <ol type="A">
    <li><span class="label">Text</span></li>
    <li><span class="label">Text</span></li>
    <li><span class="label">Text</span></li>
    </ol>
    

    Then in the stylesheet:

    ol {font-weight: bold;}
    ol li span.label {font-weight:normal;}
    

    And it bolded the A, B, C etc and not the text.

    (Tested it in Opera 9.6, FF 3, Safari 3.2 and IE 7)

    Excel: Search for a list of strings within a particular string using array formulas?

    This will return the matching word or an error if no match is found. For this example I used the following.

    List of words to search for: G1:G7
    Cell to search in: A1

    =INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))
    

    Enter as an array formula by pressing Ctrl+Shift+Enter.

    This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX() function, throwing an error.

    To return the row number of a matching word, you can use the following:

    =MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))
    

    This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1 if no match is found.

    How to check if array is not empty?

    print(len(a_list))
    

    As many languages have the len() function, in Python this would work for your question.

    If the output is not 0, the list is not empty.

    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

    protected $primaryKey = 'SongID';

    After adding to my model to tell the primary key because it was taking id(SongID) by default

    rbind error: "names do not match previous names"

    rbind() needs the two object names to be the same. For example, the first object names: ID Age, the next object names: ID Gender,if you want to use rbind(), it will print out:

    names do not match previous names

    Replace words in the body text

    Try to apply the above suggested solution on pretty big document, replacing pretty short strings which might be present in innerHTML or even innerText, and your html design becomes broken at best

    Therefore I firstly pickup only text node elements via HTML DOM nodes, like this

    function textNodesUnder(node){
      var all = [];
      for (node=node.firstChild;node;node=node.nextSibling){
        if (node.nodeType==3) all.push(node);
        else all = all.concat(textNodesUnder(node));
      }
      return all;
    }
    
    textNodes=textNodesUnder(document.body)
    for (i in textNodes) { textNodes[i].nodeValue = textNodes[i].nodeValue.replace(/hello/g, 'hi');    
    

    `and followingly I applied the replacement on all of them in cycle

    What is the difference between GitHub and gist?

    GISTS The Gist is an outstanding service provided by GitHub. Using this service, you can share your work publically or privately. You can share a single file, articles, full applications or source code etc.

    The GitHub is much more than just Gists. It provides immense services to group together a project or programs digital resources in a centralized location called repository and share among stakeholder. The GitHub repository will hold or maintain the multiple version of the files or history of changes and you can retrieve a specific version of a file when you want. Whereas gist will create each post as a new repository and will maintain the history of the file.

    How do you run your own code alongside Tkinter's event loop?

    The solution posted by Bjorn results in a "RuntimeError: Calling Tcl from different appartment" message on my computer (RedHat Enterprise 5, python 2.6.1). Bjorn might not have gotten this message, since, according to one place I checked, mishandling threading with Tkinter is unpredictable and platform-dependent.

    The problem seems to be that app.start() counts as a reference to Tk, since app contains Tk elements. I fixed this by replacing app.start() with a self.start() inside __init__. I also made it so that all Tk references are either inside the function that calls mainloop() or are inside functions that are called by the function that calls mainloop() (this is apparently critical to avoid the "different apartment" error).

    Finally, I added a protocol handler with a callback, since without this the program exits with an error when the Tk window is closed by the user.

    The revised code is as follows:

    # Run tkinter code in another thread
    
    import tkinter as tk
    import threading
    
    class App(threading.Thread):
    
        def __init__(self):
            threading.Thread.__init__(self)
            self.start()
    
        def callback(self):
            self.root.quit()
    
        def run(self):
            self.root = tk.Tk()
            self.root.protocol("WM_DELETE_WINDOW", self.callback)
    
            label = tk.Label(self.root, text="Hello World")
            label.pack()
    
            self.root.mainloop()
    
    
    app = App()
    print('Now we can continue running code while mainloop runs!')
    
    for i in range(100000):
        print(i)
    

    Jquery Setting Value of Input Field

    $('.formData').attr('value','YOUR_VALUE')
    

    ComboBox- SelectionChanged event has old value, not new value

    You can check SelectedIndex or SelectedValue or SelectedItem property in the SelectionChanged event of the Combobox control.

    How do I properly clean up Excel interop objects?

    So far it seems all answers involve some of these:

    1. Kill the process
    2. Use GC.Collect()
    3. Keep track of every COM object and release it properly.

    Which makes me appreciate how difficult this issue is :)

    I have been working on a library to simplify access to Excel, and I am trying to make sure that people using it won't leave a mess (fingers crossed).

    Instead of writing directly on the interfaces Interop provides, I am making extension methods to make live easier. Like ApplicationHelpers.CreateExcel() or workbook.CreateWorksheet("mySheetNameThatWillBeValidated"). Naturally, anything that is created may lead to an issue later on cleaning up, so I am actually favoring killing the process as last resort. Yet, cleaning up properly (third option), is probably the least destructive and most controlled.

    So, in that context I was wondering whether it wouldn't be best to make something like this:

    public abstract class ReleaseContainer<T>
    {
        private readonly Action<T> actionOnT;
    
        protected ReleaseContainer(T releasible, Action<T> actionOnT)
        {
            this.actionOnT = actionOnT;
            this.Releasible = releasible;
        }
    
        ~ReleaseContainer()
        {
            Release();
        }
    
        public T Releasible { get; private set; }
    
        private void Release()
        {
            actionOnT(Releasible);
            Releasible = default(T);
        }
    }
    

    I used 'Releasible' to avoid confusion with Disposable. Extending this to IDisposable should be easy though.

    An implementation like this:

    public class ApplicationContainer : ReleaseContainer<Application>
    {
        public ApplicationContainer()
            : base(new Application(), ActionOnExcel)
        {
        }
    
        private static void ActionOnExcel(Application application)
        {
            application.Show(); // extension method. want to make sure the app is visible.
            application.Quit();
            Marshal.FinalReleaseComObject(application);
        }
    }
    

    And one could do something similar for all sorts of COM objects.

    In the factory method:

        public static Application CreateExcelApplication(bool hidden = false)
        {
            var excel = new ApplicationContainer().Releasible;
            excel.Visible = !hidden;
    
            return excel;
        }
    

    I would expect that every container will be destructed properly by the GC, and therefore automatically make the call to Quit and Marshal.FinalReleaseComObject.

    Comments? Or is this an answer to the question of the third kind?

    What is more efficient? Using pow to square or just multiply it with itself?

    I was also wondering about the performance issue, and was hoping this would be optimised out by the compiler, based on the answer from @EmileCormier. However, I was worried that the test code he showed would still allow the compiler to optimise away the std::pow() call, since the same values were used in the call every time, which would allow the compiler to store the results and re-use it in the loop - this would explain the almost identical run-times for all cases. So I had a look into it too.

    Here's the code I used (test_pow.cpp):

    #include <iostream>                                                                                                                                                                                                                       
    #include <cmath>
    #include <chrono>
    
    class Timer {
      public:
        explicit Timer () : from (std::chrono::high_resolution_clock::now()) { }
    
        void start () {
          from = std::chrono::high_resolution_clock::now();
        }
    
        double elapsed() const {
          return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - from).count() * 1.0e-6;
        }
    
      private:
        std::chrono::high_resolution_clock::time_point from;
    };
    
    int main (int argc, char* argv[])
    {
      double total;
      Timer timer;
    
    
    
      total = 0.0;
      timer.start();
      for (double i = 0.0; i < 1.0; i += 1e-8)
        total += std::pow (i,2);
      std::cout << "std::pow(i,2): " << timer.elapsed() << "s (result = " << total << ")\n";
    
      total = 0.0;
      timer.start();
      for (double i = 0.0; i < 1.0; i += 1e-8)
        total += i*i;
      std::cout << "i*i: " << timer.elapsed() << "s (result = " << total << ")\n";
    
      std::cout << "\n";
    
      total = 0.0;
      timer.start();
      for (double i = 0.0; i < 1.0; i += 1e-8)
        total += std::pow (i,3);
      std::cout << "std::pow(i,3): " << timer.elapsed() << "s (result = " << total << ")\n";
    
      total = 0.0;
      timer.start();
      for (double i = 0.0; i < 1.0; i += 1e-8)
        total += i*i*i;
      std::cout << "i*i*i: " << timer.elapsed() << "s (result = " << total << ")\n";
    
    
      return 0;
    }
    

    This was compiled using:

    g++ -std=c++11 [-O2] test_pow.cpp -o test_pow
    

    Basically, the difference is the argument to std::pow() is the loop counter. As I feared, the difference in performance is pronounced. Without the -O2 flag, the results on my system (Arch Linux 64-bit, g++ 4.9.1, Intel i7-4930) were:

    std::pow(i,2): 0.001105s (result = 3.33333e+07)
    i*i: 0.000352s (result = 3.33333e+07)
    
    std::pow(i,3): 0.006034s (result = 2.5e+07)
    i*i*i: 0.000328s (result = 2.5e+07)
    

    With optimisation, the results were equally striking:

    std::pow(i,2): 0.000155s (result = 3.33333e+07)
    i*i: 0.000106s (result = 3.33333e+07)
    
    std::pow(i,3): 0.006066s (result = 2.5e+07)
    i*i*i: 9.7e-05s (result = 2.5e+07)
    

    So it looks like the compiler does at least try to optimise the std::pow(x,2) case, but not the std::pow(x,3) case (it takes ~40 times longer than the std::pow(x,2) case). In all cases, manual expansion performed better - but particularly for the power 3 case (60 times quicker). This is definitely worth bearing in mind if running std::pow() with integer powers greater than 2 in a tight loop...

    multiple plot in one figure in Python

    This is very simple to do:

    import matplotlib.pyplot as plt
    
    plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
    plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
    plt.legend(loc='best')
    plt.show()
    

    You can keep adding plt.plot as many times as you like. As for line type, you need to first specify the color. So for blue, it's b. And for a normal line it's -. An example would be:

    plt.plot(total_lengths, sort_times_heap, 'b-', label="Heap")
    

    scrollable div inside container

    Is this what you are wanting?

    _x000D_
    _x000D_
    <body>_x000D_
      <div id="div1" style="height: 500px;">_x000D_
        <div id="div2" style="height: inherit; overflow: auto; border:1px solid red;">_x000D_
          <div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </body>
    _x000D_
    _x000D_
    _x000D_

    http://jsfiddle.net/fMs67/1/

    How to split/partition a dataset into training and test datasets for, e.g., cross validation?

    Likely you will not only need to split into train and test, but also cross validation to make sure your model generalizes. Here I am assuming 70% training data, 20% validation and 10% holdout/test data.

    Check out the np.split:

    If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in

    ary[:2] ary[2:3] ary[3:]

    t, v, h = np.split(df.sample(frac=1, random_state=1), [int(0.7*len(df)), int(0.9*len(df))]) 
    

    How do I integrate Ajax with Django applications?

    Further from yuvi's excellent answer, I would like to add a small specific example on how to deal with this within Django (beyond any js that will be used). The example uses AjaxableResponseMixin and assumes an Author model.

    import json
    
    from django.http import HttpResponse
    from django.views.generic.edit import CreateView
    from myapp.models import Author
    
    class AjaxableResponseMixin(object):
        """
        Mixin to add AJAX support to a form.
        Must be used with an object-based FormView (e.g. CreateView)
        """
        def render_to_json_response(self, context, **response_kwargs):
            data = json.dumps(context)
            response_kwargs['content_type'] = 'application/json'
            return HttpResponse(data, **response_kwargs)
    
        def form_invalid(self, form):
            response = super(AjaxableResponseMixin, self).form_invalid(form)
            if self.request.is_ajax():
                return self.render_to_json_response(form.errors, status=400)
            else:
                return response
    
        def form_valid(self, form):
            # We make sure to call the parent's form_valid() method because
            # it might do some processing (in the case of CreateView, it will
            # call form.save() for example).
            response = super(AjaxableResponseMixin, self).form_valid(form)
            if self.request.is_ajax():
                data = {
                    'pk': self.object.pk,
                }
                return self.render_to_json_response(data)
            else:
                return response
    
    class AuthorCreate(AjaxableResponseMixin, CreateView):
        model = Author
        fields = ['name']
    

    Source: Django documentation, Form handling with class-based views

    The link to version 1.6 of Django is no longer available updated to version 1.11

    Shell script to copy files from one location to another location and rename add the current date to every file

    In bash, provided you files names have no spaces:

    cd /home/webapps/project1/folder1
    for f in *.csv
    do 
       cp -v "$f" /home/webapps/project1/folder2/"${f%.csv}"$(date +%m%d%y).csv
    done
    

    Target class controller does not exist - Laravel 8

    In laravel-8 you can use like this

     Route::group(['namespace'=>'App\Http\Controllers', 'prefix'=>'admin',
     'as'=>'admin.','middleware'=>['auth:sanctum', 'verified']], function()
    {
        Route::resource('/dashboard', 'DashboardController')->only([
            'index'
        ]);
    });
    

    Thanks

    javascript filter array of objects

    For those who want to filter from an array of objects using any key:

    _x000D_
    _x000D_
    function filterItems(items, searchVal) {_x000D_
      return items.filter((item) => Object.values(item).includes(searchVal));_x000D_
    }_x000D_
    let data = [_x000D_
      { "name": "apple", "type": "fruit", "id": 123234 },_x000D_
      { "name": "cat", "type": "animal", "id": 98989 },_x000D_
      { "name": "something", "type": "other", "id": 656565 }]_x000D_
    _x000D_
    _x000D_
    console.log("Filtered by name: ", filterItems(data, "apple"));_x000D_
    console.log("Filtered by type: ", filterItems(data, "animal"));_x000D_
    console.log("Filtered by id: ", filterItems(data, 656565));
    _x000D_
    _x000D_
    _x000D_

    filter from an array of the JSON objects:**

    How to convert Milliseconds to "X mins, x seconds" in Java?

    I modified @MyKuLLSKI 's answer and added plurlization support. I took out seconds because I didn't need them, though feel free to re-add it if you need it.

    public static String intervalToHumanReadableTime(int intervalMins) {
    
        if(intervalMins <= 0) {
            return "0";
        } else {
    
            long intervalMs = intervalMins * 60 * 1000;
    
            long days = TimeUnit.MILLISECONDS.toDays(intervalMs);
            intervalMs -= TimeUnit.DAYS.toMillis(days);
            long hours = TimeUnit.MILLISECONDS.toHours(intervalMs);
            intervalMs -= TimeUnit.HOURS.toMillis(hours);
            long minutes = TimeUnit.MILLISECONDS.toMinutes(intervalMs);
    
            StringBuilder sb = new StringBuilder(12);
    
            if (days >= 1) {
                sb.append(days).append(" day").append(pluralize(days)).append(", ");
            }
    
            if (hours >= 1) {
                sb.append(hours).append(" hour").append(pluralize(hours)).append(", ");
            }
    
            if (minutes >= 1) {
                sb.append(minutes).append(" minute").append(pluralize(minutes));
            } else {
                sb.delete(sb.length()-2, sb.length()-1);
            }
    
            return(sb.toString());          
    
        }
    
    }
    
    public static String pluralize(long val) {
        return (Math.round(val) > 1 ? "s" : "");
    }
    

    Correct modification of state arrays in React.js

    Easiest, if you are using ES6.

    initialArray = [1, 2, 3];
    
    newArray = [ ...initialArray, 4 ]; // --> [1,2,3,4]
    

    New array will be [1,2,3,4]

    to update your state in React

    this.setState({
      arrayvar:[...this.state.arrayvar, newelement]
    });
    

    Learn more about array destructuring

    Horizontal Scroll Table in Bootstrap/CSS

    Here is one possiblity for you if you are using Bootstrap 3

    live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/

    edit view: http://jsfiddle.net/panchroma/vPH8N/

    I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive

    ie:

    <div class="table-responsive">
    <table class="table">
    ...
    </table>
    </div>
    

    Should a function have only one return statement?

    There are times when it is necessary for performance reasons (I don't want to fetch a different cache line kind of the same need as a continue; sometimes).

    If you allocate resources (memory, file descriptors, locks, etc.) without using RAII then muliple returns can be error prone and are certainly duplicative as the releases need to be done manually multiple times and you must keep careful track.

    In the example:

    function()
    {
        HRESULT error = S_OK;
    
        if(SUCCEEDED(Operation1()))
        {
            if(SUCCEEDED(Operation2()))
            {
                if(SUCCEEDED(Operation3()))
                {
                    if(SUCCEEDED(Operation4()))
                    {
                    }
                    else
                    {
                        error = OPERATION4FAILED;
                    }
                }
                else
                {
                    error = OPERATION3FAILED;
                }
            }
            else
            {
                error = OPERATION2FAILED;
            }
        }
        else
        {
            error = OPERATION1FAILED;
        }
    
        return error;
    }
    

    I would have written it as:

    function() {
        HRESULT error = OPERATION1FAILED;//assume failure
        if(SUCCEEDED(Operation1())) {
    
            error = OPERATION2FAILED;//assume failure
            if(SUCCEEDED(Operation3())) {
    
                error = OPERATION3FAILED;//assume failure
                if(SUCCEEDED(Operation3())) {
    
                    error = OPERATION4FAILED; //assume failure
                    if(SUCCEEDED(Operation4())) {
    
                        error = S_OK;
                    }
                }
            }
        }
        return error;
    }
    

    Which certainly seems better.

    This tends to be especially helpful in the manual resource release case as where and which releases are necessary is pretty straightforward. As in the following example:

    function() {
        HRESULT error = OPERATION1FAILED;//assume failure
        if(SUCCEEDED(Operation1())) {
    
            //allocate resource for op2;
            char* const p2 = new char[1024];
            error = OPERATION2FAILED;//assume failure
            if(SUCCEEDED(Operation2(p2))) {
    
                //allocate resource for op3;
                char* const p3 = new char[1024];
                error = OPERATION3FAILED;//assume failure
                if(SUCCEEDED(Operation3(p3))) {
    
                    error = OPERATION4FAILED; //assume failure
                    if(SUCCEEDED(Operation4(p2,p3))) {
    
                        error = S_OK;
                    }
                }
                //free resource for op3;
                delete [] p3;
            }
            //free resource for op2;
            delete [] p2;
        }
        return error;
    }
    

    If you write this code without RAII (forgetting the issue of exceptions!) with multiple exits then the deletes have to be written multiple times. If you write it with }else{ then it gets a little ugly.

    But RAII makes the multiple exit resource issue moot.

    How to set text color in submit button?

    Use this CSS:

    color: red;
    

    that's all.

    Show image using file_get_contents

    Do i need to modify the headers and just echo it or something?

    exactly.

    Send a header("content-type: image/your_image_type"); and the data afterwards.

    Create numpy matrix filled with NaNs

    Are you familiar with numpy.nan?

    You can create your own method such as:

    def nans(shape, dtype=float):
        a = numpy.empty(shape, dtype)
        a.fill(numpy.nan)
        return a
    

    Then

    nans([3,4])
    

    would output

    array([[ NaN,  NaN,  NaN,  NaN],
           [ NaN,  NaN,  NaN,  NaN],
           [ NaN,  NaN,  NaN,  NaN]])
    

    I found this code in a mailing list thread.

    Programmatic equivalent of default(Type)

    Can't find anything simple and elegant just yet, but I have one idea: If you know the type of the property you wish to set, you can write your own default(T). There are two cases - T is a value type, and T is a reference type. You can see this by checking T.IsValueType. If T is a reference type, then you can simply set it to null. If T is a value type, then it will have a default parameterless constructor that you can call to get a "blank" value.

    How to determine if a string is a number with C++?

    I'd suggest a regex approach. A full regex-match (for example, using boost::regex) with

    -?[0-9]+([\.][0-9]+)?
    

    would show whether the string is a number or not. This includes positive and negative numbers, integer as well as decimal.

    Other variations:

    [0-9]+([\.][0-9]+)?
    

    (only positive)

    -?[0-9]+
    

    (only integer)

    [0-9]+
    

    (only positive integer)

    How to list files using dos commands?

    Try dir /b, for bare format.

    dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

    C:\>dir /?
    Displays a list of files and subdirectories in a directory.
    
    DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
      [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]
    
      [drive:][path][filename]
                  Specifies drive, directory, and/or files to list.
    
      /A          Displays files with specified attributes.
      attributes   D  Directories                R  Read-only files
                   H  Hidden files               A  Files ready for archiving
                   S  System files               I  Not content indexed files
                   L  Reparse Points             -  Prefix meaning not
      /B          Uses bare format (no heading information or summary).
      /C          Display the thousand separator in file sizes.  This is the
                  default.  Use /-C to disable display of separator.
      /D          Same as wide but files are list sorted by column.
      /L          Uses lowercase.
      /N          New long list format where filenames are on the far right.
      /O          List by files in sorted order.
      sortorder    N  By name (alphabetic)       S  By size (smallest first)
                   E  By extension (alphabetic)  D  By date/time (oldest first)
                   G  Group directories first    -  Prefix to reverse order
      /P          Pauses after each screenful of information.
      /Q          Display the owner of the file.
      /R          Display alternate data streams of the file.
      /S          Displays files in specified directory and all subdirectories.
      /T          Controls which time field displayed or used for sorting
      timefield   C  Creation
                  A  Last Access
                  W  Last Written
      /W          Uses wide list format.
      /X          This displays the short names generated for non-8dot3 file
                  names.  The format is that of /N with the short name inserted
                  before the long name. If no short name is present, blanks are
                  displayed in its place.
      /4          Displays four-digit years
    
    Switches may be preset in the DIRCMD environment variable.  Override
    preset switches by prefixing any switch with - (hyphen)--for example, /-W.
    

    SQL Server, division returns zero

    if you declare it as float or any decimal format it will display

    0

    only

    E.g :

    declare @weight float;
    
    SET @weight= 47 / 638; PRINT @weight
    

    Output : 0

    If you want the output as

    0.073667712

    E.g

    declare @weight float;
    
    SET @weight= 47.000000000 / 638.000000000; PRINT @weight
    

    jQuery text() and newlines

    It's the year 2015. The correct answer to this question at this point is to use CSS white-space: pre-line or white-space: pre-wrap. Clean and elegant. The lowest version of IE that supports the pair is 8.

    https://css-tricks.com/almanac/properties/w/whitespace/

    P.S. Until CSS3 become common you'd probably need to manually trim off initial and/or trailing white-spaces.

    Fit image to table cell [Pure HTML]

    if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:

    <img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
    

    see the fiddle : http://jsfiddle.net/Lk2Rh/27/

    but still it better to handling this with CSS, i suggest you that.

    • I hope this help.

    Maximum number of rows of CSV data in excel sheet

    In my memory, excel (versions >= 2007) limits the power 2 of 20: 1.048.576 lines.

    Csv is over to this boundary, like ordinary text file. So you will be care of the transfer between two formats.

    Git on Windows: How do you set up a mergetool?

    For IntelliJ IDEA (Community Edition) 3-way git mergetool configuration in Windows environment (~/.gitconfig)

    Cygwin

    [mergetool "ideamerge"]
         cmd = C:/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe merge `cygpath -wa $LOCAL` `cygpath -wa $REMOTE` `cygpath -wa $BASE` `cygpath -wa $MERGED`
    [merge]
         tool = ideamerge
    

    Msys

    [mergetool "ideamerge"]
    cmd = "/c/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe" merge `~/winpath.sh $LOCAL` `~/winpath.sh $REMOTE` `~/winpath.sh $BASE` `~/winpath.sh $MERGED`
    [merge]
     tool = ideamerge
    

    The ~/winpath.sh is to convert paths to Windows on msys and is taken from msys path conversion question on stackoverflow

    #! /bin/sh                                                               
    
    function wpath {                                                         
        if [ -z "$1" ]; then                                                 
            echo "$@"                                                        
        else                                                                 
            if [ -f "$1" ]; then                                             
                local dir=$(dirname "$1")                                    
                local fn=$(basename "$1")                                    
                echo "$(cd "$dir"; echo "$(pwd -W)/$fn")" | sed 's|/|\\|g';  
            else                                                             
                if [ -d "$1" ]; then                                         
                    echo "$(cd "$1"; pwd -W)" | sed 's|/|\\|g';              
                else                                                         
                    echo "$1" | sed 's|^/\(.\)/|\1:\\|g; s|/|\\|g';          
                fi                                                           
            fi                                                               
        fi                                                                   
    }                                                                        
    
    wpath "$@" 
    

    What is the right way to populate a DropDownList from a database?

    You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).

    For example, if you wanted to use a DataTable:

    ddlSubject.DataSource = subjectsTable;
    ddlSubject.DataTextField = "SubjectNamne";
    ddlSubject.DataValueField = "SubjectID";
    ddlSubject.DataBind();
    

    EDIT - More complete example

    private void LoadSubjects()
    {
    
        DataTable subjects = new DataTable();
    
        using (SqlConnection con = new SqlConnection(connectionString))
        {
    
            try
            {
                SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
                adapter.Fill(subjects);
    
                ddlSubject.DataSource = subjects;
                ddlSubject.DataTextField = "SubjectNamne";
                ddlSubject.DataValueField = "SubjectID";
                ddlSubject.DataBind();
            }
            catch (Exception ex)
            {
                // Handle the error
            }
    
        }
    
        // Add the initial item - you can add this even if the options from the
        // db were not successfully loaded
        ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
    
    }
    

    To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:

    <asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
        <asp:ListItem Text="<Select Subject>" Value="0" />
    </asp:DropDownList>
    

    You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:

    ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
    

    from the code-behind, or you'll have two "" items.

    How do I iterate through each element in an n-dimensional matrix in MATLAB?

    The idea of a linear index for arrays in matlab is an important one. An array in MATLAB is really just a vector of elements, strung out in memory. MATLAB allows you to use either a row and column index, or a single linear index. For example,

    A = magic(3)
    A =
         8     1     6
         3     5     7
         4     9     2
    
    A(2,3)
    ans =
         7
    
    A(8)
    ans =
         7
    

    We can see the order the elements are stored in memory by unrolling the array into a vector.

    A(:)
    ans =
         8
         3
         4
         1
         5
         9
         6
         7
         2
    

    As you can see, the 8th element is the number 7. In fact, the function find returns its results as a linear index.

    find(A>6)
    ans =
         1
         6
         8
    

    The result is, we can access each element in turn of a general n-d array using a single loop. For example, if we wanted to square the elements of A (yes, I know there are better ways to do this), one might do this:

    B = zeros(size(A));
    for i = 1:numel(A)
      B(i) = A(i).^2;
    end
    
    B
    B =
        64     1    36
         9    25    49
        16    81     4
    

    There are many circumstances where the linear index is more useful. Conversion between the linear index and two (or higher) dimensional subscripts is accomplished with the sub2ind and ind2sub functions.

    The linear index applies in general to any array in matlab. So you can use it on structures, cell arrays, etc. The only problem with the linear index is when they get too large. MATLAB uses a 32 bit integer to store these indexes. So if your array has more then a total of 2^32 elements in it, the linear index will fail. It is really only an issue if you use sparse matrices often, when occasionally this will cause a problem. (Though I don't use a 64 bit MATLAB release, I believe that problem has been resolved for those lucky individuals who do.)

    Increase days to php current Date()

    a day is 86400 seconds.

    $tomorrow = date('y:m:d', time() + 86400);
    

    Where do you include the jQuery library from? Google JSAPI? CDN?

    If I am responsible for the 'live' site I better be aware of everything that is going on and into my site. For that reason I host the jquery-min version myself either on the same server or a static/external server but either way a location where only I (or my program/proxy) can update the library after having verified/tested every change

    check output from CalledProcessError

    If you want to get stdout and stderr back (including extracting it from the CalledProcessError in the event that one occurs), use the following:

    import subprocess
    
    command = ["ls", "-l"]
    try:
        output = subprocess.check_output(command, stderr=subprocess.STDOUT).decode()
        success = True 
    except subprocess.CalledProcessError as e:
        output = e.output.decode()
        success = False
    
    print(output)
    

    This is Python 2 and 3 compatible.

    If your command is a string rather than an array, prefix this with:

    import shlex
    command = shlex.split(command)
    

    Get an image extension from an uploaded file in Laravel

     //working code from laravel 5.2
    
     public function store(Request $request)
     {
              $file = $request->file('file');
                if($file)
                {
                        $extension =  $file->clientExtension();
                }
                echo $extension;
     }
    

    Project has no default.properties file! Edit the project properties to set one

    File-> Switch workspace -> newWorkSpace will solve the issue dx.jar

    Where are the Android icon drawables within the SDK?

    1. Right click on Drawable folder

    2. click on new

    3. click on image asset

    Then you can select an icon type

    Truncate Two decimal places without rounding

    This is an old question, but many anwsers don't perform well or overflow for big numbers. I think D. Nesterov answer is the best one: robust, simple and fast. I just want to add my two cents. I played around with decimals and also checked out the source code. From the public Decimal (int lo, int mid, int hi, bool isNegative, byte scale) constructor documentation.

    The binary representation of a Decimal number consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the integer number and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10 raised to an exponent ranging from 0 to 28.

    Knowing this, my first approach was to create another decimal whose scale corresponds to the decimals that I wanted to discard, then truncate it and finally create a decimal with the desired scale.

    private const int ScaleMask = 0x00FF0000;
        public static Decimal Truncate(decimal target, byte decimalPlaces)
        {
            var bits = Decimal.GetBits(target);
            var scale = (byte)((bits[3] & (ScaleMask)) >> 16);
    
            if (scale <= decimalPlaces)
                return target;
    
            var temporalDecimal = new Decimal(bits[0], bits[1], bits[2], target < 0, (byte)(scale - decimalPlaces));
            temporalDecimal = Math.Truncate(temporalDecimal);
    
            bits = Decimal.GetBits(temporalDecimal);
            return new Decimal(bits[0], bits[1], bits[2], target < 0, decimalPlaces);
        }
    

    This method is not faster than D. Nesterov's and it is more complex, so I played around a little bit more. My guess is that having to create an auxiliar decimal and retrieving the bits twice is making it slower. On my second attempt, I manipulated the components returned by Decimal.GetBits(Decimal d) method myself. The idea is to divide the components by 10 as many times as needed and reduce the scale. The code is based (heavily) on the Decimal.InternalRoundFromZero(ref Decimal d, int decimalCount) method.

    private const Int32 MaxInt32Scale = 9;
    private const int ScaleMask = 0x00FF0000;
        private const int SignMask = unchecked((int)0x80000000);
        // Fast access for 10^n where n is 0-9        
        private static UInt32[] Powers10 = new UInt32[] {
            1,
            10,
            100,
            1000,
            10000,
            100000,
            1000000,
            10000000,
            100000000,
            1000000000
        };
    
        public static Decimal Truncate(decimal target, byte decimalPlaces)
        {
            var bits = Decimal.GetBits(target);
            int lo = bits[0];
            int mid = bits[1];
            int hi = bits[2];
            int flags = bits[3];
    
            var scale = (byte)((flags & (ScaleMask)) >> 16);
            int scaleDifference = scale - decimalPlaces;
            if (scaleDifference <= 0)
                return target;
    
            // Divide the value by 10^scaleDifference
            UInt32 lastDivisor;
            do
            {
                Int32 diffChunk = (scaleDifference > MaxInt32Scale) ? MaxInt32Scale : scaleDifference;
                lastDivisor = Powers10[diffChunk];
                InternalDivRemUInt32(ref lo, ref mid, ref hi, lastDivisor);
                scaleDifference -= diffChunk;
            } while (scaleDifference > 0);
    
    
            return new Decimal(lo, mid, hi, (flags & SignMask)!=0, decimalPlaces);
        }
        private static UInt32 InternalDivRemUInt32(ref int lo, ref int mid, ref int hi, UInt32 divisor)
        {
            UInt32 remainder = 0;
            UInt64 n;
            if (hi != 0)
            {
                n = ((UInt32)hi);
                hi = (Int32)((UInt32)(n / divisor));
                remainder = (UInt32)(n % divisor);
            }
            if (mid != 0 || remainder != 0)
            {
                n = ((UInt64)remainder << 32) | (UInt32)mid;
                mid = (Int32)((UInt32)(n / divisor));
                remainder = (UInt32)(n % divisor);
            }
            if (lo != 0 || remainder != 0)
            {
                n = ((UInt64)remainder << 32) | (UInt32)lo;
                lo = (Int32)((UInt32)(n / divisor));
                remainder = (UInt32)(n % divisor);
            }
            return remainder;
        }
    

    I haven't performed rigorous performance tests, but on a MacOS Sierra 10.12.6, 3,06 GHz Intel Core i3 processor and targeting .NetCore 2.1 this method seems to be much faster than D. Nesterov's (I won't give numbers since, as I have mentioned, my tests are not rigorous). It is up to whoever implements this to evaluate whether or not the performance gains pay off for the added code complexity.

    get string from right hand side

    I just found out that regexp_substr() is perfect for this purpose :)

    My challenge is picking the right-hand 16 chars from a reference string which theoretically can be everything from 7ish to 250ish chars long. It annoys me that substr( OurReference , -16 ) returns null when length( OurReference ) < 16. (On the other hand, it's kind of logical, too, that Oracle consequently returns null whenever a call to substr() goes beyond a string's boundaries.) However, I can set a regular expression to recognise everything between 1 and 16 of any char right before the end of the string:

    regexp_substr( OurReference , '.{1,16}$' )
    

    When it comes to performance issues regarding regular expressions, I can't say which of the GREATER() solution and this one performs best. Anyone test this? Generally I've experienced that regular expressions are quite fast if they're written neat and well (as this one).

    Good luck! :)

    How to convert string to date to string in Swift iOS?

    //String to Date Convert
    
    var dateString = "2014-01-12"
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let s = dateFormatter.dateFromString(dateString)
    println(s)
    
    
    //CONVERT FROM NSDate to String  
    
    let date = NSDate()
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd" 
    var dateString = dateFormatter.stringFromDate(date)
    println(dateString)  
    

    Binding value to input in Angular JS

    You don't need to set the value at all. ng-model takes care of it all:

    • set the input value from the model
    • update the model value when you change the input
    • update the input value when you change the model from js

    Here's the fiddle for this: http://jsfiddle.net/terebentina/9mFpp/

    Linux: Which process is causing "device busy" when doing umount?

    lsof and fuser didn't give me anything either.

    After a process of renaming all possible directories to .old and rebooting the system every time after I made changes I found one particular directory (relating to postfix) that was responsible.

    It turned out that I had once made a symlink from /var/spool/postfix to /disk2/pers/mail/postfix/varspool in order to minimise disk writes on an SDCARD-based root filesystem (Sheeva Plug).

    With this symlink, even after stopping the postfix and dovecot services (both ps aux as well as netstat -tuanp didn't show anything related) I was not able to unmount /disk2/pers.

    When I removed the symlink and updated the postfix and dovecot config files to point directly to the new dirs on /disk2/pers/ I was able to successfully stop the services and unmount the directory.

    Next time I will look more closely at the output of:

    ls -lR /var | grep ^l | grep disk2
    

    The above command will recursively list all symbolic links in a directory tree (here starting at /var) and filter out those names that point to a specific target mount point (here disk2).

    Calling a Sub and returning a value

    Private Sub Main()
        Dim value = getValue()
        'do something with value
    End Sub
    
    Private Function getValue() As Integer
        Return 3
    End Function
    

    Windows Bat file optional argument parsing

    Here is the arguments parser. You can mix any string arguments (kept untouched) or escaped options (single or option/value pairs). To test it uncomment last 2 statements and run as:

    getargs anystr1 anystr2 /test$1 /test$2=123 /test$3 str anystr3
    

    Escape char is defined as "_SEP_=/", redefine if needed.

    @echo off
    
    REM Command line argument parser. Format (both "=" and "space" separators are supported):
    REM   anystring1 anystring2 /param1 /param2=value2 /param3 value3 [...] anystring3 anystring4
    REM Returns enviroment variables as:
    REM   param1=1
    REM   param2=value2
    REM   param3=value3
    REM Leading and traling strings are preserved as %1, %2, %3 ... %9 parameters
    REM but maximum total number of strings is 9 and max number of leading strings is 8
    REM Number of parameters is not limited!
    
    set _CNT_=1
    set _SEP_=/
    
    :PARSE
    
    if %_CNT_%==1 set _PARAM1_=%1 & set _PARAM2_=%2
    if %_CNT_%==2 set _PARAM1_=%2 & set _PARAM2_=%3
    if %_CNT_%==3 set _PARAM1_=%3 & set _PARAM2_=%4
    if %_CNT_%==4 set _PARAM1_=%4 & set _PARAM2_=%5
    if %_CNT_%==5 set _PARAM1_=%5 & set _PARAM2_=%6
    if %_CNT_%==6 set _PARAM1_=%6 & set _PARAM2_=%7
    if %_CNT_%==7 set _PARAM1_=%7 & set _PARAM2_=%8
    if %_CNT_%==8 set _PARAM1_=%8 & set _PARAM2_=%9
    
    if "%_PARAM2_%"=="" set _PARAM2_=1
    
    if "%_PARAM1_:~0,1%"=="%_SEP_%" (
      if "%_PARAM2_:~0,1%"=="%_SEP_%" (
        set %_PARAM1_:~1,-1%=1
        shift /%_CNT_%
      ) else (
        set %_PARAM1_:~1,-1%=%_PARAM2_%
        shift /%_CNT_%
        shift /%_CNT_%
      )
    ) else (
      set /a _CNT_+=1
    )
    
    if /i %_CNT_% LSS 9 goto :PARSE
    
    set _PARAM1_=
    set _PARAM2_=
    set _CNT_=
    
    rem getargs anystr1 anystr2 /test$1 /test$2=123 /test$3 str anystr3
    rem set | find "test$"
    rem echo %1 %2 %3 %4 %5 %6 %7 %8 %9
    
    :EXIT
    

    PDO mysql: How to know if insert was successful

    PDOStatement->execute() returns true on success. There is also PDOStatement->errorCode() which you can check for errors.

    Sending email with gmail smtp with codeigniter email library

    It can be this:

    If you are using cpanel for your website smtp restrictions are problem and cause this error. SMTP Restrictions

    Error while sending an email with CodeIgniter

    T-SQL How to create tables dynamically in stored procedures?

    You are using a table variable i.e. you should declare the table. This is not a temporary table.

    You create a temp table like so:

    CREATE TABLE #customer
    (
         Name varchar(32) not null
    )
    

    You declare a table variable like so:

    DECLARE @Customer TABLE
    (
          Name varchar(32) not null
    )
    

    Notice that a temp table is declared using # and a table variable is declared using a @. Go read about the difference between table variables and temp tables.

    UPDATE:

    Based on your comment below you are actually trying to create tables in a stored procedure. For this you would need to use dynamic SQL. Basically dynamic SQL allows you to construct a SQL Statement in the form of a string and then execute it. This is the ONLY way you will be able to create a table in a stored procedure. I am going to show you how and then discuss why this is not generally a good idea.

    Now for a simple example (I have not tested this code but it should give you a good indication of how to do it):

    CREATE PROCEDURE sproc_BuildTable 
        @TableName NVARCHAR(128)
       ,@Column1Name NVARCHAR(32)
       ,@Column1DataType NVARCHAR(32)
       ,@Column1Nullable NVARCHAR(32)
    AS
    
       DECLARE @SQLString NVARCHAR(MAX)
       SET @SQString = 'CREATE TABLE '+@TableName + '( '+@Column1Name+' '+@Column1DataType +' '+@Column1Nullable +') ON PRIMARY '
    
       EXEC (@SQLString)
       GO
    

    This stored procedure can be executed like this:

    sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'

    There are some major problems with this type of stored procedure.

    Its going to be difficult to cater for complex tables. Imagine the following table structure:

    CREATE TABLE [dbo].[Customers] (
        [CustomerID] [int] IDENTITY(1,1) NOT NULL,
        [CustomerName] [nvarchar](64) NOT NULL,
        [CustomerSUrname] [nvarchar](64) NOT NULL,
        [CustomerDateOfBirth] [datetime] NOT NULL,
        [CustomerApprovedDiscount] [decimal](3, 2) NOT NULL,
        [CustomerActive] [bit] NOT NULL,
        CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED 
        (
            [CustomerID] ASC
        ) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,      ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO
    
    ALTER TABLE [dbo].[Customers] ADD CONSTRAINT [DF_Customers_CustomerApprovedDiscount] DEFAULT ((0.00)) FOR [CustomerApprovedDiscount]
    GO 
    

    This table is a little more complex than the first example, but not a lot. The stored procedure will be much, much more complex to deal with. So while this approach might work for small tables it is quickly going to be unmanageable.

    Creating tables require planning. When you create tables they should be placed strategically on different filegroups. This is to ensure that you don't cause disk I/O contention. How will you address scalability if everything is created on the primary file group?

    Could you clarify why you need tables to be created dynamically?

    UPDATE 2:

    Delayed update due to workload. I read your comment about needing to create a table for each shop and I think you should look at doing it like the example I am about to give you.

    In this example I make the following assumptions:

    1. It's an e-commerce site that has many shops
    2. A shop can have many items (goods) to sell.
    3. A particular item (good) can be sold at many shops
    4. A shop will charge different prices for different items (goods)
    5. All prices are in $ (USD)

    Let say this e-commerce site sells gaming consoles (i.e. Wii, PS3, XBOX360).

    Looking at my assumptions I see a classical many-to-many relationship. A shop can sell many items (goods) and items (goods) can be sold at many shops. Let's break this down into tables.

    First I would need a shop table to store all the information about the shop.

    A simple shop table might look like this:

    CREATE TABLE [dbo].[Shop](
        [ShopID] [int] IDENTITY(1,1) NOT NULL,
        [ShopName] [nvarchar](128) NOT NULL,
        CONSTRAINT [PK_Shop] PRIMARY KEY CLUSTERED 
        (
          [ShopID] ASC
        ) WITH (
                  PAD_INDEX  = OFF
                  , STATISTICS_NORECOMPUTE  = OFF
                  , IGNORE_DUP_KEY = OFF
                  , ALLOW_ROW_LOCKS  = ON
                  , ALLOW_PAGE_LOCKS  = ON
        ) ON [PRIMARY]
        ) ON [PRIMARY]
    
        GO
    

    Let's insert three shops into the database to use during our example. The following code will insert three shops:

    INSERT INTO Shop
    SELECT 'American Games R US'
    UNION
    SELECT 'Europe Gaming Experience'
    UNION
    SELECT 'Asian Games Emporium'
    

    If you execute a SELECT * FROM Shop you will probably see the following:

    ShopID  ShopName
    1           American Games R US
    2           Asian Games Emporium
    3           Europe Gaming Experience
    

    Right, so now let's move onto the Items (goods) table. Since the items/goods are products of various companies I am going to call the table product. You can execute the following code to create a simple Product table.

    CREATE TABLE [dbo].[Product](
        [ProductID] [int] IDENTITY(1,1) NOT NULL,
        [ProductDescription] [nvarchar](128) NOT NULL,
     CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED 
     (
         [ProductID] ASC
     )WITH (PAD_INDEX  = OFF
            , STATISTICS_NORECOMPUTE  = OFF
            , IGNORE_DUP_KEY = OFF
            ,     ALLOW_ROW_LOCKS  = ON
             , ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
      ) ON [PRIMARY]
    
    GO
    

    Let's populate the products table with some products. Execute the following code to insert some products:

    INSERT INTO Product
    SELECT 'Wii'
    UNION 
    SELECT 'PS3'
    UNION 
    SELECT 'XBOX360'
    

    If you execute SELECT * FROM Product you will probably see the following:

    ProductID   ProductDescription
    1           PS3
    2           Wii
    3           XBOX360
    

    OK, at this point you have both product and shop information. So how do you bring them together? Well we know we can identify the shop by its ShopID primary key column and we know we can identify a product by its ProductID primary key column. Also, since each shop has a different price for each product we need to store the price the shop charges for the product.

    So we have a table that maps the Shop to the product. We will call this table ShopProduct. A simple version of this table might look like this:

    CREATE TABLE [dbo].[ShopProduct](
    [ShopID] [int] NOT NULL,
    [ProductID] [int] NOT NULL,
    [Price] [money] NOT NULL,
    CONSTRAINT [PK_ShopProduct] PRIMARY KEY CLUSTERED 
     (
         [ShopID] ASC,
          [ProductID] ASC
     )WITH (PAD_INDEX  = OFF,
         STATISTICS_NORECOMPUTE  = OFF, 
         IGNORE_DUP_KEY = OFF, 
         ALLOW_ROW_LOCKS  = ON,
         ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
      ) ON [PRIMARY]
    
     GO
    

    So let's assume the American Games R Us shop only sells American consoles, the Europe Gaming Experience sells all consoles and the Asian Games Emporium sells only Asian consoles. We would need to map the primary keys from the shop and product tables into the ShopProduct table.

    Here is how we are going to do the mapping. In my example the American Games R Us has a ShopID value of 1 (this is the primary key value) and I can see that the XBOX360 has a value of 3 and the shop has listed the XBOX360 for $159.99

    By executing the following code you would complete the mapping:

    INSERT INTO ShopProduct VALUES(1,3,159.99)
    

    Now we want to add all product to the Europe Gaming Experience shop. In this example we know that the Europe Gaming Experience shop has a ShopID of 3 and since it sells all consoles we will need to insert the ProductID 1, 2 and 3 into the mapping table. Let's assume the prices for the consoles (products) at the Europe Gaming Experience shop are as follows: 1- The PS3 sells for $259.99 , 2- The Wii sells for $159.99 , 3- The XBOX360 sells for $199.99.

    To get this mapping done you would need to execute the following code:

    INSERT INTO ShopProduct VALUES(3,2,159.99) --This will insert the WII console into the mapping table for the Europe Gaming Experience Shop with a price of 159.99
    INSERT INTO ShopProduct VALUES(3,1,259.99) --This will insert the PS3 console into the mapping table for the Europe Gaming Experience Shop with a price of 259.99
    INSERT INTO ShopProduct VALUES(3,3,199.99) --This will insert the XBOX360 console into the mapping table for the Europe Gaming Experience Shop with a price of 199.99
    

    At this point you have mapped two shops and their products into the mapping table. OK, so now how do I bring this all together to show a user browsing the website? Let's say you want to show all the product for the European Gaming Experience to a user on a web page – you would need to execute the following query:

    SELECT      Shop.*
            , ShopProduct.*
            , Product.*
    FROM         Shop 
    INNER JOIN  ShopProduct ON Shop.ShopID = ShopProduct.ShopID 
    INNER JOIN  Product ON ShopProduct.ProductID = Product.ProductID
    WHERE       Shop.ShopID=3
    

    You will probably see the following results:

    ShopID     ShopName                 ShopID  ProductID   Price   ProductID   ProductDescription
    3          Europe Gaming Experience   3         1       259.99  1           PS3
    3          Europe Gaming Experience   3         2       159.99  2           Wii
    3          Europe Gaming Experience   3         3       199.99  3           XBOX360
    

    Now for one last example, let's assume that your website has a feature which finds the cheapest price for a console. A user asks to find the cheapest prices for XBOX360.

    You can execute the following query:

     SELECT     Shop.*
            , ShopProduct.*
            , Product.*
     FROM         Shop 
     INNER JOIN  ShopProduct ON Shop.ShopID = ShopProduct.ShopID 
     INNER JOIN  Product ON ShopProduct.ProductID = Product.ProductID
     WHERE      Product.ProductID =3  -- You can also use Product.ProductDescription = 'XBOX360'
     ORDER BY    Price ASC
    

    This query will return a list of all shops which sells the XBOX360 with the cheapest shop first and so on.

    You will notice that I have not added the Asian Games shop. As an exercise, add the Asian games shop to the mapping table with the following products: the Asian Games Emporium sells the Wii games console for $99.99 and the PS3 console for $159.99. If you work through this example you should now understand how to model a many-to-many relationship.

    I hope this helps you in your travels with database design.

    How to place a JButton at a desired location in a JFrame using Java

    Use child.setLocation(0, 0) on the button, and parent.setLayout(null). Instead of using setBounds(...) on the JFrame to size it, consider using just setSize(...) and letting the OS position the frame.

    //JPanel
    JPanel pnlButton = new JPanel();
    //Buttons
    JButton btnAddFlight = new JButton("Add Flight");
    
    public Control() {
    
        //JFrame layout
        this.setLayout(null);
    
        //JPanel layout
        pnlButton.setLayout(null);
    
        //Adding to JFrame
        pnlButton.add(btnAddFlight);
        add(pnlButton);
    
        // postioning
        pnlButton.setLocation(0,0);
    

    What is meant with "const" at end of function declaration?

    I always find it conceptually easier to think of that you are making the this pointer const (which is pretty much what it does).

    How can I select the first day of a month in SQL?

    ----Last Day of Previous Month
    SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
    LastDay_PreviousMonth
    ----Last Day of Current Month
    SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
    LastDay_CurrentMonth
    ----Last Day of Next Month
    SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
    LastDay_NextMonth
    

    stale element reference: element is not attached to the page document

    In my case, I had a page where it was an input type='date' whose reference I had got on page load, but When I tried to interact with it, it showed this exception and that was quite meaningful as Javascript had manipulated my control hence it was detached from the document and I had to re-get its reference after the javascript had performed its job with the control. So, this is how my code looked before the exception:

    if (elemDate != null)
    { 
        elemDate.Clear(); 
        elemDate.SendKeys(model.Age);
    }
    

    Code after the exception was raised:

    int tries = 0;
    do
    {
        try
        {
            tries++;
            if (elemDate != null)
            {
                // these lines were causing the exception so I had break after these are successfully executed because if they are executed that means the control was found and attached to the document and we have taken the reference of it again.
                elemDate.Clear();
                elemDate.SendKeys(model.Age);
                break;
            }
        }
        catch (StaleElementReferenceException)
        {
            System.Threading.Thread.Sleep(10); // put minor fake delay so Javascript on page does its actions with controls
            elemDate = driver.FindElement(By.Id(dateId));
        }
    } while (tries < 3); // Try it three times.
    

    So, Now you can perform further actions with your code or you can quit the driver if it was unsuccessful in getting the control to work.

    if(tries > 2)
    {
       // element was not found, find out what is causing the control detachment.
       // driver.Quit();
       return;
    }
    
    // Hurray!! Control was attached and actions were performed.
    // Do something with it...
    

    Something that I have learnt so far is, catching exceptions to know about successful code execution is not a good idea, But, I had to do it and I found this work-around to be working well in this case.

    PS: After writing all this, I just noticed the tags that this thread was for java. This code sample is just for demonstration purpose, It might help people who have issue in C# language. Or it can be easily translated to java as it doesn't have much C# specific code.

    Tracking changes in Windows registry

    There is a python-hids called sobek ( http://code.google.com/p/sobek-hids/ ) that is able to monitor some parts of the SO. It's working fine for my for monitoring file changes, and although the doc sais that it's able to monitor registry changes it does not work for me.

    Good piece of software for easily deplay a python based hids.

    Add a duration to a moment (moment.js)

    For people having a startTime (like 12h:30:30) and a duration (value in minutes like 120), you can guess the endTime like so:

    const startTime = '12:30:00';
    const durationInMinutes = '120';
    
    const endTime = moment(startTime, 'HH:mm:ss').add(durationInMinutes, 'minutes').format('HH:mm');
    
    // endTime is equal to "14:30"
    

    Mean per group in a data.frame

    You can also accomplish this using the sqldf package as shown below:

    library(sqldf)
    
    x <- read.table(text='Name     Month  Rate1     Rate2
    Aira       1      12        23
                    Aira       2      18        73
                    Aira       3      19        45
                    Ben        1      53        19
                    Ben        2      22        87
                    Ben        3      19        45
                    Cat        1      22        87
                    Cat        2      67        43
                    Cat        3      45        32', header=TRUE)
    
    sqldf("
    select 
      Name
      ,avg(Rate1) as Rate1_float
      ,avg(Rate2) as Rate2_float
      ,avg(Rate1) as Rate1
      ,avg(Rate2) as Rate2
    from x
    group by 
      Name
    ")
    
    #  Name Rate1_float Rate2_float Rate1 Rate2
    #1 Aira    16.33333    47.00000    16    47
    #2  Ben    31.33333    50.33333    31    50
    #3  Cat    44.66667    54.00000    44    54
    

    I am a recent convert to dplyr as shown in other answers, but sqldf is nice as most data analysts/data scientists/developers have at least some fluency in SQL. In this way, I think it tends to make for more universally readable code than dplyr or other solutions presented above.

    UPDATE: In responding to the comment below, I attempted to update the code as shown above. However, the behavior was not as I expected. It seems that the column definition (i.e. int vs float) is only carried through when the column alias matches the original column name. When you specify a new name, the aggregate column is returned without rounding.

    Copy a git repo without history

    You can limit the depth of the history while cloning:

    --depth <depth>
    Create a shallow clone with a history truncated to the specified 
    number of revisions.
    

    Use this if you want limited history, but still some.

    Click through div to underlying elements

    Yes, you CAN do this.

    Using pointer-events: none along with CSS conditional statements for IE11 (does not work in IE10 or below), you can get a cross browser compatible solution for this problem.

    Using AlphaImageLoader, you can even put transparent .PNG/.GIFs in the overlay div and have clicks flow through to elements underneath.

    CSS:

    pointer-events: none;
    background: url('your_transparent.png');
    

    IE11 conditional:

    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='your_transparent.png', sizingMethod='scale');
    background: none !important;
    

    Here is a basic example page with all the code.

    Export query result to .csv file in SQL Server 2008

    One more method worth to mention here:

    SQLCMD -S SEVERNAME -E -Q "SELECT COLUMN FROM TABLE" -s "," -o "c:\test.csv"
    

    NOTE: I don't see any network admin let you run powershell scripts

    PHP: if !empty & empty

    Here's a compact way to do something different in all four cases:

    if(empty($youtube)) {
        if(empty($link)) {
            # both empty
        } else {
            # only $youtube not empty
        }
    } else {
        if(empty($link)) {
            # only $link empty
        } else {
            # both not empty
        }
    }
    

    If you want to use an expression instead, you can use ?: instead:

    echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
                         : ( empty($link) ? 'only $link empty' : 'both not empty' );
    

    How to efficiently build a tree from a flat structure?

    Most of the answers assume you are looking to do this outside of the database. If your trees are relatively static in nature and you just need to somehow map the trees into the database, you may want to consider using nested set representations on the database side. Check out books by Joe Celko (or here for an overview by Celko).

    If tied to Oracle dbs anyway, check out their CONNECT BY for straight SQL approaches.

    With either approach, you could completely skip mapping the trees before you load the data up in the database. Just thought I would offer this up as an alternative, it may be completely inappropriate for your specific needs. The whole "proper order" part of the original question somewhat implies you need the order to be "correct" in the db for some reason? This might push me towards handling the trees there as well.

    Transfer data between iOS and Android via Bluetooth?

    This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.

    Some possible alternatives:

    1. Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
    2. Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
    3. Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
    4. Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)

    Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.

    Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.

    What is 'Context' on Android?

    Context means component (or application) in various time-period. If I do eat so much food between 1 to 2 pm then my context of that time is used to access all methods (or resources) that I use during that time. Content is a component (application) for a particular time. The Context of components of the application keeps changing based on the underlying lifecycle of the components or application. For instance, inside the onCreate() of an Activity,

    getBaseContext() -- gives the context of the Activity that is set (created) by the constructor of activity. getApplicationContext() -- gives the Context setup (created) during the creation of application.

    Note: <application> holds all Android Components.

    <application>
        <activity> .. </activity> 
    
        <service>  .. </service>
    
        <receiver> .. </receiver>
    
        <provider> .. </provider>
    </application> 
    

    It means, when you call getApplicationContext() from inside whatever component, you are calling the common context of the whole application.

    Context keeps being modified by the system based on the lifecycle of components.

    How do you make websites with Java?

    I'd suggest OOWeb to act as an HTTP server and a templating engine like Velocity to generate HTML. I also second Esko's suggestion of Wicket. Both solutions are considerably simpler than the average setup.

    How to extract filename.tar.gz file

    If file filename.tar.gz gives this message: POSIX tar archive, the archive is a tar, not a GZip archive.

    Unpack a tar without the z, it is for gzipped (compressed), only:

    mv filename.tar.gz filename.tar # optional
    tar xvf filename.tar
    

    Or try a generic Unpacker like unp (https://packages.qa.debian.org/u/unp.html), a script for unpacking a wide variety of archive formats.

    determine the file type:

    $ file ~/Downloads/filename.tbz2
    /User/Name/Downloads/filename.tbz2: bzip2 compressed data, block size = 400k
    

    Getting an Embedded YouTube Video to Auto Play and Loop

    All of the answers didn't work for me, I checked the playlist URL and seen that playlist parameter changed to list! So it should be:

    &loop=1&list=PLvNxGp1V1dOwpDBl7L3AJIlkKYdNDKUEs

    So here is the full code I use make a clean, looping, autoplay video:

    <iframe width="100%" height="425" src="https://www.youtube.com/embed/MavEpJETfgI?autoplay=1&showinfo=0&loop=1&list=PLvNxGp1V1dOwpDBl7L3AJIlkKYdNDKUEs&rel=0" frameborder="0" allowfullscreen></iframe>
    

    how to implement login auth in node.js

    @alessioalex answer is a perfect demo for fresh node user. But anyway, it's hard to write checkAuth middleware into all routes except login, so it's better to move the checkAuth from every route to one entry with app.use. For example:

    function checkAuth(req, res, next) {
      // if logined or it's login request, then go next route
      if (isLogin || (req.path === '/login' && req.method === 'POST')) {
        next()
      } else {
        res.send('Not logged in yet.')
      }
    }
    
    app.use('/', checkAuth)
    

    How to detect page zoom level in all modern browsers?

    You can try

    var browserZoomLevel = Math.round(window.devicePixelRatio * 100);
    

    This will give you browser zoom percentage level on non-retina displays. For high DPI/retina displays, it would yield different values (e.g., 200 for Chrome and Safari, 140 for Firefox).

    To catch zoom event you can use

    $(window).resize(function() { 
    // your code 
    });
    

    Java 32-bit vs 64-bit compatibility

    yo where wrong! To this theme i wrote an question to oracle. The answer was.

    "If you compile your code on an 32 Bit Machine, your code should only run on an 32 Bit Processor. If you want to run your code on an 64 Bit JVM you have to compile your class Files on an 64 Bit Machine using an 64-Bit JDK."