Programs & Examples On #Windows live messenger

AngularJS directive does not update on scope variable changes

We can try this

$scope.$apply(function() {
    $scope.step1 = true;
    //scope.list2.length = 0;
});

http://jsfiddle.net/Etb9d/

Difference between Activity and FragmentActivity

FragmentActivity is part of the support library, while Activity is the framework's default class. They are functionally equivalent.

You should always use FragmentActivity and android.support.v4.app.Fragment instead of the platform default Activity and android.app.Fragment classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.

Seeding the random number generator in Javascript

Antti Sykäri's algorithm is nice and short. I initially made a variation that replaced JavaScript's Math.random when you call Math.seed(s), but then Jason commented that returning the function would be better:

Math.seed = function(s) {
    return function() {
        s = Math.sin(s) * 10000; return s - Math.floor(s);
    };
};

// usage:
var random1 = Math.seed(42);
var random2 = Math.seed(random1());
Math.random = Math.seed(random2());

This gives you another functionality that JavaScript doesn't have: multiple independent random generators. That is especially important if you want to have multiple repeatable simulations running at the same time.

Chart.js v2 hide dataset labels

add:

Chart.defaults.global.legend.display = false;

in the starting of your script code;

Redirect to specified URL on PHP script completion?

Note that this will not work:

header('Location: $url');

You need to do this (for variable expansion):

header("Location: $url");

How can I close a dropdown on click outside?

I've done it this way.

Added an event listener on document click and in that handler checked if my container contains event.target, if not - hide the dropdown.

It would look like this.

@Component({})
class SomeComponent {
    @ViewChild('container') container;
    @ViewChild('dropdown') dropdown;

    constructor() {
        document.addEventListener('click', this.offClickHandler.bind(this)); // bind on doc
    }

    offClickHandler(event:any) {
        if (!this.container.nativeElement.contains(event.target)) { // check click origin
            this.dropdown.nativeElement.style.display = "none";
        }
    }
}

How to get an array of unique values from an array containing duplicates in JavaScript?

Those of you who work with google closure library, have at their disposal goog.array.removeDuplicates, which is the same as unique. It changes the array itself, though.

Creating threads - Task.Factory.StartNew vs new Thread()

There is a big difference. Tasks are scheduled on the ThreadPool and could even be executed synchronous if appropiate.

If you have a long running background work you should specify this by using the correct Task Option.

You should prefer Task Parallel Library over explicit thread handling, as it is more optimized. Also you have more features like Continuation.

Converting between strings and ArrayBuffers

  stringToArrayBuffer(byteString) {
    var byteArray = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
      byteArray[i] = byteString.codePointAt(i);
    }
    return byteArray;
  }
  arrayBufferToString(buffer) {
    var byteArray = new Uint8Array(buffer);
    var byteString = '';
    for (var i = 0; i < byteArray.byteLength; i++) {
      byteString += String.fromCodePoint(byteArray[i]);
    }
    return byteString;
  }

Convert timestamp long to normal date format

I tried this and worked for me.

Date = (long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds

PHP MySQL Query Where x = $variable

$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];

How to convert Java String into byte[]?

  String example = "Convert Java String";
  byte[] bytes = example.getBytes();

Jquery change <p> text programmatically

It seems you have the click event wrapped around a custom event name "pageinit", are you sure you're triggered the event before you click the button?

something like this:

$("#gender").trigger("pageinit");

Compute row average in pandas

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

'Access denied for user 'root'@'localhost' (using password: NO)'

Another solution if someone gets the error The specified password for user account ‘root’ is not valid, or failed to connect to the database server also with the right password, is the follow

•In the Windows registry, delete the mysql_pwd reg key under HKCU\Software\Microsoft\WebPlatformInstaller

•Unistall older version of MySQL .NET connector

•Download and install the latest MySql .NET Connector.

What's the difference between an id and a class?

Any element can have a class or an id.

A class is used to reference a certain type of display, for example you may have a css class for a div that represents the answer to this question. As there will be many answers, multiple divs would need the same styling and you would use a class.

An id refers to only a single element, for example the related section at the right may have styling specific to it not reused elsewhere, it would use an id.

Technically you can use classes for all of it, or split them up logically. You can not, however, reuse id's for multiple elements.

Hide all elements with class using plain Javascript

Late answer, but I found out that this is the simplest solution (if you don't use jQuery):

var myClasses = document.querySelectorAll('.my-class'),
    i = 0,
    l = myClasses.length;

for (i; i < l; i++) {
    myClasses[i].style.display = 'none';
}

Demo

A Windows equivalent of the Unix tail command

If you use PowerShell then this works:

Get-Content filenamehere -Wait -Tail 30

Posting Stefan's comment from below, so people don't miss it

PowerShell 3 introduces a -Tail parameter to include only the last x lines

Raise an event whenever a property's value changed?

The INotifyPropertyChanged interface is implemented with events. The interface has just one member, PropertyChanged, which is an event that consumers can subscribe to.

The version that Richard posted is not safe. Here is how to safely implement this interface:

public class MyClass : INotifyPropertyChanged
{
    private string imageFullPath;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, e);
    }

    protected void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    public string ImageFullPath
    {
        get { return imageFullPath; }
        set
        {
            if (value != imageFullPath)
            {
                imageFullPath = value;
                OnPropertyChanged("ImageFullPath");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Note that this does the following things:

  • Abstracts the property-change notification methods so you can easily apply this to other properties;

  • Makes a copy of the PropertyChanged delegate before attempting to invoke it (failing to do this will create a race condition).

  • Correctly implements the INotifyPropertyChanged interface.

If you want to additionally create a notification for a specific property being changed, you can add the following code:

protected void OnImageFullPathChanged(EventArgs e)
{
    EventHandler handler = ImageFullPathChanged;
    if (handler != null)
        handler(this, e);
}

public event EventHandler ImageFullPathChanged;

Then add the line OnImageFullPathChanged(EventArgs.Empty) after the line OnPropertyChanged("ImageFullPath").

Since we have .Net 4.5 there exists the CallerMemberAttribute, which allows to get rid of the hard-coded string for the property name in the source code:

    protected void OnPropertyChanged(
        [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    public string ImageFullPath
    {
        get { return imageFullPath; }
        set
        {
            if (value != imageFullPath)
            {
                imageFullPath = value;
                OnPropertyChanged();
            }
        }
    }

How can I require at least one checkbox be checked before a form can be submitted?

Here's an example using jquery and your html.

<html>
<head>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
$(document).ready(function () {
    $('#checkBtn').click(function() {
      checked = $("input[type=checkbox]:checked").length;

      if(!checked) {
        alert("You must check at least one checkbox.");
        return false;
      }

    });
});

</script>

<p>Box Set 1</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 1" required><label>Box 1</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 2" required><label>Box 2</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 3" required><label>Box 3</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 4" required><label>Box 4</label></li>
</ul>
<p>Box Set 2</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 5" required><label>Box 5</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 6" required><label>Box 6</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 7" required><label>Box 7</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 8" required><label>Box 8</label></li>
</ul>
<p>Box Set 3</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 9" required><label>Box 9</label></li>
</ul>
<p>Box Set 4</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 10" required><label>Box 10</label></li>
</ul>

<input type="button" value="Test Required" id="checkBtn">

</body>
</html>

MetadataException when using Entity Framework Entity Connection

I had this problem when moving my .edmx database first model from one project to another.

I simply did the following:

  1. Deleted the connection strings in the app.config or web.config
  2. Deleted the 'Model.edmx'
  3. Re-added the model to the project.

Reading a string with spaces with sscanf

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);

How to check if an alert exists using WebDriver?

public boolean isAlertPresent() 
{ 
    try 
    { 
        driver.switchTo().alert(); 
        return true; 
    }   // try 
    catch (NoAlertPresentException Ex) 
    { 
        return false; 
    }   // catch 
}   // isAlertPresent()

check the link here https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY

How to set timeout for a line of c# code

I use something like this (you should add code to deal with the various fails):

    var response = RunTaskWithTimeout<ReturnType>(
        (Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);


    /// <summary>
    /// Generic method to run a task on a background thread with a specific timeout, if the task fails,
    /// notifies a user
    /// </summary>
    /// <typeparam name="T">Return type of function</typeparam>
    /// <param name="TaskAction">Function delegate for task to perform</param>
    /// <param name="TimeoutSeconds">Time to allow before task times out</param>
    /// <returns></returns>
    private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
    {
        Task<T> backgroundTask;

        try
        {
            backgroundTask = Task.Factory.StartNew(TaskAction);
            backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
        }
        catch (AggregateException ex)
        {
            // task failed
            var failMessage = ex.Flatten().InnerException.Message);
            return default(T);
        }
        catch (Exception ex)
        {
            // task failed
            var failMessage = ex.Message;
            return default(T);
        }

        if (!backgroundTask.IsCompleted)
        {
            // task timed out
            return default(T);
        }

        // task succeeded
        return backgroundTask.Result;
    }

Changing width property of a :before css selector using JQuery

One option is to use an attribute on the image, and modify that using jQuery. Then take that value in CSS:

HTML (note I'm assuming .cloumn is a div but it could be anything):

<div class="column" bf-width=100 >
    <img src="..." />
</div>

jQuery:

// General use:
$('.column').attr('bf-width', 100);
// With your image, along the lines of:
$('.column').attr('bf-width', $('img').width());

And then in order to use that value in CSS:

.column:before {
    content: attr(data-content) 'px';
    /* ... */
}

This will grab the attribute value from .column, and apply it on the before.

Sources: CSS attr (note the examples with before), jQuery attr.

Uploading Laravel Project onto Web Server

Had this problem too and found out that the easiest way is to point your domain to the public folder and leave everything else the way they are.

PLEASE ENSURE TO USE THE RIGHT VERSION OF PHP. Save yourself some stress :)

Google Maps: How to create a custom InfoWindow?

I found InfoBox perfect for advanced styling.

An InfoBox behaves like a google.maps.InfoWindow, but it supports several additional properties for advanced styling. An InfoBox can also be used as a map label. An InfoBox also fires the same events as a google.maps.InfoWindow.

Include http://code.google.com/p/google-maps-utility-library-v3/source/browse/trunk/infobox/src/infobox.js in your page

Responsive css styles on mobile devices ONLY

Yes, this can be done via javascript feature detection ( or browser detection , e.g. Modernizr ) . Then, use yepnope.js to load required resources ( JS and/or CSS )

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

How do I pick randomly from an array?

Just use Array#sample:

[:foo, :bar].sample # => :foo, or :bar :-)

It is available in Ruby 1.9.1+. To be also able to use it with an earlier version of Ruby, you could require "backports/1.9.1/array/sample".

Note that in Ruby 1.8.7 it exists under the unfortunate name choice; it was renamed in later version so you shouldn't use that.

Although not useful in this case, sample accepts a number argument in case you want a number of distinct samples.

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

Difference between private, public, and protected inheritance

It's essentially the access protection of the public and protected members of the base class in the derived class. With public inheritance, the derived class can see public and protected members of the base. With private inheritance, it can't. With protected, the derived class and any classes derived from that can see them.

Android button font size

You define these attributes in xml as you would anything else, for example:

<Button android:id="@+id/next_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/next"
            android:background="@drawable/mybutton_background"
            android:textSize="10sp" /> <!-- Use SP(Scale Independent Pixel) -->

You can find the allowed attributes in the api.

Or, if you want this to apply to all buttons in your application, create a style. See the Styles and Themes development documentation.

In Python, how to display current time in readable format

You could do something like:

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
'Thu, 28 Jun 2001 14:17:15 +0000'

The full doc on the % codes are at http://docs.python.org/library/time.html

How to make a class JSON serializable

Here is my 3 cents ...
This demonstrates explicit json serialization for a tree-like python object.
Note: If you actually wanted some code like this you could use the twisted FilePath class.

import json, sys, os

class File:
    def __init__(self, path):
        self.path = path

    def isdir(self):
        return os.path.isdir(self.path)

    def isfile(self):
        return os.path.isfile(self.path)

    def children(self):        
        return [File(os.path.join(self.path, f)) 
                for f in os.listdir(self.path)]

    def getsize(self):        
        return os.path.getsize(self.path)

    def getModificationTime(self):
        return os.path.getmtime(self.path)

def _default(o):
    d = {}
    d['path'] = o.path
    d['isFile'] = o.isfile()
    d['isDir'] = o.isdir()
    d['mtime'] = int(o.getModificationTime())
    d['size'] = o.getsize() if o.isfile() else 0
    if o.isdir(): d['children'] = o.children()
    return d

folder = os.path.abspath('.')
json.dump(File(folder), sys.stdout, default=_default)

How do I test a single file using Jest?

"test": "jest api/ds_server/ds_server.test.js"

How to generate a git patch for a specific commit?

For generating the patches from the topmost commits from a specific sha1 hash:

git format-patch -<n> <SHA1>

The last 10 patches from head in a single patch file:

git format-patch -10 HEAD --stdout > 0001-last-10-commits.patch

Spring Boot - Handle to Hibernate SessionFactory

The simplest and least verbose way to autowire your Hibernate SessionFactory is:

This is the solution for Spring Boot 1.x with Hibernate 4:

application.properties:

spring.jpa.properties.hibernate.current_session_context_class=
org.springframework.orm.hibernate4.SpringSessionContext

Configuration class:

@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
    return new HibernateJpaSessionFactoryBean();
}

Then you can autowire the SessionFactory in your services as usual:

@Autowired
private SessionFactory sessionFactory;

As of Spring Boot 1.5 with Hibernate 5, this is now the preferred way:

application.properties:

spring.jpa.properties.hibernate.current_session_context_class=
org.springframework.orm.hibernate5.SpringSessionContext

Configuration class:

@EnableAutoConfiguration
...
...
@Bean
public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
    HibernateJpaSessionFactoryBean fact = new HibernateJpaSessionFactoryBean();
    fact.setEntityManagerFactory(emf);
    return fact;
}

Using GPU from a docker container?

Updated for cuda-8.0 on ubuntu 16.04

Dockerfile

FROM ubuntu:16.04
MAINTAINER Jonathan Kosgei <[email protected]>

# A docker container with the Nvidia kernel module and CUDA drivers installed

ENV CUDA_RUN https://developer.nvidia.com/compute/cuda/8.0/prod/local_installers/cuda_8.0.44_linux-run

RUN apt-get update && apt-get install -q -y \
  wget \
  module-init-tools \
  build-essential 

RUN cd /opt && \
  wget $CUDA_RUN && \
  chmod +x cuda_8.0.44_linux-run && \
  mkdir nvidia_installers && \
  ./cuda_8.0.44_linux-run -extract=`pwd`/nvidia_installers && \
  cd nvidia_installers && \
  ./NVIDIA-Linux-x86_64-367.48.run -s -N --no-kernel-module

RUN cd /opt/nvidia_installers && \
  ./cuda-linux64-rel-8.0.44-21122537.run -noprompt

# Ensure the CUDA libs and binaries are in the correct environment variables
ENV LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-8.0/lib64
ENV PATH=$PATH:/usr/local/cuda-8.0/bin

RUN cd /opt/nvidia_installers &&\
    ./cuda-samples-linux-8.0.44-21122537.run -noprompt -cudaprefix=/usr/local/cuda-8.0 &&\
    cd /usr/local/cuda/samples/1_Utilities/deviceQuery &&\ 
    make

WORKDIR /usr/local/cuda/samples/1_Utilities/deviceQuery
  1. Run your container

sudo docker run -ti --device /dev/nvidia0:/dev/nvidia0 --device /dev/nvidiactl:/dev/nvidiactl --device /dev/nvidia-uvm:/dev/nvidia-uvm <built-image> ./deviceQuery

You should see output similar to:

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 8.0, CUDA Runtime Version = 8.0, NumDevs = 1, Device0 = GRID K520 Result = PASS

Spark : how to run spark file from spark shell

You can use either sbt or maven to compile spark programs. Simply add the spark as dependency to maven

<repository>
      <id>Spark repository</id>
      <url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
</repository>

And then the dependency:

<dependency>
      <groupId>spark</groupId>
      <artifactId>spark</artifactId>
      <version>1.2.0</version>
</dependency>

In terms of running a file with spark commands: you can simply do this:

echo"
   import org.apache.spark.sql.*
   ssc = new SQLContext(sc)
   ssc.sql("select * from mytable").collect
" > spark.input

Now run the commands script:

cat spark.input | spark-shell

How do I read / convert an InputStream into a String in Java?

I have written a class that does just that, so I figured I'd share it with everyone. Sometimes you don't want to add Apache Commons just for one thing, and want something dumber than Scanner that doesn't examine the content.

Usage is as follows

// Read from InputStream
String data = new ReaderSink(inputStream, Charset.forName("UTF-8")).drain();

// Read from File
data = new ReaderSink(file, Charset.forName("UTF-8")).drain();

// Drain input stream to console
new ReaderSink(inputStream, Charset.forName("UTF-8")).drainTo(System.out);

Here is the code for ReaderSink:

import java.io.*;
import java.nio.charset.Charset;

/**
 * A simple sink class that drains a {@link Reader} to a {@link String} or
 * to a {@link Writer}.
 *
 * @author Ben Barkay
 * @version 2/20/2014
 */
public class ReaderSink {
    /**
     * The default buffer size to use if no buffer size was specified.
     */
    public static final int DEFAULT_BUFFER_SIZE = 1024;

    /**
     * The {@link Reader} that will be drained.
     */
    private final Reader in;

    /**
     * Constructs a new {@code ReaderSink} for the specified file and charset.
     * @param file      The file to read from.
     * @param charset   The charset to use.
     * @throws FileNotFoundException    If the file was not found on the filesystem.
     */
    public ReaderSink(File file, Charset charset) throws FileNotFoundException {
        this(new FileInputStream(file), charset);
    }

    /**
     * Constructs a new {@code ReaderSink} for the specified {@link InputStream}.
     * @param in        The {@link InputStream} to drain.
     * @param charset   The charset to use.
     */
    public ReaderSink(InputStream in, Charset charset) {
        this(new InputStreamReader(in, charset));
    }

    /**
     * Constructs a new {@code ReaderSink} for the specified {@link Reader}.
     * @param in    The reader to drain.
     */
    public ReaderSink(Reader in) {
        this.in = in;
    }

    /**
     * Drains the data from the underlying {@link Reader}, returning a {@link String} containing
     * all of the read information. This method will use {@link #DEFAULT_BUFFER_SIZE} for
     * its buffer size.
     * @return  A {@link String} containing all of the information that was read.
     */
    public String drain() throws IOException {
        return drain(DEFAULT_BUFFER_SIZE);
    }

    /**
     * Drains the data from the underlying {@link Reader}, returning a {@link String} containing
     * all of the read information.
     * @param bufferSize    The size of the buffer to use when reading.
     * @return  A {@link String} containing all of the information that was read.
     */
    public String drain(int bufferSize) throws IOException {
        StringWriter stringWriter = new StringWriter();
        drainTo(stringWriter, bufferSize);
        return stringWriter.toString();
    }

    /**
     * Drains the data from the underlying {@link Reader}, writing it to the
     * specified {@link Writer}. This method will use {@link #DEFAULT_BUFFER_SIZE} for
     * its buffer size.
     * @param out   The {@link Writer} to write to.
     */
    public void drainTo(Writer out) throws IOException {
        drainTo(out, DEFAULT_BUFFER_SIZE);
    }

    /**
     * Drains the data from the underlying {@link Reader}, writing it to the
     * specified {@link Writer}.
     * @param out           The {@link Writer} to write to.
     * @param bufferSize    The size of the buffer to use when reader.
     */
    public void drainTo(Writer out, int bufferSize) throws IOException {
        char[] buffer = new char[bufferSize];
        int read;
        while ((read = in.read(buffer)) > -1) {
            out.write(buffer, 0, read);
        }
    }
}

How to get 2 digit year w/ Javascript?

another version:

var yy = (new Date().getFullYear()+'').slice(-2);

How to get raw text from pdf file using java

You can use iText for do such things

//iText imports

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

for example:

try {     
    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages(); 
    String str=PdfTextExtractor.getTextFromPage(reader, 2); //Extracting the content from a particular page.
    System.out.println(str);
    reader.close();
} catch (Exception e) {
    System.out.println(e);
}

another one

try {

    PdfReader reader = new PdfReader("c:/temp/test.pdf");
    System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
    String page = PdfTextExtractor.getTextFromPage(reader, 2);
    System.out.println("Page Content:\n\n"+page+"\n\n");
    System.out.println("Is this document tampered: "+reader.isTampered());
    System.out.println("Is this document encrypted: "+reader.isEncrypted());
} catch (IOException e) {
    e.printStackTrace();
}

the above examples can only extract the text, but you need to do some more to remove hyperlinks, bullets, heading & numbers.

in_array multiple values

if(in_array('foo',$arg) && in_array('bar',$arg)){
    //both of them are in $arg
}

if(in_array('foo',$arg) || in_array('bar',$arg)){
    //at least one of them are in $arg
}

Reload a DIV without reloading the whole page

try this

<script type="text/javascript">
window.onload = function(){


var auto_refresh = setInterval(
function ()
{
$('.View').html('');
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds

}
</script>

split string in two on given index and return both parts

function splitText(value, index) {
  if (value.length < index) {return value;} 
  return [value.substring(0, index)].concat(splitText(value.substring(index), index));
}
console.log(splitText('this is a testing peace of text',10));
// ["this is a ", "testing pe", "ace of tex", "t"] 

For those who want to split a text into array using the index.

Combining two Series into a DataFrame in pandas

I used pandas to convert my numpy array or iseries to an dataframe then added and additional the additional column by key as 'prediction'. If you need dataframe converted back to a list then use values.tolist()

output=pd.DataFrame(X_test)
output['prediction']=y_pred

list=output.values.tolist()     

Difference between Big-O and Little-O Notation

In general

Asymptotic notation is something you can understand as: how do functions compare when zooming out? (A good way to test this is simply to use a tool like Desmos and play with your mouse wheel). In particular:

  • f(n) ? o(n) means: at some point, the more you zoom out, the more f(n) will be dominated by n (it will progressively diverge from it).
  • g(n) ? T(n) means: at some point, zooming out will not change how g(n) compare to n (if we remove ticks from the axis you couldn't tell the zoom level).

Finally h(n) ? O(n) means that function h can be in either of these two categories. It can either look a lot like n or it could be smaller and smaller than n when n increases. Basically, both f(n) and g(n) are also in O(n).

In computer science

In computer science, people will usually prove that a given algorithm admits both an upper O and a lower bound . When both bounds meet that means that we found an asymptotically optimal algorithm to solve that particular problem.

For example, if we prove that the complexity of an algorithm is both in O(n) and (n) it implies that its complexity is in T(n). That's the definition of T and it more or less translates to "asymptotically equal". Which also means that no algorithm can solve the given problem in o(n). Again, roughly saying "this problem can't be solved in less than n steps".

An upper bound of O(n) simply means that even in the worse case, the algorithm will terminate in at most n steps (ignoring all constant factors, both multiplicative and additive). A lower bound of (n) means on the opposite that we built some examples where the problem solved by this algorithm couldn't be solved in less than n steps (again ignoring multiplicative and additive constants). The number of steps is at most n and at least n so this problem complexity is "exactly n". Instead of saying "ignoring constant multiplicative/additive factor" every time we just write T(n) for short.

Are there any free Xml Diff/Merge tools available?

There are a few Java-based XML diff and merge tools listed here:

Open Source XML Diff written in Java

Added links:

git replacing LF with CRLF

Most of tools in Windows accepts only LF in text files. For example you can control the behaviour for Visual Studio in a file named '.editorconfig' with following example content (part):

 indent_style = space
 indent_size = 2
 end_of_line = lf    <<====
 charset = utf-8

Only the original Windows-Notepad does not work with LF but there are some more proper simple editor tools available!

Hence You should use LF in text files in Windows too. This is my message, stronlgy recommended! There is no reason to use CRLF in windows!

(The same discussion is using \ in include paths in C/++, it is bullshit, use #include <pathTo/myheader.h> with slash!, It is the C/++ standard and all microsoft compilers support it).

Hence the proper setting for git is

git config core.autocrlf false

My message: Forget such old thinking programs as dos2unix and unix2dos. Clarify in your team that LF is proper to use under Windows.

Multi-dimensional associative arrays in JavaScript

_x000D_
_x000D_
<script language="javascript">_x000D_
_x000D_
// Set values to variable_x000D_
var sectionName = "TestSection";_x000D_
var fileMap = "fileMapData";_x000D_
var fileId = "foobar";_x000D_
var fileValue= "foobar.png";_x000D_
var fileId2 = "barfoo";_x000D_
var fileValue2= "barfoo.jpg";_x000D_
_x000D_
// Create top-level image object_x000D_
var images = {};_x000D_
_x000D_
// Create second-level object in images object with_x000D_
// the name of sectionName value_x000D_
images[sectionName] = {};_x000D_
_x000D_
// Create a third level object_x000D_
var fileMapObj = {};_x000D_
_x000D_
// Add the third level object to the second level object_x000D_
images[sectionName][fileMap] = fileMapObj;_x000D_
_x000D_
// Add forth level associate array key and value data_x000D_
images[sectionName][fileMap][fileId] = fileValue;_x000D_
images[sectionName][fileMap][fileId2] = fileValue2;_x000D_
_x000D_
_x000D_
// All variables_x000D_
alert ("Example 1 Value: " + images[sectionName][fileMap][fileId]);_x000D_
_x000D_
// All keys with dots_x000D_
alert ("Example 2 Value: " + images.TestSection.fileMapData.foobar);_x000D_
_x000D_
// Mixed with a different final key_x000D_
alert ("Example 3 Value: " + images[sectionName]['fileMapData'][fileId2]);_x000D_
_x000D_
// Mixed brackets and dots..._x000D_
alert ("Example 4 Value: " + images[sectionName]['fileMapData'].barfoo);_x000D_
_x000D_
// This will FAIL! variable names must be in brackets!_x000D_
alert ("Example 5 Value: " + images[sectionName]['fileMapData'].fileId2);_x000D_
// Produces: "Example 5 Value: undefined"._x000D_
_x000D_
// This will NOT work either. Values must be quoted in brackets._x000D_
alert ("Example 6 Value: " + images[sectionName][fileMapData].barfoo);_x000D_
// Throws and exception and stops execution with error: fileMapData is not defined_x000D_
_x000D_
// We never get here because of the uncaught exception above..._x000D_
alert ("The End!");_x000D_
</script>
_x000D_
_x000D_
_x000D_

When to use SELECT ... FOR UPDATE?

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

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


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

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

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

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

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

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

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

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

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

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

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

SQL Server: SELECT only the rows with MAX(DATE)

The best way is Mikael Eriksson, if ROW_NUMBER() is available to you.

The next best is to join on a query, as per Cularis' answer.

Alternatively, the most simple and straight forward way is a correlated-sub-query in the WHERE clause.

SELECT
  *
FROM
  yourTable AS [data]
WHERE
  DateEntered = (SELECT MAX(DateEntered) FROM yourTable WHERE orderNo = [data].orderNo)

Or...

WHERE
  ID = (SELECT TOP 1 ID FROM yourTable WHERE orderNo = [data].orderNo ORDER BY DateEntered DESC)

How to print the value of a Tensor object in TensorFlow?

In Tensorflow 2.0+ (or in Eager mode environment) you can call .numpy() method:

import tensorflow as tf

matrix1 = tf.constant([[3., 3.0]])
matrix2 = tf.constant([[2.0],[2.0]])
product = tf.matmul(matrix1, matrix2)

print(product.numpy()) 

Flatten nested dictionaries, compressing keys

How about a functional and performant solution in Python3.5?

from functools import reduce


def _reducer(items, key, val, pref):
    if isinstance(val, dict):
        return {**items, **flatten(val, pref + key)}
    else:
        return {**items, pref + key: val}

def flatten(d, pref=''):
    return(reduce(
        lambda new_d, kv: _reducer(new_d, *kv, pref), 
        d.items(), 
        {}
    ))

This is even more performant:

def flatten(d, pref=''):
    return(reduce(
        lambda new_d, kv: \
            isinstance(kv[1], dict) and \
            {**new_d, **flatten(kv[1], pref + kv[0])} or \
            {**new_d, pref + kv[0]: kv[1]}, 
        d.items(), 
        {}
    ))

In use:

my_obj = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y': 10}}, 'd': [1, 2, 3]}

print(flatten(my_obj)) 
# {'d': [1, 2, 3], 'cby': 10, 'cbx': 5, 'ca': 2, 'a': 1}

Get all parameters from JSP page

The fastest way should be:

<%@ page import="java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
    if (entry.getKey().startsWith("question")) {
        String[] values = entry.getValue();
        // etc.

Note that you can't do:

for (Map.Entry<String, String[]> entry : 
     request.getParameterMap().entrySet()) { // WRONG!

for reasons explained here.

Ruby combining an array into one string

While a bit more cryptic than join, you can also multiply the array by a string.

@arr * " "

What is difference between Lightsail and EC2?

Check official website https://aws.amazon.com/free/compute/lightsail-vs-ec2/

enter image description here

Amazon Lightsail – The Power of AWS, the Simplicity of a VPS https://aws.amazon.com/blogs/aws/amazon-lightsail-the-power-of-aws-the-simplicity-of-a-vps/

Amazon EC2 vs Amazon Lightsail (comparison on point )

  • Web Performances
  • Plans
  • Features and Usability enter image description here

Source : https://www.vpsbenchmarks.com/compare/features/ec2_vs_lightsail

Bootstrap 4 - Responsive cards in card-columns

I realize this question was posted a while ago; nonetheless, Bootstrap v4.0 has card layout support out of the box. You can find the documentation here: Bootstrap Card Layouts.

I've gotten back into using Bootstrap for a recent project that relies heavily on the card layout UI. I've found success with the following implementation across the standard breakpoints:

_x000D_
_x000D_
<link href="https://unpkg.com/[email protected]/css/tachyons.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="flex justify-center" id="cars" v-cloak>_x000D_
    <!-- RELEVANT MARKUP BEGINS HERE -->_x000D_
    <div class="container mh0 w-100">_x000D_
        <div class="page-header text-center mb5">_x000D_
            <h1 class="avenir text-primary mb-0">Cars</h1>_x000D_
            <p class="text-secondary">Add and manage your cars for sale.</p>_x000D_
            <div class="header-button">_x000D_
                <button class="btn btn-outline-primary" @click="clickOpenAddCarModalButton">Add a car for sale</button>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="container pa0 flex justify-center">_x000D_
            <div class="listings card-columns">_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

After trying both the Bootstrap .card-group and .card-deck card layout classes with quirky results at best across the standard breakpoints, I finally decided to give the .card-columns class a shot. And it worked!

Your results may vary, but .card-columns seems to be the most stable implementation here.

Select 50 items from list at random to write to file

One easy way to select random items is to shuffle then slice.

import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables

Angular 4 - Observable catch error

With angular 6 and rxjs 6 Observable.throw(), Observable.off() has been deprecated instead you need to use throwError

ex :

return this.http.get('yoururl')
  .pipe(
    map(response => response.json()),
    catchError((e: any) =>{
      //do your processing here
      return throwError(e);
    }),
  );

How to extract hours and minutes from a datetime.datetime object?

Don't know how you want to format it, but you can do:

print("Created at %s:%s" % (t1.hour, t1.minute))

for example.

How to center content in a bootstrap column?

No need to complicate things. With Bootstrap 4, you can simply align items horizontally inside a column using the margin auto class my-auto

         <div class="col-md-6 my-auto">
           <h3>Lorem ipsum.</h3>
         </div>

Using pointer to char array, values in that array can be accessed?

Use of pointer before character array

Normally, Character array is used to store single elements in it i.e 1 byte each

eg:

char a[]={'a','b','c'};

we can't store multiple value in it.

by using pointer before the character array we can store the multi dimensional array elements in the array

i.e.

char *a[]={"one","two","three"};
printf("%s\n%s\n%s",a[0],a[1],a[2]);

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

How to Load an Assembly to AppDomain with all references recursively?

You need to invoke CreateInstanceAndUnwrap before your proxy object will execute in the foreign application domain.

 class Program
{
    static void Main(string[] args)
    {
        AppDomainSetup domaininfo = new AppDomainSetup();
        domaininfo.ApplicationBase = System.Environment.CurrentDirectory;
        Evidence adevidence = AppDomain.CurrentDomain.Evidence;
        AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, domaininfo);

        Type type = typeof(Proxy);
        var value = (Proxy)domain.CreateInstanceAndUnwrap(
            type.Assembly.FullName,
            type.FullName);

        var assembly = value.GetAssembly(args[0]);
        // AppDomain.Unload(domain);
    }
}

public class Proxy : MarshalByRefObject
{
    public Assembly GetAssembly(string assemblyPath)
    {
        try
        {
            return Assembly.LoadFile(assemblyPath);
        }
        catch (Exception)
        {
            return null;
            // throw new InvalidOperationException(ex);
        }
    }
}

Also, note that if you use LoadFrom you'll likely get a FileNotFound exception because the Assembly resolver will attempt to find the assembly you're loading in the GAC or the current application's bin folder. Use LoadFile to load an arbitrary assembly file instead--but note that if you do this you'll need to load any dependencies yourself.

Check if a variable is between two numbers with Java

<<= is like +=, but for a left shift. x <<= 1 means x = x << 1. That's why 90 >>= angle doesn't parse. And, like others have said, Java doesn't have an elegant syntax for checking if a number is an an interval, so you have to do it the long way. It also can't do if (x == 0 || 1), and you're stuck writing it out the long way.

jQuery: serialize() form and other parameters

Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:

// ...

url: "MyUrl",       //  For example --> @Url.Action("Method", "Controller")
method: "post",
traditional: true,  
data: 
    $('#myForm').serialize() +
    "&param1="xxx" +
    "&param2="33" +
    "&" + $.param({ paramArray: ["1","2","3"]}, true)
,             

// ...

Parsing a JSON array using Json.Net

You can get at the data values like this:

string json = @"
[ 
    { ""General"" : ""At this time we do not have any frequent support requests."" },
    { ""Support"" : ""For support inquires, please see our support page."" }
]";

JArray a = JArray.Parse(json);

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        Console.WriteLine(name + " -- " + value);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

Escape text for HTML

using System.Web;

var encoded = HttpUtility.HtmlEncode(unencoded);

I want to execute shell commands from Maven's pom.xml

The problem here is that I don't know what is expected. With your current setup, invoking the plugin on the command line would just work:

$ mvn exec:exec
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Q3491937
[INFO]    task-segment: [exec:exec]
[INFO] ------------------------------------------------------------------------
[INFO] [exec:exec {execution: default-cli}]
[INFO] laptop
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
...

The global configuration is used, the hostname command is executed (laptop is my hostname). In other words, the plugin works as expected.

Now, if you want a plugin to get executed as part of the build, you have to bind a goal on a specific phase. For example, to bind it on compile:

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1.1</version>
    <executions>
      <execution>
        <id>some-execution</id>
        <phase>compile</phase>
        <goals>
          <goal>exec</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <executable>hostname</executable>
    </configuration>
  </plugin>

And then:

$ mvn compile
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Q3491937
[INFO]    task-segment: [compile]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources {execution: default-resources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/pascal/Projects/Q3491937/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [exec:exec {execution: some-execution}]
[INFO] laptop
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
...

Note that you can specify a configuration inside an execution.

How do I get the RootViewController from a pushed controller?

Use the viewControllers property of the UINavigationController. Example code:

// Inside another ViewController
NSArray *viewControllers = self.navigationController.viewControllers;
UIViewController *rootViewController = [viewControllers objectAtIndex:viewControllers.count - 2];

This is the standard way of getting the "back" view controller. The reason objectAtIndex:0 works is because the view controller you're trying to access is also the root one, if you were deeper in the navigation, the back view would not be the same as the root view.

How to access form methods and controls from a class in C#?

Another solution would be to pass the textbox (or control you want to modify) into the method that will manipulate it as a parameter.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        TestClass test = new TestClass();
        test.ModifyText(textBox1);
    }
}

public class TestClass
{
    public void ModifyText(TextBox textBox)
    {
        textBox.Text = "New text";
    }
}

Convert Map to JSON using Jackson

You should prefer Object Mapper instead. Here is the link for the same : Object Mapper - Spring MVC way of Obect to JSON

How do you reinstall an app's dependencies using npm?

The easiest way that I can see is delete node_modules folder and execute npm install.

SQL left join vs multiple tables on FROM line?

I hear a lot of people complain the first one is too difficult to understand and that it is unclear. I don't see a problem with it, but after having that discussion, I use the second one even on INNER JOINS for clarity.

How to add one column into existing SQL Table

Its work perfectly

ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL;

But if you want more precise in table then you can try AFTER.

ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL AFTER `column_name`;

It will add LastUpdate column after specified column name (column_name).

How many socket connections possible?

10,000? 70,000? is that all :)

FreeBSD is probably the server you want, Here's a little blog post about tuning it to handle 100,000 connections, its has had some interesting features like zero-copy sockets for some time now, along with kqueue to act as a completion port mechanism.

Solaris can handle 100,000 connections back in the last century!. They say linux would be better

The best description I've come across is this presentation/paper on writing a scalable webserver. He's not afraid to say it like it is :)

Same for software: the cretins on the application layer forced great innovations on the OS layer. Because Lotus Notes keeps one TCP connection per client open, IBM contributed major optimizations for the ”one process, 100.000 open connections” case to Linux

And the O(1) scheduler was originally created to score well on some irrelevant Java benchmark. The bottom line is that this bloat bene?ts all of us.

What is a serialVersionUID and why should I use it?

It would be nice if CheckStyle could verify that the serialVersionUID on a class that implements Serializable has a good value, i.e. that it matches what the serial version id generator would produce. If you have a project with lots of serializable DTOs, for example, remembering to delete the existing serialVersionUID and regenerate it is a pain, and currently the only way (that I know of) to verify this is to regenerate for each class and compare to the old one. This is very very painful.

Running a command as Administrator using PowerShell?

Here is an addition to Shay Levi's suggestion (just add these lines at the beginning of a script):

if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))  
{  
  $arguments = "& '" +$myinvocation.mycommand.definition + "'"
  Start-Process powershell -Verb runAs -ArgumentList $arguments
  Break
}

This results in the current script being passed to a new powershell process in Administrator mode (if current User has access to Administrator mode and the script is not launched as Administrator).

Perl: Use s/ (replace) and return new string

require 5.013002; # or better:    use Syntax::Construct qw(/r);
print "bla: ", $myvar =~ s/a/b/r, "\n";

See perl5132delta:

The substitution operator now supports a /r option that copies the input variable, carries out the substitution on the copy and returns the result. The original remains unmodified.

my $old = 'cat';
my $new = $old =~ s/cat/dog/r;
# $old is 'cat' and $new is 'dog'

Normalize data in pandas

If you don't mind importing the sklearn library, I would recommend the method talked on this blog.

import pandas as pd
from sklearn import preprocessing

data = {'score': [234,24,14,27,-74,46,73,-18,59,160]}
cols = data.columns
df = pd.DataFrame(data)
df

min_max_scaler = preprocessing.MinMaxScaler()
np_scaled = min_max_scaler.fit_transform(df)
df_normalized = pd.DataFrame(np_scaled, columns = cols)
df_normalized

How to send SMS in Java

There are two ways : First : Use a SMS API Gateway which you need to pay for it , maybe you find some trial even free ones but it's scarce . Second : To use AT command with a modem GSM connected to your laptop . that's all

sudo: npm: command not found

I had the same problem; here are the commands to fix it:

  • sudo ln -s /usr/local/bin/node /usr/bin/node
  • sudo ln -s /usr/local/lib/node /usr/lib/node
  • sudo ln -s /usr/local/bin/npm /usr/bin/npm
  • sudo ln -s /usr/local/bin/node-waf /usr/bin/node-waf

Putting a simple if-then-else statement on one line

Moreover, you can still use the "ordinary" if syntax and conflate it into one line with a colon.

if i > 3: print("We are done.")

or

field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural)) 

Initialising mock objects - MockIto

There is a neat way of doing this.

  • If it's an Unit Test you can do this:

    @RunWith(MockitoJUnitRunner.class)
    public class MyUnitTest {
    
        @Mock
        private MyFirstMock myFirstMock;
    
        @Mock
        private MySecondMock mySecondMock;
    
        @Spy
        private MySpiedClass mySpiedClass = new MySpiedClass();
    
        // It's gonna inject the 2 mocks and the spied object per reflection to this object
        // The java doc of @InjectMocks explains it really well how and when it does the injection
        @InjectMocks
        private MyClassToTest myClassToTest;
    
        @Test
        public void testSomething() {
        }
    }
    
  • EDIT: If it's an Integration test you can do this(not intended to be used that way with Spring. Just showcase that you can initialize mocks with diferent Runners):

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("aplicationContext.xml")
    public class MyIntegrationTest {
    
        @Mock
        private MyFirstMock myFirstMock;
    
        @Mock
        private MySecondMock mySecondMock;
    
        @Spy
        private MySpiedClass mySpiedClass = new MySpiedClass();
    
        // It's gonna inject the 2 mocks and the spied object per reflection to this object
        // The java doc of @InjectMocks explains it really well how and when it does the injection
        @InjectMocks
        private MyClassToTest myClassToTest;
    
        @Before
        public void setUp() throws Exception {
              MockitoAnnotations.initMocks(this);
        }
    
        @Test
        public void testSomething() {
        }
    }
    

Get raw POST body in Python Flask regardless of Content-Type header

I created a WSGI middleware that stores the raw body from the environ['wsgi.input'] stream. I saved the value in the WSGI environ so I could access it from request.environ['body_copy'] within my app.

This isn't necessary in Werkzeug or Flask, as request.get_data() will get the raw data regardless of content type, but with better handling of HTTP and WSGI behavior.

This reads the entire body into memory, which will be an issue if for example a large file is posted. This won't read anything if the Content-Length header is missing, so it won't handle streaming requests.

from io import BytesIO

class WSGICopyBody(object):
    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):
        length = int(environ.get('CONTENT_LENGTH') or 0)
        body = environ['wsgi.input'].read(length)
        environ['body_copy'] = body
        # replace the stream since it was exhausted by read()
        environ['wsgi.input'] = BytesIO(body)
        return self.application(environ, start_response)

app.wsgi_app = WSGICopyBody(app.wsgi_app)
request.environ['body_copy']

Create a Date with a set timezone without using a string representation

One line solution

new Date(new Date(1422524805305).getTime() - 330*60*1000)

Instead of 1422524805305, use the timestamp in milliseconds Instead of 330, use your timezone offset in minutes wrt. GMT (eg India +5:30 is 5*60+30 = 330 minutes)

Which Radio button in the group is checked?

You can use an Extension method to iterate the RadioButton's Parent.Controls collection. This allows you to query other RadioButtons in the same scope. Using two extension methods, you can use the first determine whether any RadioButtons in the group are selected, then use the second to get the selection. The RadioButton Tag field can be used to hold an Enum to identify each RadioButton in the group:

    public static int GetRadioSelection(this RadioButton rb, int Default = -1) {
        foreach(Control c in  rb.Parent.Controls) {
            RadioButton r = c as RadioButton;
            if(r != null && r.Checked) return Int32.Parse((string)r.Tag);
        }
        return Default;
    }

    public static bool IsRadioSelected(this RadioButton rb) {
        foreach(Control c in  rb.Parent.Controls) {
            RadioButton r = c as RadioButton;
            if(r != null && r.Checked) return true;
        }
        return false;
    }

Here's a typical use pattern:

if(!MyRadioButton.IsRadioSelected()) {
   MessageBox.Show("No radio selected.");
   return;
}
int selection = MyRadioButton.GetRadioSelection;

Subtracting two lists in Python

to use list comprehension:

[i for i in a if not i in b or b.remove(i)]

would do the trick. It would change b in the process though. But I agree with jkp and Dyno Fu that using a for loop would be better.

Perhaps someone can create a better example that uses list comprehension but still is KISS?

Invalid column name sql error

You have to use '"+texbox1.Text+"','"+texbox2.Text+"','"+texbox3.Text+"'

Instead of "+texbox1.Text+","+texbox2.Text+","+texbox3.Text+"

Notice the extra single quotes.

Python check if list items are integers?

The usual way to check whether something can be converted to an int is to try it and see, following the EAFP principle:

try:
    int_value = int(string_value)
except ValueError:
    # it wasn't an int, do something appropriate
else:
    # it was an int, do something appropriate

So, in your case:

for item in mylist:
    try:
        int_value = int(item)
    except ValueError:
        pass
    else:
        mynewlist.append(item) # or append(int_value) if you want numbers

In most cases, a loop around some trivial code that ends with mynewlist.append(item) can be turned into a list comprehension, generator expression, or call to map or filter. But here, you can't, because there's no way to put a try/except into an expression.

But if you wrap it up in a function, you can:

def raises(func, *args, **kw):
    try:
        func(*args, **kw)
    except:
        return True
    else:
        return False

mynewlist = [item for item in mylist if not raises(int, item)]

… or, if you prefer:

mynewlist = filter(partial(raises, int), item)

It's cleaner to use it this way:

def raises(exception_types, func, *args, **kw):
    try:
        func(*args, **kw)
    except exception_types:
        return True
    else:
        return False

This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True, but if any unexpected exceptions are raised, they'll propagate out. So:

mynewlist = [item for item in mylist if not raises(ValueError, int, item)]

… will do what you want, but:

mynewlist = [item for item in mylist if not raises(ValueError, item, int)]

… will raise a TypeError, as it should.

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

Basically It is used in HeapOverflows or other reversing type Problems i.e. If you want to change a 64 bit ELF to 32 bit ELF and it is showing error while converting.

You can simply run the commands

apt-get install gcc-multilib g++-multilib

which will update your libraries Packages upgraded:

The following additional packages will be installed: g++-8-multilib gcc-8-multilib lib32asan5 lib32atomic1 lib32gcc-8-dev lib32gomp1 lib32itm1 lib32mpx2 lib32quadmath0 lib32stdc++-8-dev lib32ubsan1 libc-dev-bin libc6 libc6-dbg libc6-dev libc6-dev-i386 libc6-dev-x32 libc6-i386 libc6-x32 libx32asan5 libx32atomic1 libx32gcc-8-dev libx32gcc1 libx32gomp1 libx32itm1 libx32quadmath0 libx32stdc++-8-dev libx32stdc++6 libx32ubsan1 Suggested packages: lib32stdc++6-8-dbg libx32stdc++6-8-dbg glibc-doc The following NEW packages will be installed: g++-8-multilib g++-multilib gcc-8-multilib gcc-multilib lib32asan5 lib32atomic1 lib32gcc-8-dev lib32gomp1 lib32itm1 lib32mpx2 lib32quadmath0 lib32stdc++-8-dev lib32ubsan1 libc6-dev-i386 libc6-dev-x32 libc6-x32 libx32asan5 libx32atomic1 libx32gcc-8-dev libx32gcc1 libx32gomp1 libx32itm1 libx32quadmath0 libx32stdc++-8-dev libx32stdc++6 libx32ubsan1

similar to this will be shown to your terminal

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

If you are connecting from Windows machine A to Windows machine B (server with SQL Server installed), and are getting this error, you need to do the following:

On machine B:

1.) turn on the Windows service called "SQL Server Browser" and start the service

2.) in the Windows firewall, enable incoming port UDP 1434 (in case SQL Server Management Studio on machine A is connecting or a program on machine A is connecting)

3.) in the Windows firewall, enable incoming port TCP 1433 (in case there is a telnet connection)

4.) in SQL Server Configuration Manager, enable TCP/IP protocol for port 1433

enter image description here

Is there a need for range(len(a))?

Short answer: mathematically speaking, no, in practical terms, yes, for example for Intentional Programming.

Technically, the answer would be "no, it's not needed" because it's expressible using other constructs. But in practice, I use for i in range(len(a) (or for _ in range(len(a)) if I don't need the index) to make it explicit that I want to iterate as many times as there are items in a sequence without needing to use the items in the sequence for anything.

So: "Is there a need?"? — yes, I need it to express the meaning/intent of the code for readability purposes.

See also: https://en.wikipedia.org/wiki/Intentional_programming

And obviously, if there is no collection that is associated with the iteration at all, for ... in range(len(N)) is the only option, so as to not resort to i = 0; while i < N; i += 1 ...

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

sudo psql --host=localhost --dbname=database-name --username=postgres

This solved my issue

Getting the IP address of the current machine using Java

You can use java's InetAddress class for this purpose.

InetAddress IP=InetAddress.getLocalHost();
System.out.println("IP of my system is := "+IP.getHostAddress());

Output for my system = IP of my system is := 10.100.98.228

getHostAddress() returns

Returns the IP address string in textual presentation.

OR you can also do

InetAddress IP=InetAddress.getLocalHost();
System.out.println(IP.toString());

Output = IP of my system is := RanRag-PC/10.100.98.228

Newtonsoft JSON Deserialize

As per the Newtonsoft Documentation you can also deserialize to an anonymous object like this:

var definition = new { Name = "" };

string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);

Console.WriteLine(customer1.Name);
// James

Get data from php array - AJAX - jQuery

When you echo $array;, the result is Array, result[0] then represents the first character in Array which is A.

One way to handle this problem would be like this:

ajax.php

<?php
$array = array(1,2,3,4,5,6);
foreach($array as $a)
    echo $a.",";
?>

jquery code

$(function(){ /* short for $(document).ready(function(){ */

    $('#prev').click(function(){

        $.ajax({type:    'POST',
                 url:     'ajax.php',
                 data:    'id=testdata',
                 cache:   false,
                 success: function(data){
                     var tmp = data.split(",");
                     $('#content1').html(tmp[0]);
                 }
                });
    });

});

How to choose an AWS profile when using boto3 to connect to CloudFront

I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.

So there are three different ways to do this:

Option A) Create a new session with the profile

    dev = boto3.session.Session(profile_name='dev')

Option B) Change the profile of the default session in code

    boto3.setup_default_session(profile_name='dev')

Option C) Change the profile of the default session with an environment variable

    $ AWS_PROFILE=dev ipython
    >>> import boto3
    >>> s3dev = boto3.resource('s3')

What is the best way to remove accents (normalize) in a Python unicode string?

Some languages have combining diacritics as language letters and accent diacritics to specify accent.

I think it is more safe to specify explicitly what diactrics you want to strip:

def strip_accents(string, accents=('COMBINING ACUTE ACCENT', 'COMBINING GRAVE ACCENT', 'COMBINING TILDE')):
    accents = set(map(unicodedata.lookup, accents))
    chars = [c for c in unicodedata.normalize('NFD', string) if c not in accents]
    return unicodedata.normalize('NFC', ''.join(chars))

Install IPA with iTunes 11

For iTunes 12, drag the .ipa file from the Finder to the Apps area NOT inside your device (in iTunes)... alternately, you can just double click on the .ipa in the Finder.

Important note: you have to change Version and/or Build number. Otherwise, you get no notice from iTunes at all...

Then switch to your device in iTunes, and install or update the application.

Then hit sync.

Destroy or remove a view in Backbone.js

I had to be absolutely sure the view was not just removed from DOM but also completely unbound from events.

destroy_view: function() {

    // COMPLETELY UNBIND THE VIEW
    this.undelegateEvents();

    this.$el.removeData().unbind(); 

    // Remove view from DOM
    this.remove();  
    Backbone.View.prototype.remove.call(this);

}

Seemed like overkill to me, but other approaches did not completely do the trick.

What are the rules about using an underscore in a C++ identifier?

From MSDN:

Use of two sequential underscore characters ( __ ) at the beginning of an identifier, or a single leading underscore followed by a capital letter, is reserved for C++ implementations in all scopes. You should avoid using one leading underscore followed by a lowercase letter for names with file scope because of possible conflicts with current or future reserved identifiers.

This means that you can use a single underscore as a member variable prefix, as long as it's followed by a lower-case letter.

This is apparently taken from section 17.4.3.1.2 of the C++ standard, but I can't find an original source for the full standard online.

See also this question.

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

Loose coupling means that the degree of dependency between two components is very low.
Example: GSM SIM

Tight coupling means that the degree of dependency between two components is very high.
Example: CDMA Mobile

How to "properly" create a custom object in JavaScript?

Douglas Crockford discusses that topic extensively in The Good Parts. He recommends to avoid the new operator to create new objects. Instead he proposes to create customized constructors. For instance:

var mammal = function (spec) {     
   var that = {}; 
   that.get_name = function (  ) { 
      return spec.name; 
   }; 
   that.says = function (  ) { 
      return spec.saying || ''; 
   }; 
   return that; 
}; 

var myMammal = mammal({name: 'Herb'});

In Javascript a function is an object, and can be used to construct objects out of together with the new operator. By convention, functions intended to be used as constructors start with a capital letter. You often see things like:

function Person() {
   this.name = "John";
   return this;
}

var person = new Person();
alert("name: " + person.name);**

In case you forget to use the new operator while instantiating a new object, what you get is an ordinary function call, and this is bound to the global object instead to the new object.

What does 'x packages are looking for funding' mean when running `npm install`?

You can skip fund using:

npm install --no-fund YOUR PACKAGE NAME

For example :

npm install --no-fund core-js

Pure CSS scroll animation

You can do it with anchor tags using css3 :target pseudo-selector, this selector is going to be triggered when the element with the same id as the hash of the current URL get an match. Example

Knowing this, we can combine this technique with the use of proximity selectors like "+" and "~" to select any other element through the target element who id get match with the hash of the current url. An example of this would be something like what you are asking.

How to create and write to a txt file using VBA

an easy way with out much redundancy.

    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim Fileout As Object
    Set Fileout = fso.CreateTextFile("C:\your_path\vba.txt", True, True)
    Fileout.Write "your string goes here"
    Fileout.Close

Keep background image fixed during scroll using css

Just add background-attachment to your code

body {
    background-position: center;
    background-image: url(../images/images5.jpg);
    background-attachment: fixed;
}

Sending cookies with postman

Based @RBT's answer above, I tried Postman native app and want to give a couple of additional details.

In the latest postman desktop app, you can find the cookies option on the extreme right:

enter image description here

You can see the cookies for your localhost (these cookies are linked with the cookies in your chrome browser, although the app is running natively). Also you can set the cookies for a particular domain too.

enter image description here

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

A simple solution is to convert base 64 to alphanumeric by discarding the non-alphanumeric characters.

This one uses random_bytes() for a cryptographically secure result.

function random_alphanumeric(int $length): string
{
    $result='';
    do
    {
        //Base 64 produces 4 characters for each 3 bytes, so most times this will give enough bytes in a single pass
        $bytes=random_bytes(($length+3-strlen($result))*2);
        //Discard non-alhpanumeric characters
        $result.=str_replace(['/','+','='],['','',''],base64_encode($bytes));
        //Keep adding characters until the string is long enough
        //Add a few extra because the last 2 or 3 characters of a base 64 string tend to be less diverse
    }while(strlen($result)<$length+3);
    return substr($result,0,$length);
}

Edit: I just revisited this because I need something a bit more flexible. Here is a solution that performs a bit better than the above and gives the option to specify any subset of the ASCII character set:

<?php
class RandomText
{
    protected
        $allowedChars,
        //Maximum index to use
        $allowedCount,
        //Index values will be taken from a pool of this size
        //It is a power of 2 to keep the distribution of values even
        $distributionSize,
        //This many characters will be generated for each output character
        $ratio;
    /**
     * @param string $allowedChars characters to choose from
     */
    public function __construct(string $allowedChars)
    {
        $this->allowedCount = strlen($allowedChars);
        if($this->allowedCount < 1 || $this->allowedCount > 256) throw new \Exception('At least 1 and no more than 256 allowed character(s) must be specified.');
        $this->allowedChars = $allowedChars;
        //Find the power of 2 equal or greater than the number of allowed characters
        $this->distributionSize = pow(2,ceil(log($this->allowedCount, 2)));
        //Generating random bytes is the expensive part of this algorithm
        //In most cases some will be wasted so it is helpful to produce some extras, but not too many
        //On average, this is how many characters needed to produce 1 character in the allowed set
        //50% of the time, more characters will be needed. My tests have shown this to perform well.
        $this->ratio = $this->distributionSize / $this->allowedCount;
    }

    /**
     * @param int $length string length of required result
     * @return string random text
     */
    public function get(int $length) : string
    {
        if($length < 1) throw new \Exception('$length must be >= 1.');
        $result = '';
        //Keep track of result length to prevent having to compute strlen()
        $l = 0;
        $indices = null;
        $i = null;
        do
        {
            //Bytes will be used to index the character set. Convert to integers.
            $indices = unpack('C*', random_bytes(ceil(($length - $l) * $this->ratio)));
            foreach($indices as $i)
            {
                //Reduce to the smallest range that gives an even distribution
                $i %= $this->distributionSize;
                //If the index is within the range of characters, add one char to the string
                if($i < $this->allowedCount)
                {
                    $l++;
                    $result .= $this->allowedChars[$i];
                }
                if($l >= $length) break;
            }
        }while($l < $length);
        return $result;
    }
}

*ngIf and *ngFor on same element causing error

in html:

<div [ngClass]="{'disabled-field': !show}" *ngFor="let thing of stuff">
    {{thing.name}}
</div>

in css:

.disabled-field {
    pointer-events: none;
    display: none;
}

What is the difference between React Native and React?

ReactJS is a framework for building an hierarchy of UI components. Each component has state and props. Data flows from the top to low-level components via props. The state is updated in the top-level component using event handlers.

React native uses React framework for building components for mobile apps. React native provides a basic set of components for both iOS and Android platforms. Some of the components in React Native are Navigator, TabBar, Text, TextInput, View, ScrollView. These components use native iOS UIKit and Android UI components internally. React native also allows NativeModules where code written in ObjectiveC for iOS and Java for Android can be used within JavaScript.

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

Download and install an ipa from self hosted url on iOS

To distribute your app over-the-air (OTA, this means without using TestFlight or the official App Store), you may need to create 3 different files, namely:

  • The .ipa file (using an ad-hoc provisioning profile)
  • index.html
  • manifest.plist

You can use Beta Builder to generate these files:

  1. Archive your build.
  2. Save the .ipa on the Desktop.
  3. Download a small utility Beta Builder from here. This does most of the required task.
  4. Open the tool and select your .ipa file, then provide the path you will be placing the build on https://myWeb.com/MY_TEST_APP in the beta builder.
  5. Generate all the files.
  6. Now upload index.html, your_App.ipa, & manifest.plist to your server path https://myWeb.com/MY_TEST_APP
  7. Now share the link of index.html. Once you open this file, you will be asked to Tap on install.
  8. It will install your_App.ipa on your device.

You can also do this more manually.

index.html

<a href="itms-services://?action=download-manifest&url=https://myWeb.com/MY_TEST_APP/manifest.plist">Install App</a>

manifest.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>http://YOUR_SERVER_URL/YOUR-IPA-FILE.ipa</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>com.yourCompany.productName</string>
                <key>bundle-version</key>
                <string>1.0.0</string>
                <key>kind</key>
                <string>software</string>
                <key>title</key>
                <string>YOUR APP NAME</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>

If the app refuses to install or run, you may need to check the following items:

  • The provisioning profile you've used when compiling/archiving your app
  • The URLs in both index.html and manifest.plist
  • The plist file may possibly need to be hosted on an HTTPS server. You can use Dropbox for this if necessary.
  • Your device UUIDs may need to be registered inside Apple Developer Center unless you have an Enterprise licence
  • You may need to manually enable access to the app within Settings > Profiles

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

So while this is answered and accepted it still came up as a top search result and the answers though laid out (after lots of research) left me scratching my head and digging a lot further. So here's a quick layout of how I resolved the issue.

Assuming my server is myserver.myhome.com and my static IP address is 192.168.1.150:

  1. Edit the hosts file

    $ sudo nano -w /etc/hosts
    
    127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
    
    127.0.0.1 myserver.myhome.com myserver
    
    192.168.1.150 myserver.myhome.com myserver
    
    ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
    ::1 myserver.myhome.com myserver
    
  2. Edit httpd.conf

    $ sudo nano -w /etc/apache2/httpd.conf
    
    ServerName myserver.myhome.com
    
  3. Edit network

    $ sudo nano -w /etc/sysconfig/network HOSTNAME=myserver.myhome.com
    
  4. Verify

    $ hostname
    
    (output) myserver.myhome.com
    
    $ hostname -f
    
    (output) myserver.myhome.com
    
  5. Restart Apache

    $ sudo /etc/init.d/apache2 restart
    

It appeared the difference was including myserver.myhome.com to both the 127.0.0.1 as well as the static IP address 192.168.1.150 in the hosts file. The same on Ubuntu Server and CentOS.

Simplest way to wait some asynchronous tasks complete, in Javascript?

I do this without external libaries:

var yourArray = ['aaa','bbb','ccc'];
var counter = [];

yourArray.forEach(function(name){
    conn.collection(name).drop(function(err) {
        counter.push(true);
        console.log('dropped');
        if(counter.length === yourArray.length){
            console.log('all dropped');
        }
    });                
});

any tool for java object to object mapping?

ModelMapper is another library worth checking out. ModelMapper's design is different from other libraries in that it:

  • Automatically maps object models by intelligently matching source and destination properties
  • Provides a refactoring safe mapping API that uses actual code to map fields and methods rather than using strings
  • Utilizes convention based configuration for simple handling of custom scenarios

Check out the ModelMapper site for more info:

http://modelmapper.org

Getting current directory in .NET web application

Use this code:

 HttpContext.Current.Server.MapPath("~")

Detailed Reference:

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward (/) or backward slash (), the MapPath method returns a path as if Path were a full, virtual path.

If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

Server.MapPath(null) and Server.MapPath("") will produce this effect too.

JQuery - $ is not defined

if script tag has defer attribute it show the error

Uncaught ReferenceError: $ is not defined

and must remove the attribute defer from script tag

html5 input for money/currency

_x000D_
_x000D_
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'USD' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml

 // format inital value
onBlur({target:currencyInput})

// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)


function localStringToNumber( s ){
  return Number(String(s).replace(/[^0-9.-]+/g,""))
}

function onFocus(e){
  var value = e.target.value;
  e.target.value = value ? localStringToNumber(value) : ''
}

function onBlur(e){
  var value = e.target.value

  var options = {
      maximumFractionDigits : 2,
      currency              : currency,
      style                 : "currency",
      currencyDisplay       : "symbol"
  }
  
  e.target.value = value 
    ? localStringToNumber(value).toLocaleString(undefined, options)
    : ''
}
_x000D_
input{
  padding: 10px;
  font: 20px Arial;
  width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
_x000D_
_x000D_

mysql: get record count between two date-time

select * from yourtable 
   where created < now() 
     and created > concat(curdate(),' 4:30:00 AM') 

How to catch curl errors in PHP

Since you are interested in catching network related errors and HTTP errors, the following provides a better approach:

function curl_error_test($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $responseBody = curl_exec($ch);
    /*
     * if curl_exec failed then
     * $responseBody is false
     * curl_errno() returns non-zero number
     * curl_error() returns non-empty string
     * which one to use is up too you
     */
    if ($responseBody === false) {
        return "CURL Error: " . curl_error($ch);
    }

    $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    /*
     * 4xx status codes are client errors
     * 5xx status codes are server errors
     */
    if ($responseCode >= 400) {
        return "HTTP Error: " . $responseCode;
    }

    return "No CURL or HTTP Error";
}

Tests:

curl_error_test("http://expamle.com");          // CURL Error: Could not resolve host: expamle.com
curl_error_test("http://example.com/whatever"); // HTTP Error: 404
curl_error_test("http://example.com");          // No CURL or HTTP Error

Python - How to concatenate to a string in a for loop?

endstring = ''
for s in list:
    endstring += s

Add padding on view programmatically

use below method for setting padding dynamically

setPadding(int left, int top, int right, int bottom)

Example :

view.setPadding(2,2,2,2);

Is it possible to capture the stdout from the sh DSL command in the pipeline

A short version would be:

echo sh(script: 'ls -al', returnStdout: true).result

Difference between break and continue statement

break completely exits the loop. continue skips the statements after the continue statement and keeps looping.

How to increase the distance between table columns in HTML?

If I understand correctly, you want this fiddle.

_x000D_
_x000D_
table {_x000D_
  background: gray;_x000D_
}_x000D_
td {    _x000D_
  display: block;_x000D_
  float: left;_x000D_
  padding: 10px 0;_x000D_
  margin-right:50px;_x000D_
  background: white;_x000D_
}_x000D_
td:last-child {_x000D_
  margin-right: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Hello HTML!</td>_x000D_
    <td>Hello CSS!</td>_x000D_
    <td>Hello JS!</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to add java plugin for Firefox on Linux?

you should add plug in to your local setting of firefox in your user home

 vladimir@shinsengumi ~/.mozilla/plugins $ pwd
 /home/vladimir/.mozilla/plugins 
 vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
 lrwxrwxrwx 1 vladimir vladimir 60 Jan  1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so

Java String encoding (UTF-8)

How is this different from the following?

This line of code here:

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

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

String newString = oldString;

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

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

Absolutely:

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

vs.

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

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

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

is

String newString = new String(oldString);

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

Pure CSS collapse/expand div

Or a super simple version with barely any css :)

<style>   
.faq ul li {
    display:block;
    float:left;
    padding:5px;
}

.faq ul li div {
    display:none;
}

.faq ul li div:target {
    display:block;
}


</style>


<div class="faq">
   <ul>
   <li><a href="#question1">Question 1</a>   
   <div id="question1">Answer 1 </div>
   </li>


   <li><a href="#question2">Question 2</a>
   <div id="question2">Answer 2 </div>
   </li>
   <li><a href="#question3">Question 3</a>
   <div id="question3">Answer 3 </div>
   </li>
   <li><a href="#question4">Question 4</a>
   <div id="question4">Answer 4 </div>
   </li>
   <li><a href="#question5">Question 5</a>
   <div id="question5">Answer 5 </div>
   </li>
   <li><a href="#question6">Question 6</a>
   <div id="question6">Answer 6 </div>
   </li>
   </ul>  
</div>

http://jsfiddle.net/ionko22/4sKD3/

python 2 instead of python 3 as the (temporary) default python?

Just call the script using something like python2.7 or python2 instead of just python.

So:

python2 myscript.py

instead of:

python myscript.py

What you could alternatively do is to replace the symbolic link "python" in /usr/bin which currently links to python3 with a link to the required python2/2.x executable. Then you could just call it as you would with python 3.

onclick or inline script isn't working in extension

As already mentioned, Chrome Extensions don't allow to have inline JavaScript due to security reasons so you can try this workaround as well.

HTML file

<!doctype html>
    <html>
        <head>
            <title>
                Getting Started Extension's Popup
            </title>
            <script src="popup.js"></script>
        </head>
        <body>
            <div id="text-holder">ha</div><br />
            <a class="clickableBtn">
                  hyhy
            </a>
        </body>
    </html>
<!doctype html>

popup.js

window.onclick = function(event) {
    var target = event.target ;
    if(target.matches('.clickableBtn')) {
        var clickedEle = document.activeElement.id ;
        var ele = document.getElementById(clickedEle);
        alert(ele.text);
    }
}

Or if you are having a Jquery file included then

window.onclick = function(event) {
    var target = event.target ;
    if(target.matches('.clickableBtn')) {
        alert($(target).text());
    }
}

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

The entity name must immediately follow the '&' in the entity reference

Just in case someone from Blogger arrives, I had this problem when using Beautify extension in VSCode. Don´t use it, don´t beautify it.

Split string into individual words Java

See my other answer if your phrase contains accentuated characters :

String[] listeMots = phrase.split("\\P{L}+");

python pandas remove duplicate columns

The way below will identify dupe columns to review what is going wrong building the dataframe originally.

dupes = pd.DataFrame(df.columns)
dupes[dupes.duplicated()]

Python JSON serialize a Decimal object

I tried switching from simplejson to builtin json for GAE 2.7, and had issues with the decimal. If default returned str(o) there were quotes (because _iterencode calls _iterencode on the results of default), and float(o) would remove trailing 0.

If default returns an object of a class that inherits from float (or anything that calls repr without additional formatting) and has a custom __repr__ method, it seems to work like I want it to.

import json
from decimal import Decimal

class fakefloat(float):
    def __init__(self, value):
        self._value = value
    def __repr__(self):
        return str(self._value)

def defaultencode(o):
    if isinstance(o, Decimal):
        # Subclass float with custom repr?
        return fakefloat(o)
    raise TypeError(repr(o) + " is not JSON serializable")

json.dumps([10.20, "10.20", Decimal('10.20')], default=defaultencode)
'[10.2, "10.20", 10.20]'

Is there a way to use max-width and height for a background image?

You can do this with background-size:

html {
    background: url(images/bg.jpg) no-repeat center center fixed; 
    background-size: cover;
}

There are a lot of values other than cover that you can set background-size to, see which one works for you: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

Spec: https://www.w3.org/TR/css-backgrounds-3/#the-background-size

It works in all modern browsers: http://caniuse.com/#feat=background-img-opts

Permission denied on CopyFile in VBS

You can do this:

fso.CopyFile "C:\Minecraft\options.txt", "H:\Minecraft\.minecraft\options.txt"

Include the filename in the folder that you copy to.

Netbeans 8.0.2 The module has not been deployed

UPDATE: this was solved by rebooting but there was another error when running app. This time tomcat woudnt start. To solve this (bugs with latest apache and netbeans versions) follow: Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

How to grant remote access to MySQL for a whole subnet?

It looks like you can also use a netmask, e.g.

GRANT ... TO 'user'@'192.168.0.0/255.255.255.0' IDENTIFIED BY ...

Is it possible to add an HTML link in the body of a MAILTO link

The specification for 'mailto' body says:

The body of a message is simply lines of US-ASCII characters. The only two limitations on the body are as follows:

  • CR and LF MUST only occur together as CRLF; they MUST NOT appear independently in the body.
  • Lines of characters in the body MUST be limited to 998 characters, and SHOULD be limited to 78 characters, excluding the CRLF.

https://tools.ietf.org/html/rfc5322#section-2.3

Generally nowadays most email clients are good at autolinking, but not all do, due to security concerns. You can likely find some work-arounds, but it won't necessarily work universally.

int *array = new int[n]; what is this function actually doing?

In C/C++, pointers and arrays are (almost) equivalent. int *a; a[0]; will return *a, and a[1]; will return *(a + 1)

But array can't change the pointer it points to while pointer can.

new int[n] will allocate some spaces for the "array"

I can't install python-ldap

The python-ldap is based on OpenLDAP, so you need to have the development files (headers) in order to compile the Python module. If you're on Ubuntu, the package is called libldap2-dev.

Debian/Ubuntu:

sudo apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev

RedHat/CentOS:

sudo yum install python-devel openldap-devel

Display PDF within web browser

The browser's plugin controls those settings, so you can't force it. However, you can do a simple <a href="whatver.pdf"> instead of <a href="whatever.pdf" target="_blank">.

QString to char* conversion

Qt provides the simplest API

const char *qPrintable(const QString &str)
const char *qUtf8Printable(const QString &str)

If you want non-const data pointer use

str.toLocal8Bit().data()
str.toUtf8().data()

Create folder in Android

If you are trying to make more than just one folder on the root of the sdcard, ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"

then instead of folder.mkdir() you would use folder.mkdirs()

I've made this mistake in the past & I took forever to figure it out.

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

How can I find the dimensions of a matrix in Python?

m = [[1, 1, 1, 0],[0, 5, 0, 1],[2, 1, 3, 10]]

print(len(m),len(m[0]))

Output

(3 4)

How to create a fixed-size array of objects

Swift 4

You can somewhat think about it as array of object vs. array of references.

  • [SKSpriteNode] must contain actual objects
  • [SKSpriteNode?] can contain either references to objects, or nil

Examples

  1. Creating an array with 64 default SKSpriteNode:

    var sprites = [SKSpriteNode](repeatElement(SKSpriteNode(texture: nil),
                                               count: 64))
    
  2. Creating an array with 64 empty slots (a.k.a optionals):

    var optionalSprites = [SKSpriteNode?](repeatElement(nil,
                                          count: 64))
    
  3. Converting an array of optionals into an array of objects (collapsing [SKSpriteNode?] into [SKSpriteNode]):

    let flatSprites = optionalSprites.flatMap { $0 }
    

    The count of the resulting flatSprites depends on the count of objects in optionalSprites: empty optionals will be ignored, i.e. skipped.

JSON and XML comparison

Faster is not an attribute of JSON or XML or a result that a comparison between those would yield. If any, then it is an attribute of the parsers or the bandwidth with which you transmit the data.

Here is (the beginning of) a list of advantages and disadvantages of JSON and XML:


JSON

Pro:

  • Simple syntax, which results in less "markup" overhead compared to XML.
  • Easy to use with JavaScript as the markup is a subset of JS object literal notation and has the same basic data types as JavaScript.
  • JSON Schema for description and datatype and structure validation
  • JsonPath for extracting information in deeply nested structures

Con:

  • Simple syntax, only a handful of different data types are supported.

  • No support for comments.


XML

Pro:

  • Generalized markup; it is possible to create "dialects" for any kind of purpose
  • XML Schema for datatype, structure validation. Makes it also possible to create new datatypes
  • XSLT for transformation into different output formats
  • XPath/XQuery for extracting information in deeply nested structures
  • built in support for namespaces

Con:

  • Relatively wordy compared to JSON (results in more data for the same amount of information).

So in the end you have to decide what you need. Obviously both formats have their legitimate use cases. If you are mostly going to use JavaScript then you should go with JSON.

Please feel free to add pros and cons. I'm not an XML expert ;)

Maven not found in Mac OSX mavericks

For me trying above techniques did work so I opened .bash_profile file and added following line in new line to connect to maven using short cmd :

alias mvn=/opt/apache-maven-3.6.3/bin/mvn

Restart your terminal and hit mvn clean install cmd

javac is not recognized as an internal or external command, operable program or batch file

Run the following from the command prompt: set Path="C:\Program Files\Java\jdk1.7.0_09\bin" or set PATH="C:\Program Files\Java\jdk1.7.0_09\bin"

I have tried this and it works well.

How to use "not" in xpath?

Use boolean function like below:

//a[(contains(@id, 'xx'))=false]

Shell script to set environment variables

Run the script as source= to run in debug mode as well.

source= ./myscript.sh

Splitting a string into chunks of a certain size

    public static List<string> SplitByMaxLength(this string str)
    {
        List<string> splitString = new List<string>();

        for (int index = 0; index < str.Length; index += MaxLength)
        {
            splitString.Add(str.Substring(index, Math.Min(MaxLength, str.Length - index)));
        }

        return splitString;
    }

SQL DATEPART(dw,date) need monday = 1 and sunday = 7

Another solution is the following:

ISNULL(NULLIF(DATEPART(dw,DateField)-1,0),7)

How to run ssh-add on windows?

In order to run ssh-add on Windows one could install git using choco install git. The ssh-add command is recognized once C:\Program Files\Git\usr\bin has been added as a PATH variable and the command prompt has been restarted:

C:\Users\user\Desktop\repository>ssh-add .ssh/id_rsa
Enter passphrase for .ssh/id_rsa:
Identity added: .ssh/id_rsa (.ssh/id_rsa)

C:\Users\user\Desktop\repository> 

How can I open two pages from a single click without using JavaScript?

also you can open more than two page try this

`<a href="http://www.microsoft.com" target="_blank" onclick="window.open('http://www.google.com'); window.open('http://www.yahoo.com');">Click Here</a>`

Android error: Failed to install *.apk on device *: timeout

I have encountered the same problem and tried to change the ADB connection timeout. That did not work. I switched between my PC's USB ports (front -> back) and it fixed the problem!!!

What does <![CDATA[]]> in XML mean?

A CDATA section is "a section of element content that is marked for the parser to interpret as only character data, not markup."

Syntactically, it behaves similarly to a comment:

<exampleOfAComment>
<!--
    Since this is a comment
    I can use all sorts of reserved characters
    like > < " and &
    or write things like
    <foo></bar>
    but my document is still well-formed!
-->
</exampleOfAComment>

... but it is still part of the document:

<exampleOfACDATA>
<![CDATA[
    Since this is a CDATA section
    I can use all sorts of reserved characters
    like > < " and &
    or write things like
    <foo></bar>
    but my document is still well formed!
]]>
</exampleOfACDATA>

Try saving the following as a .xhtml file (not .html) and open it using FireFox (not Internet Explorer) to see the difference between the comment and the CDATA section; the comment won't appear when you look at the document in a browser, while the CDATA section will:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!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" xml:lang="en" lang="en" >
<head>
<title>CDATA Example</title>
</head>
<body>

<h2>Using a Comment</h2>
<div id="commentExample">
<!--
You won't see this in the document
and can use reserved characters like
< > & "
-->
</div>

<h2>Using a CDATA Section</h2>
<div id="cdataExample">
<![CDATA[
You will see this in the document
and can use reserved characters like
< > & "
]]>
</div>

</body>
</html>

Something to take note of with CDATA sections is that they have no encoding, so there's no way to include the string ]]> in them. Any character data which contains ]]> will have to - as far as I know - be a text node instead. Likewise, from a DOM manipulation perspective you can't create a CDATA section which includes ]]>:

var myEl = xmlDoc.getElementById("cdata-wrapper");
myEl.appendChild(xmlDoc.createCDATASection("This section cannot contain ]]>"));

This DOM manipulation code will either throw an exception (in Firefox) or result in a poorly structured XML document: http://jsfiddle.net/9NNHA/

Creating a UIImage from a UIColor to use as a background image for UIButton

I suppose that 255 in 227./255 is perceived as an integer and divide is always return 0

SQL select max(date) and corresponding value

You can use a subquery. The subquery will get the Max(CompletedDate). You then take this value and join on your table again to retrieve the note associate with that date:

select ET1.TrainingID,
  ET1.CompletedDate,
  ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
  select Max(CompletedDate) CompletedDate, TrainingID
  from HR_EmployeeTrainings
  --where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
  group by TrainingID
) ET2
  on ET1.TrainingID = ET2.TrainingID
  and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID

For-loop vs while loop in R

The variable in the for loop is an integer sequence, and so eventually you do this:

> y=as.integer(60000)*as.integer(60000)
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow

whereas in the while loop you are creating a floating point number.

Its also the reason these things are different:

> seq(0,2,1)
[1] 0 1 2
> seq(0,2)
[1] 0 1 2

Don't believe me?

> identical(seq(0,2),seq(0,2,1))
[1] FALSE

because:

> is.integer(seq(0,2))
[1] TRUE
> is.integer(seq(0,2,1))
[1] FALSE

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

I know this is late to the game, but I wanted to share in case it helps someone.

Your exact situation may not apply, however I had a similar situation and setting the File attribute helped.

Try to set the File attribute to Normal:

var path = Server.MapPath("~/App_Data/file.txt");
File.SetAttributes(path, FileAttributes.Normal);
System.IO.File.WriteAllText(path, "Hello World");

I hope this helps someone.

How to iterate through a DataTable

There are already nice solution has been given. The below code can help others to query over datatable and get the value of each row of the datatable for the ImagePath column.

  for (int i = 0; i < dataTable.Rows.Count; i++)
  {
       var theUrl = dataTable.Rows[i]["ImagePath"].ToString();
  }

Remove last character from C++ string

buf.erase(buf.size() - 1);

This assumes you know that the string is not empty. If so, you'll get an out_of_range exception.

How do I count columns of a table

this query may help you

SELECT COUNT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE 
TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'tbl_ifo'

How to detect if a stored procedure already exists

In addition to what has already been said I also like to add a different approach and advocate the use of differential script deployment strategy. Instead of making a stateful script that always checks the current state and acts based on that state, deploy via a series of stateless scripts that upgrade from well known versions. I have used this strategy and it pays off big time as my deployment scripts are now all 'IF' free.

Convert XML String to Object

You can generate class as described above, or write them manually:

[XmlRoot("msg")]
public class Message
{
    [XmlElement("id")]
    public string Id { get; set; }
    [XmlElement("action")]
    public string Action { get; set; }
}

Then you can use ExtendedXmlSerializer to serialize and deserialize.

Instalation You can install ExtendedXmlSerializer from nuget or run the following command:

Install-Package ExtendedXmlSerializer

Serialization:

var serializer = new ConfigurationContainer().Create();
var obj = new Message();
var xml = serializer.Serialize(obj);

Deserialization

var obj2 = serializer.Deserialize<Message>(xml);

This serializer support:

  • Deserialization xml from standard XMLSerializer
  • Serialization class, struct, generic class, primitive type, generic list and dictionary, array, enum
  • Serialization class with property interface
  • Serialization circular reference and reference Id
  • Deserialization of old version of xml
  • Property encryption
  • Custom serializer
  • Support XmlElementAttribute and XmlRootAttribute
  • POCO - all configurations (migrations, custom serializer...) are outside the class

ExtendedXmlSerializer support .NET 4.5 or higher and .NET Core. You can integrate it with WebApi and AspCore.

"document.getElementByClass is not a function"

It should be getElementsByClassName, and not getElementByClass. See this - https://developer.mozilla.org/en/DOM/document.getElementsByClassName.

Note that some browsers/versions may not support this.

Create list of object from another using Java 8 Streams

An addition to the solution by @Rafael Teles. The syntactic sugar Collectors.mapping does the same in one step:

//...
List<Employee> employees = persons.stream()
  .filter(p -> p.getLastName().equals("l1"))
  .collect(
    Collectors.mapping(
      p -> new Employee(p.getName(), p.getLastName(), 1000),
      Collectors.toList()));

Detailed example can be found here

How to create a shortcut using PowerShell

Beginning PowerShell 5.0 New-Item, Remove-Item, and Get-ChildItem have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.

New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"

Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.

Anyway if you want to create a Run As Administrator shortcut using Powershell you can use

$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

Here is how I solved it: In Java-ADT: Windows - Preference - Java - Installed JREs Just add another JRE, pointing to the 'jre' folder under your JDK folder. (jre is included in the jdk). Make sure you chose the new jre.

Throw away local commits in Git

Simply delete your local master branch and recreate it like so:

git branch -D master
git checkout origin/master -b master

Java: How to read a text file

Java 1.5 introduced the Scanner class for handling input from file and streams.

It is used for getting integers from a file and would look something like this:

List<Integer> integers = new ArrayList<Integer>();
Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
while (fileScanner.hasNextInt()){
   integers.add(fileScanner.nextInt());
}

Check the API though. There are many more options for dealing with different types of input sources, differing delimiters, and differing data types.

Can I restore a single table from a full mysql mysqldump file?

You can use vi editor. Type:

vi -o mysql.dump mytable.dump

to open both whole dump mysql.dump and a new file mytable.dump. Find the appropriate insert into line by pressing / and then type a phrase, for example: "insert into `mytable`", then copy that line using yy. Switch to next file by ctrl+w then down arrow key, paste the copied line with pp. Finally save the new file by typing :wq and quite vi editor by :q.

Note that if you have dumped the data using multiple inserts you can copy (yank) all of them at once using Nyy in which N is the number of lines to be copied.

I have done it with a file of 920 MB size.

Using Postman to access OAuth 2.0 Google APIs

The current answer is outdated. Here's the up-to-date flow:

The approach outlined here still works (10.12.2020) as confirmed by alexwhan.

We will use the YouTube Data API for our example. Make changes accordingly.

Make sure you have enabled your desired API for your project.

Create the OAuth 2.0 Client

  1. Visit https://console.cloud.google.com/apis/credentials
  2. Click on CREATE CREDENTIALS
  3. Select OAuth client ID
  4. For Application Type choose Web Application
  5. Add a name
  6. Add following URI for Authorized redirect URIs
https://oauth.pstmn.io/v1/callback
  1. Click Save
  2. Click on the OAuth client you just generated
  3. In the Topbar click on DOWNLOAD JSON and save the file somewhere on your machine.

We will use the file later to authenticate Postman.

Authorize Postman via OAuth 2.0 Client

  1. In the Auth tab under TYPE choose OAuth 2.0
  2. For Access Token enter the Access Token found inside the client_secret_[YourClientID].json file we downloaded in step 9
  3. Click on Get New Access Token
  4. Make sure your settings are as follows:

Click here to see the settings

You can find everything else you need in your .json file.

  1. Click on Request Token
  2. A new browser tab/window will open
  3. Once the browser tab opens, login via the appropriate Google account
  4. Accept the consent screen
  5. Done

Ignore the browser message "Not safe" etc. This will be shown until your app has been screened by Google officials. In this case it will always be shown since Postman is the app.

How to implement static class member functions in *.cpp file?

Try this:

header.hxx:

class CFoo
{
public: 
    static bool IsThisThingOn();
};

class.cxx:

#include "header.hxx"
bool CFoo::IsThisThingOn() // note: no static keyword here
{
    return true;
}

How to change line width in IntelliJ (from 120 character)

IntelliJ IDEA 2018

File > Settings... > Editor > Code Style > Hard wrap at

Code Style > Hard wrap at

IntelliJ IDEA 2016 & 2017

File > Settings... > Editor > Code Style > Right margin (columns):

File > Settings

Editor > Code Style > Right margin

How to place two divs next to each other?

  1. Add float:left; property in both divs.

  2. Add display:inline-block; property.

  3. Add display:flex; property in parent div.

How to know if an object has an attribute in Python

hasattr() is the right answer. What I want to add is that hasattr() can also be used well in conjunction with assert (to avoid unnecessary if statements and make the code more readable):

assert hasattr(a, 'property'), 'object lacks property' 

As stated in another answer on SO: Asserts should be used to test conditions that should never happen. The purpose is to crash early in the case of a corrupt program state.

How come I can't remove the blue textarea border in Twitter Bootstrap?

textarea:hover,
input:hover,
textarea:active,
input:active,
textarea:focus,
input:focus
{
    outline: 0px !important;
    border: none!important;
}

*use border:none; instead of outline because the focus line is a border not a outline.

Microsoft.ACE.OLEDB.12.0 is not registered

The easiest fix for me was to change SQL Agent job to run in 32-bit runtime. Go to SQL Job > right click properties > step > edit(step) > Execution option tab > Use 32 bit runtime

screenshot

c# open file with default application and parameters

this should be close!

public static void OpenWithDefaultProgram(string path)
{
    Process fileopener = new Process();
    fileopener.StartInfo.FileName = "explorer";
    fileopener.StartInfo.Arguments = "\"" + path + "\"";
    fileopener.Start();
}

Violation Long running JavaScript task took xx ms

If you're using Chrome Canary (or Beta), just check the 'Hide Violations' option.

Hide Violations Checkbox in Chrome 56 Console

CSS:Defining Styles for input elements inside a div

Like this.

.divContainer input[type="text"] {
  width:150px;
}
.divContainer input[type="radio"] {
  width:20px;
}

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

I have python2.7 installed via brew and the following solved my problem

brew install numpy

It installs python3, but it still works and sets it up for 2.7 as well.

Detect click outside React component

Typescript with Hooks

Note: I'm using React version 16.3, with React.createRef. For other versions use the ref callback.

Dropdown component:

interface DropdownProps {
 ...
};

export const Dropdown: React.FC<DropdownProps> () {
  const ref: React.RefObject<HTMLDivElement> = React.createRef();
  
  const handleClickOutside = (event: MouseEvent) => {
    if (ref && ref !== null) {
      const cur = ref.current;
      if (cur && !cur.contains(event.target as Node)) {
        // close all dropdowns
      }
    }
  }

  useEffect(() => {
    // Bind the event listener
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener("mousedown", handleClickOutside);
    };
  });

  return (
    <div ref={ref}>
        ...
    </div>
  );
}

jQuery - hashchange event

There is a hashchange plug-in which wraps up the functionality and cross browser issues available here.

How to reference image resources in XAML?

One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.

Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:UI.Images" 

Set your Image source like this:

<Image Source={Binding {x:Static UI:Resources.Search}} /> where 'Search' is name of the resource.

How to serialize object to CSV file?

Though its very late reply, I have faced this problem of exporting java entites to CSV, EXCEL etc in various projects, Where we need to provide export feature on UI.

I have created my own light weight framework. It works with any Java Beans, You just need to add annotations on fields you want to export to CSV, Excel etc.

Link: https://github.com/abhisoni96/dev-tools

Summernote image upload

This code worked well with new version (v0.8.12) (2019-05-21)

$('#summernote').summernote({
        callbacks: {
            onImageUpload: function(files) {
                for(let i=0; i < files.length; i++) {
                    $.upload(files[i]);
                }
            }
        },
        height: 500,
    });

    $.upload = function (file) {
        let out = new FormData();
        out.append('file', file, file.name);

        $.ajax({
            method: 'POST',
            url: 'upload.php',
            contentType: false,
            cache: false,
            processData: false,
            data: out,
            success: function (img) {
                $('#summernote').summernote('insertImage', img);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(textStatus + " " + errorThrown);
            }
        });
    };

PHP Code (upload.php)

if ($_FILES['file']['name']) {
 if (!$_FILES['file']['error']) {
    $name = md5(rand(100, 200));
    $ext = explode('.', $_FILES['file']['name']);
    $filename = $name . '.' . $ext[1];
    $destination = 'images/' . $filename; //change this directory
    $location = $_FILES["file"]["tmp_name"];
    move_uploaded_file($location, $destination);
    echo 'images/' . $filename;//change this URL
 }
 else
 {
  echo  $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
 }
}

Installing MySQL Python on Mac OS X

I used PyMySQL instead and its working fine!

sudo easy_install-3.7 pymysql

Value Change Listener to JTextField

textBoxName.getDocument().addDocumentListener(new DocumentListener() {
   @Override
   public void insertUpdate(DocumentEvent e) {
       onChange();
   }

   @Override
   public void removeUpdate(DocumentEvent e) {
      onChange();
   }

   @Override
   public void changedUpdate(DocumentEvent e) {
      onChange();
   } 
});

But I would not just parse anything the user (maybe on accident) touches on his keyboard into an Integer. You should catch any Exceptions thrown and make sure the JTextField is not empty.

Remove item from list based on condition

prods.Remove(prods.Single(p=>p.ID == 1));

you can't modify collection in foreach, as Vincent suggests

"The page you are requesting cannot be served because of the extension configuration." error message

Related to Server 2016, I should add:

  1. Run this command: aspnet_regiis -lv from this dir: C:\Windows\Microsoft.NET\Framework\v2.0.50727\ This gives you the best view of what is going on

  2. On Server 2016, installing .net and iis out of sequence does not seem to be a problem.

  3. What is more likely to be a problem on Server 2016 is simply that asp.net is not installed on the machine.