Programs & Examples On #Accesscontrolexception

An exception that occurs when trying to access an object for which you don't have the correct security authorization. For example, trying to access a file that doesn't allow read access by your user.

java.security.AccessControlException: Access denied (java.io.FilePermission

Within your <jre location>\lib\security\java.policy try adding:

grant { permission java.security.AllPermission; };

And see if it allows you. If so, you will have to add more granular permissions.

See:

Java 8 Documentation for java.policy files

and

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html

Compile c++14-code with g++

Follow the instructions at https://gist.github.com/application2000/73fd6f4bf1be6600a2cf9f56315a2d91 to set up the gcc version you need - gcc 5 or gcc 6 - on Ubuntu 14.04. The instructions include configuring update-alternatives to allow you to switch between versions as you need to.

C++ compiling on Windows and Linux: ifdef switch

I know it is not answer but added if someone looking same in Qt

In Qt

https://wiki.qt.io/Get-OS-name-in-Qt

QString Get::osName()
{
#if defined(Q_OS_ANDROID)
    return QLatin1String("android");
#elif defined(Q_OS_BLACKBERRY)
    return QLatin1String("blackberry");
#elif defined(Q_OS_IOS)
    return QLatin1String("ios");
#elif defined(Q_OS_MAC)
    return QLatin1String("osx");
#elif defined(Q_OS_WINCE)
    return QLatin1String("wince");
#elif defined(Q_OS_WIN)
    return QLatin1String("windows");
#elif defined(Q_OS_LINUX)
    return QLatin1String("linux");
#elif defined(Q_OS_UNIX)
    return QLatin1String("unix");
#else
    return QLatin1String("unknown");
#endif
}

How do I remove all null and empty string values from an object?

There is a very simple way to remove NULL values from JSON object. By default JSON object includes NULL values. Following can be used to remove NULL from JSON string

JsonConvert.SerializeObject(yourClassObject, new JsonSerializerSettings() {
                                       NullValueHandling = NullValueHandling.Ignore})) 

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

How to use code to open a modal in Angular 2?

Include jQuery as usual inside script tags in index.html.

After all the imports but before declaring @Component, add:

declare var $: any;

Now you are free to use jQuery anywhere in your Angular 2 TypeScript code:

$("#myModal").modal('show');

Reference: https://stackoverflow.com/a/38246116/2473022

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

The configuration here is working for me:

configurations {
    customProvidedRuntime
}

dependencies {
    compile(
        // Spring Boot dependencies
    )

    customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}

war {
    classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}

springBoot {
    providedConfiguration = "customProvidedRuntime"
}

Where is HttpContent.ReadAsAsync?

I have the same problem, so I simply get JSON string and deserialize to my class:

HttpResponseMessage response = await client.GetAsync("Products");
//get data as Json string 
string data = await response.Content.ReadAsStringAsync();
//use JavaScriptSerializer from System.Web.Script.Serialization
JavaScriptSerializer JSserializer = new JavaScriptSerializer();
//deserialize to your class
products = JSserializer.Deserialize<List<Product>>(data);

Permission denied on CopyFile in VBS

It's worth checking task manager for any stray wscript.exe tasks that are stuck. It could be one of those that's blocking access to the file.

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

What is the difference between HTTP and REST?

Not quite...

http://en.wikipedia.org/wiki/Representational_State_Transfer

REST was initially described in the context of HTTP, but is not limited to that protocol. RESTful architectures can be based on other Application Layer protocols if they already provide a rich and uniform vocabulary for applications based on the transfer of meaningful representational state. RESTful applications maximise the use of the pre-existing, well-defined interface and other built-in capabilities provided by the chosen network protocol, and minimise the addition of new application-specific features on top of it.

http://www.looselycoupled.com/glossary/SOAP

(Simple Object Access Protocol) The standard for web services messages. Based on XML, SOAP defines an envelope format and various rules for describing its contents. Seen (with WSDL and UDDI) as one of the three foundation standards of web services, it is the preferred protocol for exchanging web services, but by no means the only one; proponents of REST say that it adds unnecessary complexity.

How to get parameter on Angular2 route in Angular way?

Update: Sep 2019

As a few people have mentioned, the parameters in paramMap should be accessed using the common MapAPI:

To get a snapshot of the params, when you don't care that they may change:

this.bankName = this.route.snapshot.paramMap.get('bank');

To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)

this.route.paramMap.subscribe( paramMap => {
    this.bankName = paramMap.get('bank');
})

Update: Aug 2017

Since Angular 4, params have been deprecated in favor of the new interface paramMap. The code for the problem above should work if you simply substitute one for the other.

Original Answer

If you inject ActivatedRoute in your component, you'll be able to extract the route parameters

    import {ActivatedRoute} from '@angular/router';
    ...
    
    constructor(private route:ActivatedRoute){}
    bankName:string;
    
    ngOnInit(){
        // 'bank' is the name of the route parameter
        this.bankName = this.route.snapshot.params['bank'];
    }

If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:

    ngOnInit(){
        this.route.params.subscribe( params =>
            this.bankName = params['bank'];
        )
    }

For the docs, including the differences between the two check out this link and search for "activatedroute"

Change label text using JavaScript

Using .innerText should work.

document.getElementById('lbltipAddedComment').innerText = 'your tip has been submitted!';

What is the proper way to URL encode Unicode characters?

IRI (RFC 3987) is the latest standard that replaces the URI/URL (RFC 3986 and older) standards. URI/URL do not natively support Unicode (well, RFC 3986 adds provisions for future URI/URL-based protocols to support it, but does not update past RFCs). The "%uXXXX" scheme is a non-standard extension to allow Unicode in some situations, but is not universally implemented by everyone. IRI, on the other hand, fully supports Unicode, and requires that text be encoded as UTF-8 before then being percent-encoded.

Flash CS4 refuses to let go

Flash still has the ASO file, which is the compiled byte code for your classes. On Windows, you can see the ASO files here:

C:\Documents and Settings\username\Local Settings\Application Data\Adobe\Flash CS4\en\Configuration\Classes\aso

On a Mac, the directory structure is similar in /Users/username/Library/Application Support/


You can remove those files by hand, or in Flash you can select Control->Delete ASO files to remove them.

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

Get Memory Usage in Android

Based on the previous answers and personnal experience, here is the code I use to monitor CPU use. The code of this class is written in pure Java.

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Utilities available only on Linux Operating System.
 * 
 * <p>
 * A typical use is to assign a thread to CPU monitoring:
 * </p>
 * 
 * <pre>
 * &#064;Override
 * public void run() {
 *  while (CpuUtil.monitorCpu) {
 * 
 *      LinuxUtils linuxUtils = new LinuxUtils();
 * 
 *      int pid = android.os.Process.myPid();
 *      String cpuStat1 = linuxUtils.readSystemStat();
 *      String pidStat1 = linuxUtils.readProcessStat(pid);
 * 
 *      try {
 *          Thread.sleep(CPU_WINDOW);
 *      } catch (Exception e) {
 *      }
 * 
 *      String cpuStat2 = linuxUtils.readSystemStat();
 *      String pidStat2 = linuxUtils.readProcessStat(pid);
 * 
 *      float cpu = linuxUtils.getSystemCpuUsage(cpuStat1, cpuStat2);
 *      if (cpu &gt;= 0.0f) {
 *          _printLine(mOutput, &quot;total&quot;, Float.toString(cpu));
 *      }
 * 
 *      String[] toks = cpuStat1.split(&quot; &quot;);
 *      long cpu1 = linuxUtils.getSystemUptime(toks);
 * 
 *      toks = cpuStat2.split(&quot; &quot;);
 *      long cpu2 = linuxUtils.getSystemUptime(toks);
 * 
 *      cpu = linuxUtils.getProcessCpuUsage(pidStat1, pidStat2, cpu2 - cpu1);
 *      if (cpu &gt;= 0.0f) {
 *          _printLine(mOutput, &quot;&quot; + pid, Float.toString(cpu));
 *      }
 * 
 *      try {
 *          synchronized (this) {
 *              wait(CPU_REFRESH_RATE);
 *          }
 *      } catch (InterruptedException e) {
 *          e.printStackTrace();
 *          return;
 *      }
 *  }
 * 
 *  Log.i(&quot;THREAD CPU&quot;, &quot;Finishing&quot;);
 * }
 * </pre>
 */
public final class LinuxUtils {

    // Warning: there appears to be an issue with the column index with android linux:
    // it was observed that on most present devices there are actually
    // two spaces between the 'cpu' of the first column and the value of 
    // the next column with data. The thing is the index of the idle 
    // column should have been 4 and the first column with data should have index 1. 
    // The indexes defined below are coping with the double space situation.
    // If your file contains only one space then use index 1 and 4 instead of 2 and 5.
    // A better way to deal with this problem may be to use a split method 
    // not preserving blanks or compute an offset and add it to the indexes 1 and 4.

    private static final int FIRST_SYS_CPU_COLUMN_INDEX = 2;

    private static final int IDLE_SYS_CPU_COLUMN_INDEX = 5;

    /** Return the first line of /proc/stat or null if failed. */
    public String readSystemStat() {

        RandomAccessFile reader = null;
        String load = null;

        try {
            reader = new RandomAccessFile("/proc/stat", "r");
            load = reader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            Streams.close(reader);
        }

        return load;
    }

    /**
     * Compute and return the total CPU usage, in percent.
     * 
     * @param start
     *            first content of /proc/stat. Not null.
     * @param end
     *            second content of /proc/stat. Not null.
     * @return 12.7 for a CPU usage of 12.7% or -1 if the value is not
     *         available.
     * @see {@link #readSystemStat()}
     */
    public float getSystemCpuUsage(String start, String end) {
        String[] stat = start.split("\\s");
        long idle1 = getSystemIdleTime(stat);
        long up1 = getSystemUptime(stat);

        stat = end.split("\\s");
        long idle2 = getSystemIdleTime(stat);
        long up2 = getSystemUptime(stat);

        // don't know how it is possible but we should care about zero and
        // negative values.
        float cpu = -1f;
        if (idle1 >= 0 && up1 >= 0 && idle2 >= 0 && up2 >= 0) {
            if ((up2 + idle2) > (up1 + idle1) && up2 >= up1) {
                cpu = (up2 - up1) / (float) ((up2 + idle2) - (up1 + idle1));
                cpu *= 100.0f;
            }
        }

        return cpu;
    }

    /**
     * Return the sum of uptimes read from /proc/stat.
     * 
     * @param stat
     *            see {@link #readSystemStat()}
     */
    public long getSystemUptime(String[] stat) {
        /*
         * (from man/5/proc) /proc/stat kernel/system statistics. Varies with
         * architecture. Common entries include: cpu 3357 0 4313 1362393
         * 
         * The amount of time, measured in units of USER_HZ (1/100ths of a
         * second on most architectures, use sysconf(_SC_CLK_TCK) to obtain the
         * right value), that the system spent in user mode, user mode with low
         * priority (nice), system mode, and the idle task, respectively. The
         * last value should be USER_HZ times the second entry in the uptime
         * pseudo-file.
         * 
         * In Linux 2.6 this line includes three additional columns: iowait -
         * time waiting for I/O to complete (since 2.5.41); irq - time servicing
         * interrupts (since 2.6.0-test4); softirq - time servicing softirqs
         * (since 2.6.0-test4).
         * 
         * Since Linux 2.6.11, there is an eighth column, steal - stolen time,
         * which is the time spent in other operating systems when running in a
         * virtualized environment
         * 
         * Since Linux 2.6.24, there is a ninth column, guest, which is the time
         * spent running a virtual CPU for guest operating systems under the
         * control of the Linux kernel.
         */

        // with the following algorithm, we should cope with all versions and
        // probably new ones.
        long l = 0L;

        for (int i = FIRST_SYS_CPU_COLUMN_INDEX; i < stat.length; i++) {
            if (i != IDLE_SYS_CPU_COLUMN_INDEX ) { // bypass any idle mode. There is currently only one.
                try {
                    l += Long.parseLong(stat[i]);
                } catch (NumberFormatException ex) {
                    ex.printStackTrace();
                    return -1L;
                }
            }
        }

        return l;
    }

    /**
     * Return the sum of idle times read from /proc/stat.
     * 
     * @param stat
     *            see {@link #readSystemStat()}
     */
    public long getSystemIdleTime(String[] stat) {
        try {
            return Long.parseLong(stat[IDLE_SYS_CPU_COLUMN_INDEX]);
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }

        return -1L;
    }

    /** Return the first line of /proc/pid/stat or null if failed. */
    public String readProcessStat(int pid) {

        RandomAccessFile reader = null;
        String line = null;

        try {
            reader = new RandomAccessFile("/proc/" + pid + "/stat", "r");
            line = reader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            Streams.close(reader);
        }

        return line;
    }

    /**
     * Compute and return the CPU usage for a process, in percent.
     * 
     * <p>
     * The parameters {@code totalCpuTime} is to be the one for the same period
     * of time delimited by {@code statStart} and {@code statEnd}.
     * </p>
     * 
     * @param start
     *            first content of /proc/pid/stat. Not null.
     * @param end
     *            second content of /proc/pid/stat. Not null.
     * @return the CPU use in percent or -1f if the stats are inverted or on
     *         error
     * @param uptime
     *            sum of user and kernel times for the entire system for the
     *            same period of time.
     * @return 12.7 for a cpu usage of 12.7% or -1 if the value is not available
     *         or an error occurred.
     * @see {@link #readProcessStat(int)}
     */
    public float getProcessCpuUsage(String start, String end, long uptime) {

        String[] stat = start.split("\\s");
        long up1 = getProcessUptime(stat);

        stat = end.split("\\s");
        long up2 = getProcessUptime(stat);

        float ret = -1f;
        if (up1 >= 0 && up2 >= up1 && uptime > 0.) {
            ret = 100.f * (up2 - up1) / (float) uptime;
        }

        return ret;
    }

    /**
     * Decode the fields of the file {@code /proc/pid/stat} and return (utime +
     * stime)
     * 
     * @param stat
     *            obtained with {@link #readProcessStat(int)}
     */
    public long getProcessUptime(String[] stat) {
        return Long.parseLong(stat[14]) + Long.parseLong(stat[15]);
    }

    /**
     * Decode the fields of the file {@code /proc/pid/stat} and return (cutime +
     * cstime)
     * 
     * @param stat
     *            obtained with {@link #readProcessStat(int)}
     */
    public long getProcessIdleTime(String[] stat) {
        return Long.parseLong(stat[16]) + Long.parseLong(stat[17]);
    }

    /**
     * Return the total CPU usage, in percent.
     * <p>
     * The call is blocking for the time specified by elapse.
     * </p>
     * 
     * @param elapse
     *            the time in milliseconds between reads.
     * @return 12.7 for a CPU usage of 12.7% or -1 if the value is not
     *         available.
     */
    public float syncGetSystemCpuUsage(long elapse) {

        String stat1 = readSystemStat();
        if (stat1 == null) {
            return -1.f;
        }

        try {
            Thread.sleep(elapse);
        } catch (Exception e) {
        }

        String stat2 = readSystemStat();
        if (stat2 == null) {
            return -1.f;
        }

        return getSystemCpuUsage(stat1, stat2);
    }

    /**
     * Return the CPU usage of a process, in percent.
     * <p>
     * The call is blocking for the time specified by elapse.
     * </p>
     * 
     * @param pid
     * @param elapse
     *            the time in milliseconds between reads.
     * @return 6.32 for a CPU usage of 6.32% or -1 if the value is not
     *         available.
     */
    public float syncGetProcessCpuUsage(int pid, long elapse) {

        String pidStat1 = readProcessStat(pid);
        String totalStat1 = readSystemStat();
        if (pidStat1 == null || totalStat1 == null) {
            return -1.f;
        }

        try {
            Thread.sleep(elapse);
        } catch (Exception e) {
            e.printStackTrace();
            return -1.f;
        }

        String pidStat2 = readProcessStat(pid);
        String totalStat2 = readSystemStat();
        if (pidStat2 == null || totalStat2 == null) {
            return -1.f;
        }

        String[] toks = totalStat1.split("\\s");
        long cpu1 = getSystemUptime(toks);

        toks = totalStat2.split("\\s");
        long cpu2 = getSystemUptime(toks);

        return getProcessCpuUsage(pidStat1, pidStat2, cpu2 - cpu1);
    }

}

There are several ways of exploiting this class. You can call either syncGetSystemCpuUsage or syncGetProcessCpuUsage but each is blocking the calling thread. Since a common issue is to monitor the total CPU usage and the CPU use of the current process at the same time, I have designed a class computing both of them. That class contains a dedicated thread. The output management is implementation specific and you need to code your own.

The class can be customized by a few means. The constant CPU_WINDOW defines the depth of a read, i.e. the number of milliseconds between readings and computing of the corresponding CPU load. CPU_REFRESH_RATE is the time between each CPU load measurement. Do not set CPU_REFRESH_RATE to 0 because it will suspend the thread after the first read.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

import android.app.Application;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import my.app.LinuxUtils;
import my.app.Streams;
import my.app.TestReport;
import my.app.Utils;

public final class CpuUtil {

    private static final int CPU_WINDOW = 1000;

    private static final int CPU_REFRESH_RATE = 100; // Warning: anything but > 0

    private static HandlerThread handlerThread;

    private static TestReport output;

    static {
        output = new TestReport();
        output.setDateFormat(Utils.getDateFormat(Utils.DATE_FORMAT_ENGLISH));
    }

    private static boolean monitorCpu;

    /**
     * Construct the class singleton. This method should be called in
     * {@link Application#onCreate()}
     * 
     * @param dir
     *            the parent directory
     * @param append
     *            mode
     */
    public static void setOutput(File dir, boolean append) {
        try {
            File file = new File(dir, "cpu.txt");
            output.setOutputStream(new FileOutputStream(file, append));
            if (!append) {
                output.println(file.getAbsolutePath());
                output.newLine(1);

                // print header
                _printLine(output, "Process", "CPU%");

                output.flush();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /** Start CPU monitoring */
    public static boolean startCpuMonitoring() {
        CpuUtil.monitorCpu = true;

        handlerThread = new HandlerThread("CPU monitoring"); //$NON-NLS-1$
        handlerThread.start();

        Handler handler = new Handler(handlerThread.getLooper());
        handler.post(new Runnable() {

            @Override
            public void run() {
                while (CpuUtil.monitorCpu) {

                    LinuxUtils linuxUtils = new LinuxUtils();

                    int pid = android.os.Process.myPid();
                    String cpuStat1 = linuxUtils.readSystemStat();
                    String pidStat1 = linuxUtils.readProcessStat(pid);

                    try {
                        Thread.sleep(CPU_WINDOW);
                    } catch (Exception e) {
                    }

                    String cpuStat2 = linuxUtils.readSystemStat();
                    String pidStat2 = linuxUtils.readProcessStat(pid);

                    float cpu = linuxUtils
                            .getSystemCpuUsage(cpuStat1, cpuStat2);
                    if (cpu >= 0.0f) {
                        _printLine(output, "total", Float.toString(cpu));
                    }

                    String[] toks = cpuStat1.split(" ");
                    long cpu1 = linuxUtils.getSystemUptime(toks);

                    toks = cpuStat2.split(" ");
                    long cpu2 = linuxUtils.getSystemUptime(toks);

                    cpu = linuxUtils.getProcessCpuUsage(pidStat1, pidStat2,
                            cpu2 - cpu1);
                    if (cpu >= 0.0f) {
                        _printLine(output, "" + pid, Float.toString(cpu));
                    }

                    try {
                        synchronized (this) {
                            wait(CPU_REFRESH_RATE);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        return;
                    }
                }

                Log.i("THREAD CPU", "Finishing");
            }

        });

        return CpuUtil.monitorCpu;
    }

    /** Stop CPU monitoring */
    public static void stopCpuMonitoring() {
        if (handlerThread != null) {
            monitorCpu = false;
            handlerThread.quit();
            handlerThread = null;
        }
    }

    /** Dispose of the object and release the resources allocated for it */
    public void dispose() {

        monitorCpu = false;

        if (output != null) {
            OutputStream os = output.getOutputStream();
            if (os != null) {
                Streams.close(os);
                output.setOutputStream(null);
            }

            output = null;
        }
    }

    private static void _printLine(TestReport output, String process, String cpu) {
        output.stampln(process + ";" + cpu);
    }

}

error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app

I came across this issue as well. What I did was force kill the app on my device, then I opened up another console and ran

react-native start

and then I opened the app again from my device and it started working again.

EDIT: If you are using an android device via USB and have unplugged it or your computer went to sleep, you may have to first run

adb reverse tcp:8081 tcp:8081

How to echo out table rows from the db (php)

 $result= mysql_query("SELECT * FROM MY_TABLE");
 while($row = mysql_fetch_array($result)){
      echo $row['whatEverColumnName'];
 }

How to make a whole 'div' clickable in html and css without JavaScript?

we are using like this

     <label for="1">
<div class="options">
<input type="radio" name="mem" id="1" value="1" checked="checked"/>option one
    </div>
</label>
   <label for="2"> 
<div class="options">
 <input type="radio" name="mem" id="2" value="1" checked="checked"/>option two
</div></label>

using

  <label for="1">

tag and catching is with

id=1

hope this helps.

How to convert all text to lowercase in Vim

Many ways to skin a cat... here's the way I just posted about:


:%s/[A-Z]/\L&/g

Likewise for upper case:


:%s/[a-z]/\U&/g

I prefer this way because I am using this construct (:%s/[pattern]/replace/g) all the time so it's more natural.

Python: Split a list into sub-lists based on index ranges

If you already know the indices:

list1 = ['x','y','z','a','b','c','d','e','f','g']
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]

Note that we're adding +1 to the end to make the range inclusive...

sprintf like functionality in Python

If you want something like the python3 print function but to a string:

def sprint(*args, **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, file=sio)
    return sio.getvalue()
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}\n"

or without the '\n' at the end:

def sprint(*args, end='', **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, end=end, file=sio)
    return sio.getvalue()
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}"

Using iFrames In ASP.NET

try this

<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>

Expose this iframe in the master page's codebehind:

public HtmlControl iframe
{
get
{
return this.myIframe;
}
}

Add the MasterType directive for the content page to strongly typed Master Page.

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>

In code behind

protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}

Use PPK file in Mac Terminal to connect to remote connection over SSH

There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.

Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.

Copy the PEM file to your Mac and set it to be read-only by your user:

chmod 400 <private-key-filename>.pem

Then you should be able to use ssh to connect to your remote server

ssh -i <private-key-filename>.pem username@hostname

How to gzip all files in all sub-directories into one compressed file in bash

@amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU system, they can do this:

tar cvf - folderToCompress | gzip > compressFileName

To expand the archive:

zcat compressFileName | tar xvf -

Fastest way to count exact number of rows in a very large table?

Is there a better way to get the EXACT count of the number of rows of a table?

To answer your question simply, No.

If you need a DBMS independent way of doing this, the fastest way will always be:

SELECT COUNT(*) FROM TableName

Some DBMS vendors may have quicker ways which will work for their systems only. Some of these options are already posted in other answers.

COUNT(*) should be optimized by the DBMS (at least any PROD worthy DB) anyway, so don't try to bypass their optimizations.

On a side note:
I am sure many of your other queries also take a long time to finish because of your table size. Any performance concerns should probably be addressed by thinking about your schema design with speed in mind. I realize you said that it is not an option to change but it might turn out that 10+ minute queries aren't an option either. 3rd NF is not always the best approach when you need speed, and sometimes data can be partitioned in several tables if the records don't have to be stored together. Something to think about...

Decoding base64 in batch

Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL

I'm not sure what version of Windows introduced this command.

To encode a file:

certutil -encode inputFileName encodedOutputFileName

To decode a file:

certutil -decode encodedInputFileName decodedOutputFileName

There are a number of available verbs and options available to CERTUTIL.

To get a list of nearly all available verbs:

certutil -?

To get help on a particular verb (-encode for example):

certutil -encode -?

To get complete help for nearly all verbs:

certutil -v -?

Mysteriously, the -encodehex verb is not listed with certutil -? or certutil -v -?. But it is described using certutil -encodehex -?. It is another handy function :-)

Update

Regarding David Morales' comment, there is a poorly documented type option to the -encodehex verb that allows creation of base64 strings without header or footer lines.

certutil [Options] -encodehex inFile outFile [type]

A type of 1 will yield base64 without the header or footer lines.

See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.

Not investigated, but the -decodehex verb also has an optional trailing type argument.

Get clicked element using jQuery on event?

A simple way is to pass the data attribute to your HTML tag.

Example:

<div data-id='tagid' class="clickElem"></div>

<script>
$(document).on("click",".appDetails", function () {
   var clickedBtnID = $(this).attr('data');
   alert('you clicked on button #' + clickedBtnID);
});
</script>

Change default date time format on a single database in SQL Server

If this really is a QA issue and you can't change the code. Setup a new server instance on the machine and setup the language as "British English"

how to get the host url using javascript from the current page

Keep in mind before use window and location

1.use window and location in client side render (Note:don't use in ssr)

window.location.host; 

or

var host = window.location.protocol + "//" + window.location.host;

2.server side render

if your using nuxt.js(vue) or next.js(react) refer docs

For nuxt js Framework

req.headers.host

code:

async asyncData ({ req, res }) {
        if (process.server) {
         return { host: req.headers.host }
        }

Code In router:

export function createRouter (ssrContext) {



console.log(ssrContext.req.headers.host)   
      return new Router({
        middleware: 'route',
        routes:checkRoute(ssrContext),
        mode: 'history'
      })
    }

For next.js framework

Home.getInitalProps = async(context) => {
   const { req, query, res, asPath, pathname } = context;
   if (req) {
      let host = req.headers.host // will give you localhost:3000
     }
  }

For node.js users

var os = require("os");
var hostname = os.hostname();

or

request.headers.host

For laravel users

public function yourControllerFun(Request $request) {

    $host = $request->getHttpHost();

  

    dd($host);

}

or

directly use in web.php

Request::getHost();

Note :

both csr and ssr app you manually check example ssr render

if(req.server){
host=req.host;
}
if(req.client){
host=window.location.host; 
}

Finding CN of users in Active Directory

Most common AD default design is to have a container, cn=users just after the root of the domain. Thus a DN might be:

cn=admin,cn=users,DC=domain,DC=company,DC=com

Also, you might have sufficient rights in an LDAP bind to connect anonymously, and query for (cn=admin). If so, you should get the full DN back in that query.

Use Font Awesome Icon in Placeholder

Ignoring the jQuery this can be done using ::placeholder of an input element.

<form role="form">
  <div class="form-group">
    <input type="text" class="form-control name" placeholder="&#xF002;"/>
  </div>
</form>

The css part

input.name::placeholder{ font-family:fontAwesome; font-size:[size needed]; color:[placeholder color needed] }

input.name{ font-family:[font family you want to specify] }

THE BEST PART: You can have different font family for placeholder and text

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

Just log out of phpMyAdmin, that is all you need to do

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

How can I customize the tab-to-space conversion factor?

When using TypeScript, the default tab width is always two regardless of what it says in the toolbar. You have to set "prettier.tabWidth" in your user settings to change it.

Ctrl + P, Type ? user settings, add:

"prettier.tabWidth": 4

finding first day of the month in python

Use dateutil.

from datetime import date
from dateutil.relativedelta import relativedelta

today = date.today()
first_day = today.replace(day=1)
if today.day > 25:
    print(first_day + relativedelta(months=1))
else:
    print(first_day)

Refresh DataGridView when updating data source

Well, it doesn't get much better than that. Officially, you should use

dataGridView1.DataSource = typeof(List); 
dataGridView1.DataSource = itemStates;

It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.

How to center links in HTML

Try doing a nav element with a ul element. Mine has a main above but I don't think you need it.

<main>
<nav>
<ul><li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>

The code is something like this.
When ever I put in the code it wouldn't work right so you need to fill in the blank,
then center it.

main
nav
ul> li> a>: href="link of choice":name of link:/a>

Put search icon near textbox using bootstrap

Adding a class with a width of 90% to your input element and adding the following input-icon class to your span would achieve what you want I think.

.input { width: 90%; }
.input-icon {
    display: inline-block;
    height: 22px;
    width: 22px;
    line-height: 22px;
    text-align: center;
    color: #000;
    font-size: 12px;
    font-weight: bold;
    margin-left: 4px;
}

EDIT Per dan's suggestion, it would not be wise to use .input as the class name, some more specific would be advised. I was simply using .input as a generic placeholder for your css

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

I like the WMILinq solution. While not exactly the solution to your problem, find below a taste of it :

using (WmiContext context = new WmiContext(@"\\.")) {

  context.ManagementScope.Options.Impersonation = ImpersonationLevel.Impersonate;
  context.Log = Console.Out;

  var dnss = from nic in context.Source<Win32_NetworkAdapterConfiguration>()
          where nic.IPEnabled
          select nic;

  var ips = from s in dnss.SelectMany(dns => dns.DNSServerSearchOrder)
          select IPAddress.Parse(s);
}  

http://www.codeplex.com/linq2wmi

How do I retrieve query parameters in Spring Boot?

I was interested in this as well and came across some examples on the Spring Boot site.

   // get with query string parameters e.g. /system/resource?id="rtze1cd2"&person="sam smith" 
// so below the first query parameter id is the variable and name is the variable
// id is shown below as a RequestParam
    @GetMapping("/system/resource")
    // this is for swagger docs
    @ApiOperation(value = "Get the resource identified by id and person")
    ResponseEntity<?> getSomeResourceWithParameters(@RequestParam String id, @RequestParam("person") String name) {

        InterestingResource resource = getMyInterestingResourc(id, name);
        logger.info("Request to get an id of "+id+" with a name of person: "+name);

        return new ResponseEntity<Object>(resource, HttpStatus.OK);
    }

See here also

ReactNative: how to center text?

You can use alignSelf property on Text component

{ alignSelf : "center" }

java.util.regex - importance of Pattern.compile()?

Pre-compiling the regex increases the speed. Re-using the Matcher gives you another slight speedup. If the method gets called frequently say gets called within a loop, the overall performace will certainly go up.

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

Slightly different option usually works for me:

  1. "mvn eclipse:eclipse" for this project in the command line.
  2. "Refresh/F5" this project in eclipse.

That's all, no need to re-import but need to have the terminal window handy.

How can I make a countdown with NSTimer?

In Swift 5.1 this will work:

var counter = 30

override func viewDidLoad() {
    super.viewDidLoad()

    Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}



@objc func updateCounter() {
    //example functionality
    if counter > 0 {
        print("\(counter) seconds to the end of the world")
        counter -= 1
    }
}

Declare variable MySQL trigger

Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.

For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.

INSERT ... SELECT Syntax.

Getting strings recognized as variable names in R

You found one answer, i.e. eval(parse()) . You can also investigate do.call() which is often simpler to implement. Keep in mind the useful as.name() tool as well, for converting strings to variable names.

HTML Drag And Drop On Mobile Devices

There is a new polyfill for translating touch events to drag-and-drop, such that HTML5 Drag And Drop is utilizable on mobile.

The polyfill was introduced by Bernardo Castilho on this post.

Here's a demo from that post.

The post also presents several considerations of the folyfill design.

Immutable vs Mutable types

The goal of this answer is to create a single place to find all the good ideas about how to tell if you are dealing with mutating/nonmutating (immutable/mutable), and where possible, what to do about it? There are times when mutation is undesirable and python's behavior in this regard can feel counter-intuitive to coders coming into it from other languages.

As per a useful post by @mina-gabriel:

Analyzing the above and combining w/ a post by @arrakëën:

What cannot change unexpectedly?

  • scalars (variable types storing a single value) do not change unexpectedly
    • numeric examples: int(), float(), complex()
  • there are some "mutable sequences":
    • str(), tuple(), frozenset(), bytes()

What can?

  • list like objects (lists, dictionaries, sets, bytearray())
  • a post on here also says classes and class instances but this may depend on what the class inherits from and/or how its built.

by "unexpectedly" I mean that programmers from other languages might not expect this behavior (with the exception or Ruby, and maybe a few other "Python like" languages).

Adding to this discussion:

This behavior is an advantage when it prevents you from accidentally populating your code with mutliple copies of memory-eating large data structures. But when this is undesirable, how do we get around it?

With lists, the simple solution is to build a new one like so:

list2 = list(list1)

with other structures ... the solution can be trickier. One way is to loop through the elements and add them to a new empty data structure (of the same type).

functions can mutate the original when you pass in mutable structures. How to tell?

  • There are some tests given on other comments on this thread but then there are comments indicating these tests are not full proof
  • object.function() is a method of the original object but only some of these mutate. If they return nothing, they probably do. One would expect .append() to mutate without testing it given its name. .union() returns the union of set1.union(set2) and does not mutate. When in doubt, the function can be checked for a return value. If return = None, it does not mutate.
  • sorted() might be a workaround in some cases. Since it returns a sorted version of the original, it can allow you to store a non-mutated copy before you start working on the original in other ways. However, this option assumes you don't care about the order of the original elements (if you do, you need to find another way). In contrast .sort() mutates the original (as one might expect).

Non-standard Approaches (in case helpful): Found this on github published under an MIT license:

  • github repository under: tobgu named: pyrsistent
  • What it is: Python persistent data structure code written to be used in place of core data structures when mutation is undesirable

For custom classes, @semicolon suggests checking if there is a __hash__ function because mutable objects should generally not have a __hash__() function.

This is all I have amassed on this topic for now. Other ideas, corrections, etc. are welcome. Thanks.

var.replace is not a function

You are not passing a string otherwise it would have a replace method. I hope you didnt type function trim(str) { return var.replace(blah); } instead of return str.replace.

Notice: Undefined offset: 0 in

This answer helped me https://stackoverflow.com/a/18880670/1821607 The reason of crush — index 0 wasn't set. Simple $array = $array + array(null) did the trick. Or you should check whether array element on index 0 is set via isset($array[0]). The second variant is the best approach for me.

Does --disable-web-security Work In Chrome Anymore?

This flag worked for me at v30.0.1599.101 m enter image description here

The warning "You are using an unsupported command-line flag" can be ignored. The flag still works (as of Chrome v86).

getting the X/Y coordinates of a mouse click on an image with jQuery

Take a look at http://jsfiddle.net/TroyAlford/ZZEk8/ for a working example of the below:

<img id='myImg' src='/my/img/link.gif' />

<script type="text/javascript">
    $(document).bind('click', function () {
        // Add a click-handler to the image.
        $('#myImg').bind('click', function (ev) {
            var $img = $(ev.target);

            var offset = $img.offset();
            var x = ev.clientX - offset.left;
            var y = ev.clientY - offset.top;

            alert('clicked at x: ' + x + ', y: ' + y);
        });
    });
</script>

Note that the above will get you the x and the y relative to the image's box - but will not correctly take into account margin, border and padding. These elements aren't actually part of the image, in your case - but they might be part of the element that you would want to take into account.

In this case, you should also use $div.outerWidth(true) - $div.width() and $div.outerHeight(true) - $div.height() to calculate the amount of margin / border / etc.

Your new code might look more like:

<img id='myImg' src='/my/img/link.gif' />

<script type="text/javascript">
    $(document).bind('click', function () {
        // Add a click-handler to the image.
        $('#myImg').bind('click', function (ev) {
            var $img = $(ev.target);

            var offset = $img.offset(); // Offset from the corner of the page.
            var xMargin = ($img.outerWidth() - $img.width()) / 2;
            var yMargin = ($img.outerHeight() - $img.height()) / 2;
            // Note that the above calculations assume your left margin is 
            // equal to your right margin, top to bottom, etc. and the same 
            // for borders.

            var x = (ev.clientX + xMargin) - offset.left;
            var y = (ev.clientY + yMargin) - offset.top;

            alert('clicked at x: ' + x + ', y: ' + y);
        });
    });
</script>

What's a "static method" in C#?

Static variable doesn't link with object of the class. It can be accessed using classname. All object of the class will share static variable.

By making function as static, It will restrict the access of that function within that file.

Hex to ascii string conversion

you need to take 2 (hex) chars at the same time... then calculate the int value and after that make the char conversion like...

char d = (char)intValue;

do this for every 2chars in the hex string

this works if the string chars are only 0-9A-F:

#include <stdio.h>
#include <string.h>

int hex_to_int(char c){
        int first = c / 16 - 3;
        int second = c % 16;
        int result = first*10 + second;
        if(result > 9) result--;
        return result;
}

int hex_to_ascii(char c, char d){
        int high = hex_to_int(c) * 16;
        int low = hex_to_int(d);
        return high+low;
}

int main(){
        const char* st = "48656C6C6F3B";
        int length = strlen(st);
        int i;
        char buf = 0;
        for(i = 0; i < length; i++){
                if(i % 2 != 0){
                        printf("%c", hex_to_ascii(buf, st[i]));
                }else{
                        buf = st[i];
                }
        }
}

UIAlertController custom font, size, color

A bit clunky, but this works for me right now to set background and text colors. I found it here.

UIView * firstView = alertController.view.subviews.firstObject;
    UIView * nextView = firstView.subviews.firstObject;
    nextView.backgroundColor = [UIColor blackColor];

Check/Uncheck a checkbox on datagridview

The code bellow allows the user to un-/check the checkboxes in the DataGridView, if the Cells are created in code

private void gvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gvData.Rows[e.RowIndex].Cells[0];

    if (chk.Value == chk.TrueValue)
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.FalseValue;
    }
    else
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.TrueValue;
    }

}

Trying to use Spring Boot REST to Read JSON String from POST

I think the simplest/handy way to consuming JSON is using a Java class that resembles your JSON: https://stackoverflow.com/a/6019761

But if you can't use a Java class you can use one of these two solutions.

Solution 1: you can do it receiving a Map<String, Object> from your controller:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object> payload) 
    throws Exception {

  System.out.println(payload);

}

Using your request:

curl -H "Accept: application/json" -H "Content-type: application/json" \
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/process

Solution 2: otherwise you can get the POST payload as a String:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST,
    consumes = "text/plain")
public void process(@RequestBody String payload) throws Exception {

  System.out.println(payload);

}

Then parse the string as you want. Note that must be specified consumes = "text/plain" on your controller. In this case you must change your request with Content-type: text/plain:

curl -H "Accept: application/json" -H "Content-type: text/plain" -X POST \
-d '{"name":"value"}' http://localhost:8080/myservice/process

Formatting ISODate from Mongodb

JavaScript's Date object supports the ISO date format, so as long as you have access to the date string, you can do something like this:

> foo = new Date("2012-07-14T01:00:00+01:00")
Sat, 14 Jul 2012 00:00:00 GMT
> foo.toTimeString()
'17:00:00 GMT-0700 (MST)'

If you want the time string without the seconds and the time zone then you can call the getHours() and getMinutes() methods on the Date object and format the time yourself.

Executing a shell script from a PHP script

I was struggling with this exact issue for three days. I had set permissions on the script to 755. I had been calling my script as follows.

<?php
   $outcome = shell_exec('/tmp/clearUp.sh');
   echo $outcome;
?>

My script was as follows.

#!bin/bash
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;

I was getting no output or feedback. The change I made to get the script to run was to add a cd to tmp inside the script:

#!bin/bash
cd /tmp;
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;

This was more by luck than judgement but it is now working perfectly. I hope this helps.

TypeError: window.initMap is not a function

The problem has to do with the async attribute in the script tag. The Callback Function is trying to call "initMap()" when it doesn't really exists by the time the request finished.

To solve this I placed the Goole Maps Api Script bellow the script where my initMap function was declared.

Hope this helps

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

BeanFactory vs ApplicationContext

To add onto what Miguel Ping answered, here is another section from the documentation that answers this as well:

Short version: use an ApplicationContext unless you have a really good reason for not doing so. For those of you that are looking for slightly more depth as to the 'but why' of the above recommendation, keep reading.

(posting this for any future Spring novices who might read this question)

Random strings in Python

random_name = lambda length: ''.join(random.sample(string.letters, length))

length must be <= len(string.letters) = 53. result example

   >>> [random_name(x) for x in range(1,20)]
['V', 'Rq', 'YtL', 'AmUF', 'loFdS', 'eNpRFy', 'iWFGtDz', 'ZTNgCvLA', 'fjUDXJvMP', 'EBrPcYKUvZ', 'GmxPKCnbfih', 'nSiNmCRktdWZ', 'VWKSsGwlBeXUr', 'i
stIFGTUlZqnav', 'bqfwgBhyTJMUEzF', 'VLXlPiQnhptZyoHq', 'BXWATvwLCUcVesFfk', 'jLngHmTBtoOSsQlezV', 'JOUhklIwDBMFzrTCPub']
>>> 

Enjoy. ;)

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

I may be out fishing here, but doesn't Tomcat by default open to port 8080? Try http://localhost:8080 instead.

Android; Check if file exists without creating a new one

public boolean FileExists(String fname) {
        File file = getBaseContext().getFileStreamPath(fname);
        return file.exists();
}

How to return value from Action()?

Use Func<T> rather than Action<T>.

Action<T> acts like a void method with parameter of type T, while Func<T> works like a function with no parameters and which returns an object of type T.

If you wish to give parameters to your function, use Func<TParameter1, TParameter2, ..., TReturn>.

svn : how to create a branch from certain revision of trunk

$ svn copy http://svn.example.com/repos/calc/trunk@192 \
   http://svn.example.com/repos/calc/branches/my-calc-branch \
   -m "Creating a private branch of /calc/trunk."

Where 192 is the revision you specify

You can find this information from the SVN Book, specifically here on the page about svn copy

How to pass an ArrayList to a varargs method parameter?

You can do:

getMap(locations.toArray(new WorldLocation[locations.size()]));

or

getMap(locations.toArray(new WorldLocation[0]));

or

getMap(new WorldLocation[locations.size()]);

@SuppressWarnings("unchecked") is needed to remove the ide warning.

How can I set the opacity or transparency of a Panel in WinForms?

Panel with opacity:

public class GlassyPanel : Panel
{
    const int WS_EX_TRANSPARENT = 0x20;  

    int opacity = 50;

    public int Opacity
    {
        get
        {
            return opacity;
        }
        set
        {
            if (value < 0 || value > 100) throw new ArgumentException("Value must be between 0 and 100");
            opacity = value;
        }
    }

    protected override CreateParams CreateParams
    {
        get
        {
            var cp = base.CreateParams;
            cp.ExStyle = cp.ExStyle | WS_EX_TRANSPARENT;

            return cp;
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        using (var b = new SolidBrush(Color.FromArgb(opacity * 255 / 100, BackColor)))
        {
            e.Graphics.FillRectangle(b, ClientRectangle);
        }

        base.OnPaint(e);
    }
}

Passing arguments to C# generic new() of templated type

Very old question, but new answer ;-)

The ExpressionTree version: (I think the fastests and cleanest solution)

Like Welly Tambunan said, "we could also use expression tree to build the object"

This will generate a 'constructor' (function) for the type/parameters given. It returns a delegate and accept the parameter types as an array of objects.

Here it is:

// this delegate is just, so you don't have to pass an object array. _(params)_
public delegate object ConstructorDelegate(params object[] args);

public static ConstructorDelegate CreateConstructor(Type type, params Type[] parameters)
{
    // Get the constructor info for these parameters
    var constructorInfo = type.GetConstructor(parameters);

    // define a object[] parameter
    var paramExpr = Expression.Parameter(typeof(Object[]));

    // To feed the constructor with the right parameters, we need to generate an array 
    // of parameters that will be read from the initialize object array argument.
    var constructorParameters = parameters.Select((paramType, index) =>
        // convert the object[index] to the right constructor parameter type.
        Expression.Convert(
            // read a value from the object[index]
            Expression.ArrayAccess(
                paramExpr,
                Expression.Constant(index)),
            paramType)).ToArray();

    // just call the constructor.
    var body = Expression.New(constructorInfo, constructorParameters);

    var constructor = Expression.Lambda<ConstructorDelegate>(body, paramExpr);
    return constructor.Compile();
}

Example MyClass:

public class MyClass
{
    public int TestInt { get; private set; }
    public string TestString { get; private set; }

    public MyClass(int testInt, string testString)
    {
        TestInt = testInt;
        TestString = testString;
    }
}

Usage:

// you should cache this 'constructor'
var myConstructor = CreateConstructor(typeof(MyClass), typeof(int), typeof(string));

// Call the `myConstructor` function to create a new instance.
var myObject = myConstructor(10, "test message");

enter image description here


Another example: passing the types as an array

var type = typeof(MyClass);
var args = new Type[] { typeof(int), typeof(string) };

// you should cache this 'constructor'
var myConstructor = CreateConstructor(type, args);

// Call the `myConstructor` fucntion to create a new instance.
var myObject = myConstructor(10, "test message");

DebugView of Expression

.Lambda #Lambda1<TestExpressionConstructor.MainWindow+ConstructorDelegate>(System.Object[] $var1) {
    .New TestExpressionConstructor.MainWindow+MyClass(
        (System.Int32)$var1[0],
        (System.String)$var1[1])
}

This is equivalent to the code that is generated:

public object myConstructor(object[] var1)
{
    return new MyClass(
        (System.Int32)var1[0],
        (System.String)var1[1]);
}

Small downside

All valuetypes parameters are boxed when they are passed like an object array.


Simple performance test:

private void TestActivator()
{
    Stopwatch sw = Stopwatch.StartNew();
    for (int i = 0; i < 1024 * 1024 * 10; i++)
    {
        var myObject = Activator.CreateInstance(typeof(MyClass), 10, "test message");
    }
    sw.Stop();
    Trace.WriteLine("Activator: " + sw.Elapsed);
}

private void TestReflection()
{
    var constructorInfo = typeof(MyClass).GetConstructor(new[] { typeof(int), typeof(string) });

    Stopwatch sw = Stopwatch.StartNew();
    for (int i = 0; i < 1024 * 1024 * 10; i++)
    {
        var myObject = constructorInfo.Invoke(new object[] { 10, "test message" });
    }

    sw.Stop();
    Trace.WriteLine("Reflection: " + sw.Elapsed);
}

private void TestExpression()
{
    var myConstructor = CreateConstructor(typeof(MyClass), typeof(int), typeof(string));

    Stopwatch sw = Stopwatch.StartNew();

    for (int i = 0; i < 1024 * 1024 * 10; i++)
    {
        var myObject = myConstructor(10, "test message");
    }

    sw.Stop();
    Trace.WriteLine("Expression: " + sw.Elapsed);
}

TestActivator();
TestReflection();
TestExpression();

Results:

Activator: 00:00:13.8210732
Reflection: 00:00:05.2986945
Expression: 00:00:00.6681696

Using Expressions is +/- 8 times faster than Invoking the ConstructorInfo and +/- 20 times faster than using the Activator

How to break out or exit a method in Java?

Use the return keyword to exit from a method.

public void someMethod() {
    //... a bunch of code ...
    if (someCondition()) {
        return;
    }
    //... otherwise do the following...
}

From the Java Tutorial that I linked to above:

Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:

return;

Why is HttpContext.Current null?

Clearly HttpContext.Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.

Overall, don't use Application["Setting"] to store global stuffs, as they are not global as you discovered.

If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext or Application["Settings"], as that violates the principles of isolation and decoupling.

Update: Due to the introduction of async/await it is more often that such issues happen, so you might consider the following tip,

In general, you should only call HttpContext.Current in only a few scenarios (within an HTTP module for example). In all other cases, you should use

instead of HttpContext.Current.

Git Clone: Just the files, please?

The git command that would be the closest from what you are looking for would by git archive.
See backing up project which uses git: it will include in an archive all files (including submodules if you are using the git-archive-all script)

You can then use that archive anywhere, giving you back only files, no .git directory.

git archive --remote=<repository URL> | tar -t

If you need folders and files just from the first level:

git archive --remote=<repository URL> | tar -t --exclude="*/*"

To list only first-level folders of a remote repo:

git archive --remote=<repository URL> | tar -t --exclude="*/*" | grep "/"

Note: that does not work for GitHub (not supported)

So you would need to clone (shallow to quicken the clone step), and then archive locally:

git clone --depth=1 [email protected]:xxx/yyy.git
cd yyy
git archive --format=tar aTag -o aTag.tar

Another option would be to do a shallow clone (as mentioned below), but locating the .git folder elsewhere.

git --git-dir=/path/to/another/folder.git clone --depth=1 /url/to/repo

The repo folder would include only the file, without .git.

Note: git --git-dir is an option of the command git, not git clone.


Update with Git 2.14.X/2.15 (Q4 2017): it will make sure to avoid adding empty folders.

"git archive", especially when used with pathspec, stored an empty directory in its output, even though Git itself never does so.
This has been fixed.

See commit 4318094 (12 Sep 2017) by René Scharfe (``).
Suggested-by: Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 62b1cb7, 25 Sep 2017)

archive: don't add empty directories to archives

While git doesn't track empty directories, git archive can be tricked into putting some into archives.
While that is supported by the object database, it can't be represented in the index and thus it's unlikely to occur in the wild.

As empty directories are not supported by git, they should also not be written into archives.
If an empty directory is really needed then it can be tracked and archived by placing an empty .gitignore file in it.

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

calling parent class method from child class object in java

Say the hierarchy is C->B->A with A being the base class.

I think there's more to fixing this than renaming a method. That will work but is that a fix?

One way is to refactor all the functionality common to B and C into D, and let B and C inherit from D: (B,C)->D->A Now the method in B that was hiding A's implementation from C is specific to B and stays there. This allows C to invoke the method in A without any hokery.

Determine the number of rows in a range

Why not use an Excel formula to determine the rows? For instance, if you are looking for how many cells contain data in Column A use this:

=COUNTIFS(A:A,"<>")

You can replace <> with any value to get how many rows have that value in it.

=COUNTIFS(A:A,"2008")

This can be used for finding filled cells in a row too.

How do I format a date with Dart?

 String dateConverter(String date) {
    // Input date Format
    final format = DateFormat("dd-MM-yyyy");
    DateTime gettingDate = format.parse(date);
    final DateFormat formatter = DateFormat('yyyy-MM-dd');
    // Output Date Format
    final String formatted = formatter.format(gettingDate);
    return date;
  }

Accept server's self-signed ssl certificate in Java client

There's a better alternative to trusting all certificates: Create a TrustStore that specifically trusts a given certificate and use this to create a SSLContext from which to get the SSLSocketFactory to set on the HttpsURLConnection. Here's the complete code:

File crtFile = new File("server.crt");
Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(crtFile));

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("server", certificate);

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
connection.setSSLSocketFactory(sslContext.getSocketFactory());

You can alternatively load the KeyStore directly from a file or retrieve the X.509 Certificate from any trusted source.

Note that with this code, the certificates in cacerts will not be used. This particular HttpsURLConnection will only trust this specific certificate.

ImportError: No module named sqlalchemy

I just experienced the same problem using the virtual environment. For me installing the package using python from the venv worked:
.\venv\environment\Scripts\python.exe -m pip install flask-sqlalchemy

How to find out mySQL server ip address from phpmyadmin

The SQL query SHOW VARIABLES WHERE Variable_name = 'hostname' will show you the hostname of the MySQL server which you can easily resolve to its IP address.

SHOW VARIABLES WHERE Variable_name = 'port' Will give you the port number.

You can find details about this in MySQL's manual: 12.4.5.41. SHOW VARIABLES Syntax and 5.1.4. Server System Variables

Lambda expression to convert array/List of String to array/List of Integers

You can also use,

List<String> list = new ArrayList<>();
    list.add("1");
    list.add("2");
    list.add("3");

    Integer[] array = list.stream()
        .map( v -> Integer.valueOf(v))
        .toArray(Integer[]::new);

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

Windows 10 x64 released August 2015 - same issue arising. MSVCR110.dll is also found in the sysWOW64 folder (which is where I found it, copying to system32 does not help). To resolve:

  1. uninstall the x86 versions of VC 11 vcredist_x64/86.exe for 2012 and 2013
  2. uninstall WAMP Server 2.5
  3. delete (maybe back up first) the WAMP folder
  4. restart windows
  5. reinstall WAMP 2.5

Hopefully like me you have a MySQL database backup handy!

How to get first and last element in an array in java?

Getting first and last elements in an array in Java

int[] a = new int[]{1, 8, 5, 9, 4};

First Element: a[0]

Last Element: a[a.length-1]

Uploading a file in Rails

In your intiallizer/carrierwave.rb

if Rails.env.development? || Rails.env.test?
    config.storage = :file
    config.root = "#{Rails.root}/public"
    if Rails.env.test?
      CarrierWave.configure do |config|
        config.storage = :file
        config.enable_processing = false
      end
    end
 end

use this to store in a file while running on local

How to rename uploaded file before saving it into a directory?

You guess correctly. Read the manual page for move_uploaded_file. Set the second parameter to whereever your want to save the file.

If it doesn't work, there is something wrong with your $fileName. Please post your most recent code.

Case-insensitive search in Rails model

Similar to Andrews which is #1:

Something that worked for me is:

name = "Blue Jeans"
Product.find_by("lower(name) = ?", name.downcase)

This eliminates the need to do a #where and #first in the same query. Hope this helps!

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

Can you center a Button in RelativeLayout?

It's really easy. Try the code below,

<RelativeLayout
    android:id="@+id/second_RL"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/first_RL"
    android:background="@android:color/holo_blue_bright"
    android:gravity="center">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</RelativeLayout>

Remove by _id in MongoDB console

Suppose we have this dummy collection:

{ "_id" : ObjectId("5ea53fedaa79db20d4e14284"), "item" : "planner", "qty" : 75 }

simply use:

db.inventory.deleteOne({ _id: ObjectId("5ea53fedaa79db20d4e14284") })

it will be deleted with this as a response:

{ "acknowledged" : true, "deletedCount" : 1 }

Thats it.

ld: framework not found Pods

This issue was driving me crazy as it suddenly happened without doing any changes to the project. I've tried all suggested solutions in this thread (and other related) and none of them solved the problem.

The only thing that differed from my other projects (which compiled fine), was that this project name was containing an accent (a french accent, "é"). I've renamed the project and all related files, and it finally worked !

Maybe this is related to updating to Xcode 10, because this project was working well before...

EDIT : it also seems to failed when using a project with - in project name…

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

Location of GlassFish Server Logs

In general the logs are in /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/.

In NetBeans go to the "Services" tab open "Servers", right-click on your Glassfish instance and click "View Domain Server Log".

If this doesn't work right-click on the Glassfish instance and click "Properties", you can see the folder with the domains under "Domains folder". Go to this folder -> your-domain -> logs

If the server is already running you should see an Output tab in NetBeans which is named similar to GlassFish Server x.x.x

You can also use cat or tail -F on /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/server.log. If you are using a different domain then domain1 you have to adjust the path for that.

Get the current script file name

Here is the difference between basename(__FILE__, ".php") and basename($_SERVER['REQUEST_URI'], ".php").

basename(__FILE__, ".php") shows the name of the file where this code is included - It means that if you include this code in header.php and current page is index.php, it will return header not index.

basename($_SERVER["REQUEST_URI"], ".php") - If you use include this code in header.php and current page is index.php, it will return index not header.

Number prime test in JavaScript

Simple version:

function isPrime(num) {
    if (num <= 1) { 
        return false;
    } else {
        for (var i = 2; i < num; i++) {
            if (num % i === 0) {
                return false; 
            }
        }
        return true;
    }  
}

console.log(isPrime(9));

How do I plot only a table in Matplotlib?

If you just wanted to change the example and put the table at the top, then loc='top' in the table declaration is what you need,

the_table = ax.table(cellText=cell_text,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='top')

Then adjusting the plot with,

plt.subplots_adjust(left=0.2, top=0.8)

A more flexible option is to put the table in its own axis using subplots,

import numpy as np
import matplotlib.pyplot as plt


fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')

axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()

which looks like this,

enter image description here

You are then free to adjust the locations of the axis as required.

Why rgb and not cmy?

the 3 additive colors are in fact red, green, and blue. printers use cmyk (cyan, magenta, yellow, and black).

and as http://en.wikipedia.org/wiki/Additive_color explains: if you use RYB as your primary colors, how do you make green? since yellow is made from equal amounts of red and green.

How to pass url arguments (query string) to a HTTP request on Angular?

Edit Angular >= 4.3.x

HttpClient has been introduced along with HttpParams. Below an example of use :

import { HttpParams, HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

let params = new HttpParams();
params = params.append('var1', val1);
params = params.append('var2', val2);

this.http.get(StaticSettings.BASE_URL, {params: params}).subscribe(...);

(Old answers)

Edit Angular >= 4.x

requestOptions.search has been deprecated. Use requestOptions.params instead :

let requestOptions = new RequestOptions();
requestOptions.params = params;

Original answer (Angular 2)

You need to import URLSearchParams as below

import { Http, RequestOptions, URLSearchParams } from '@angular/http';

And then build your parameters and make the http request as the following :

let params: URLSearchParams = new URLSearchParams();
params.set('var1', val1);
params.set('var2', val2);

let requestOptions = new RequestOptions();
requestOptions.search = params;

this.http.get(StaticSettings.BASE_URL, requestOptions)
    .toPromise()
    .then(response => response.json())
...

Maximum concurrent Socket.IO connections

This guy appears to have succeeded in having over 1 million concurrent connections on a single Node.js server.

http://blog.caustik.com/2012/08/19/node-js-w1m-concurrent-connections/

It's not clear to me exactly how many ports he was using though.

angular 2 sort and filter

This isn't added out of the box because the Angular team wants Angular 2 to run minified. OrderBy runs off of reflection which breaks with minification. Check out Miško Heverey's response on the matter.

I've taken the time to create an OrderBy pipe that supports both single and multi-dimensional arrays. It also supports being able to sort on multiple columns of the multi-dimensional array.

<li *ngFor="let person of people | orderBy : ['-lastName', 'age']">{{person.firstName}} {{person.lastName}}, {{person.age}}</li>

This pipe does allow for adding more items to the array after rendering the page, and still sort the arrays with the new items correctly.

I have a write up on the process here.

And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info

EDIT: Added new demo to http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby

EDIT 2: Updated ngFor to new syntax

jquery toggle slide from left to right and back

Use this...

$('#cat_icon').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').hide();
});
$('.panel_title').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').show();
});

See this Example

Greetings.

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

jquery beforeunload when closing (not leaving) the page?

Try this, loading data via ajax and displaying through return statement.

<script type="text/javascript">
function closeWindow(){

    var Data = $.ajax({
        type : "POST",
        url : "file.txt",  //loading a simple text file for sample.
        cache : false,
        global : false,
        async : false,
        success : function(data) {
            return data;
        }

    }).responseText;


    return "Are you sure you want to leave the page? You still have "+Data+" items in your shopping cart";
}

window.onbeforeunload = closeWindow;
</script>

AutoComplete TextBox Control

There are two ways to accomplish this textbox effect:

enter image description here

Either using the graphic user interface (GUI); or with code

Using the Graphic User Interface:
Go to: "Properties" Tab; then set the following properties:

enter image description here

However; the best way is to create this by code. See example below.

AutoCompleteStringCollection sourceName = new AutoCompleteStringCollection();

foreach (string name in listNames)
{    
    sourceName.Add(name);
}

txtName.AutoCompleteCustomSource = sourceName;
txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;

Error Code: 2013. Lost connection to MySQL server during query

In my case, setting the connection timeout interval to 6000 or something higher didn't work.

I just did what the workbench says I can do.

The maximum amount of time the query can take to return data from the DBMS.Set 0 to skip the read timeout.

On Mac Preferences -> SQL Editor -> Go to MySQL Session -> set connection read timeout interval to 0.

And it works

Why is "forEach not a function" for this object?

When I tried to access the result from

Object.keys(a).forEach(function (key){ console.log(a[key]); });

it was plain text result with no key-value pairs Here is an example

var fruits = {
    apple: "fruits/apple.png",
    banana: "fruits/banana.png",
    watermelon: "watermelon.jpg",
    grapes: "grapes.png",
    orange: "orange.jpg"
}

Now i want to get all links in a separated array , but with this code

    function linksOfPics(obJect){
Object.keys(obJect).forEach(function(x){
    console.log('\"'+obJect[x]+'\"');
});
}

the result of :

linksOfPics(fruits)



"fruits/apple.png"
 "fruits/banana.png"
 "watermelon.jpg"
 "grapes.png"
 "orange.jpg"
undefined

I figured out this one which solves what I'm looking for

  console.log(Object.values(fruits));
["fruits/apple.png", "fruits/banana.png", "watermelon.jpg", "grapes.png", "orange.jpg"]

How to get first and last day of previous month (with timestamp) in SQL Server

This is the simplest way I know to get the first day of the previous month:

Step 1: Move data to Postgres

Step 2:

select date_trunc('month', getdate()) - '1 MONTH'::interval;

Detecting endianness programmatically in a C++ program

See Endianness - C-Level Code illustration.

// assuming target architecture is 32-bit = 4-Bytes
enum ENDIANNESS{ LITTLEENDIAN , BIGENDIAN , UNHANDLE };


ENDIANNESS CheckArchEndianalityV1( void )
{
    int Endian = 0x00000001; // assuming target architecture is 32-bit    

    // as Endian = 0x00000001 so MSB (Most Significant Byte) = 0x00 and LSB (Least     Significant Byte) = 0x01
    // casting down to a single byte value LSB discarding higher bytes    

    return (*(char *) &Endian == 0x01) ? LITTLEENDIAN : BIGENDIAN;
} 

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

Here the solution which worked for me when I had this issue in my local system.

  1. Go to flyway_schema_history in your DB
  2. Delete the row containing the sql migration script

JPA - Persisting a One to Many relationship

You have to set the associatedEmployee on the Vehicle before persisting the Employee.

Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

WCF Service , how to increase the timeout?

In your binding configuration, there are four timeout values you can tweak:

<bindings>
  <basicHttpBinding>
    <binding name="IncreasedTimeout"
             sendTimeout="00:25:00">
    </binding>
  </basicHttpBinding>

The most important is the sendTimeout, which says how long the client will wait for a response from your WCF service. You can specify hours:minutes:seconds in your settings - in my sample, I set the timeout to 25 minutes.

The openTimeout as the name implies is the amount of time you're willing to wait when you open the connection to your WCF service. Similarly, the closeTimeout is the amount of time when you close the connection (dispose the client proxy) that you'll wait before an exception is thrown.

The receiveTimeout is a bit like a mirror for the sendTimeout - while the send timeout is the amount of time you'll wait for a response from the server, the receiveTimeout is the amount of time you'll give you client to receive and process the response from the server.

In case you're send back and forth "normal" messages, both can be pretty short - especially the receiveTimeout, since receiving a SOAP message, decrypting, checking and deserializing it should take almost no time. The story is different with streaming - in that case, you might need more time on the client to actually complete the "download" of the stream you get back from the server.

There's also openTimeout, receiveTimeout, and closeTimeout. The MSDN docs on binding gives you more information on what these are for.

To get a serious grip on all the intricasies of WCF, I would strongly recommend you purchase the "Learning WCF" book by Michele Leroux Bustamante:

Learning WCF http://ecx.images-amazon.com/images/I/51GNuqUJq%2BL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg

and you also spend some time watching her 15-part "WCF Top to Bottom" screencast series - highly recommended!

For more advanced topics I recommend that you check out Juwal Lowy's Programming WCF Services book.

Programming WCF http://ecx.images-amazon.com/images/I/41odWcLoGAL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg

PostgreSQL: How to make "case-insensitive" query

using ILIKE instead of LIKE

SELECT id FROM groups WHERE name ILIKE 'Administrator'

Git diff -w ignore whitespace only at start & end of lines

For end of line use:

git diff --ignore-space-at-eol

Instead of what are you using currently:

git diff -w (--ignore-all-space)

For start of line... you are out of luck if you want a built in solution.

However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".

How to merge rows in a column into one cell in excel?

I know this is really a really old question, but I was trying to do the same thing and I stumbled upon a new formula in excel called "TEXTJOIN".

For the question, the following formula solves the problem

=TEXTJOIN("",TRUE,(a1:a4))

The signature of "TEXTJOIN" is explained as TEXTJOIN(delimiter,ignore_empty,text1,[text2],[text3],...)

How to make readonly all inputs in some div in Angular2?

If using reactive forms, you can also disable the entire form or any sub-set of controls in a FormGroup with myFormGroup.disable().

Writing to a TextBox from another thread?

What's even easier is to just use the BackgroundWorker control...

Changing SVG image color with javascript

Sure, here is an example (standard HTML boilerplate omitted):

_x000D_
_x000D_
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" style="width: 3.5in; height: 1in">_x000D_
  <circle id="circle1" r="30" cx="34" cy="34" _x000D_
            style="fill: red; stroke: blue; stroke-width: 2"/>_x000D_
  </svg>_x000D_
<button onclick="circle1.style.fill='yellow';">Click to change to yellow</button>
_x000D_
_x000D_
_x000D_

toggle show/hide div with button?

This is how I hide and show content using a class. changing the class to nothing will change the display to block, changing the class to 'a' will show the display as none.

<!DOCTYPE html>
<html>
<head>
<style>
body  {
  background-color:#777777;
  }
block1{
  display:block; background-color:black; color:white; padding:20px; margin:20px;
  }
block1.a{
  display:none; background-color:black; color:white; padding:20px; margin:20px;
  }
</style>
</head>
<body>
<button onclick="document.getElementById('ID').setAttribute('class', '');">Open</button>
<button onclick="document.getElementById('ID').setAttribute('class', 'a');">Close</button>
<block1 id="ID" class="a">
<p>Testing</p>
</block1>
</body>
</html>

Setting a JPA timestamp column to be generated by the database?

This also works for me:-

@Temporal(TemporalType.TIMESTAMP)   
@Column(name = "CREATE_DATE_TIME", nullable = false, updatable = false, insertable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
public Date getCreateDateTime() {
    return createDateTime;
}

public void setCreateDateTime(Date createDateTime) {
    this.createDateTime = createDateTime;
}

Convert PEM to PPK file format

I used a trial version of ZOC Terminal Emulator and it worked. It readily accepts the Amazon's *.pem files.

The trick is though, that you need to specify "ec2-user" instead of "root" for the username - despite the example shown in the EC2 console, which is wrong! ;-)

How to position text over an image in css

How about something like this: http://jsfiddle.net/EgLKV/3/

Its done by using position:absolute and z-index to place the text over the image.

_x000D_
_x000D_
#container {_x000D_
  height: 400px;_x000D_
  width: 400px;_x000D_
  position: relative;_x000D_
}_x000D_
#image {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
}_x000D_
#text {_x000D_
  z-index: 100;_x000D_
  position: absolute;_x000D_
  color: white;_x000D_
  font-size: 24px;_x000D_
  font-weight: bold;_x000D_
  left: 150px;_x000D_
  top: 350px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />_x000D_
  <p id="text">_x000D_
    Hello World!_x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Failed to load JavaHL Library

I Just installed Mountain Lion and had the same problem I use FLashBuilder (which is 32bit) and MountainLion is 64bit, which means by default MacPorts installs everything as 64bit. The version of subclipse I use is 1.8 As i had already installed Subversion and JavaHLBindings I just ran this command:

 sudo port upgrade --enforce-variants active +universal 

This made mac ports go through everything already installed and also install the 32bit version.

I then restarted FlashBuilder and it no longer showed any JavaHL errors.

Access key value from Web.config in Razor View-MVC3 ASP.NET

FOR MVC

-- WEB.CONFIG CODE IN APP SETTING -- <add key="PhaseLevel" value="1" />

-- ON VIEWS suppose you want to show or hide something based on web.config Value--

-- WRITE THIS ON TOP OF YOUR PAGE-- @{ var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString(); }

-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.

@if (phase != "1") { @Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml") }

Linq order by, group by and order by each group?

I think you want an additional projection that maps each group to a sorted-version of the group:

.Select(group => group.OrderByDescending(student => student.Grade))

It also appears like you might want another flattening operation after that which will give you a sequence of students instead of a sequence of groups:

.SelectMany(group => group)

You can always collapse both into a single SelectMany call that does the projection and flattening together.


EDIT: As Jon Skeet points out, there are certain inefficiencies in the overall query; the information gained from sorting each group is not being used in the ordering of the groups themselves. By moving the sorting of each group to come before the ordering of the groups themselves, the Max query can be dodged into a simpler First query.

setContentView(R.layout.main); error

This problem usually happen if eclipse accidentally compile the main.xml incorrectly. The easiest solution is to delete R.java inside gen directory. Once we delete, than eclipse will generate the new R.java base on the latest main.xml

Python Pandas - Find difference between two data frames

import pandas as pd
# given
df1 = pd.DataFrame({'Name':['John','Mike','Smith','Wale','Marry','Tom','Menda','Bolt','Yuswa',],
    'Age':[23,45,12,34,27,44,28,39,40]})
df2 = pd.DataFrame({'Name':['John','Smith','Wale','Tom','Menda','Yuswa',],
    'Age':[23,12,34,44,28,40]})

# find elements in df1 that are not in df2
df_1notin2 = df1[~(df1['Name'].isin(df2['Name']) & df1['Age'].isin(df2['Age']))].reset_index(drop=True)

# output:
print('df1\n', df1)
print('df2\n', df2)
print('df_1notin2\n', df_1notin2)

# df1
#     Age   Name
# 0   23   John
# 1   45   Mike
# 2   12  Smith
# 3   34   Wale
# 4   27  Marry
# 5   44    Tom
# 6   28  Menda
# 7   39   Bolt
# 8   40  Yuswa
# df2
#     Age   Name
# 0   23   John
# 1   12  Smith
# 2   34   Wale
# 3   44    Tom
# 4   28  Menda
# 5   40  Yuswa
# df_1notin2
#     Age   Name
# 0   45   Mike
# 1   27  Marry
# 2   39   Bolt

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

  1. Look at the folders drawable-hdpi, drawable-mdpi, drawable-xhdpi and so on.
  2. If there is a wrong bitmap file, Delete it and resave.
  3. Go to Build->Rebuild Project

How to position absolute inside a div?

One of #a or #b needs to be not position:absolute, so that #box will grow to accommodate it.

So you can stop #a from being position:absolute, and still position #b over the top of it, like this:

_x000D_
_x000D_
 #box {_x000D_
        background-color: #000;_x000D_
        position: relative;     _x000D_
        padding: 10px;_x000D_
        width: 220px;_x000D_
    }_x000D_
    _x000D_
    .a {_x000D_
        width: 210px;_x000D_
        background-color: #fff;_x000D_
        padding: 5px;_x000D_
    }_x000D_
    _x000D_
    .b {_x000D_
        width: 100px; /* So you can see the other one */_x000D_
        position: absolute;_x000D_
        top: 10px; left: 10px;_x000D_
        background-color: red;_x000D_
        padding: 5px;_x000D_
    }_x000D_
    _x000D_
    #after {_x000D_
        background-color: yellow;_x000D_
        padding: 10px;_x000D_
        width: 220px;_x000D_
    }
_x000D_
    <div id="box">_x000D_
        <div class="a">Lorem</div>_x000D_
        <div class="b">Lorem</div>_x000D_
    </div>_x000D_
    <div id="after">Hello world</div>
_x000D_
_x000D_
_x000D_

(Note that I've made the widths different, so you can see one behind the other.)

Edit after Justine's comment: Then your only option is to specify the height of #box. This:

#box {
    /* ... */
    height: 30px;
}

works perfectly, assuming the heights of a and b are fixed. Note that you'll need to put IE into standards mode by adding a doctype at the top of your HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
          "http://www.w3.org/TR/html4/strict.dtd">

before that works properly.

Android offline documentation and sample codes

If you install the SDK, the offline documentation can be found in $ANDROID_SDK/docs/.

can't access mysql from command line mac

I'm using OS X 10.10, open the shell, type

export PATH=$PATH:/usr/local/mysql/bin

it works temporary.if you use Command+T to open a new tab ,mysql command will not work anymore.

We need to create a .bash_profile file to make it work each time you open a new tab.

nano ~/.bash_profile

add the following line to the file.

# Set architecture flags
export ARCHFLAGS="-arch x86_64"
# Ensure user-installed binaries take precedence
export PATH=/usr/local/mysql/bin:$PATH
# Load .bashrc if it exists
test -f ~/.bashrc && source ~/.bashrc

Save the file, then open a new shell tab, it works like a charm..

by the way, why not try https://github.com/dbcli/mycli

pip install -U mycli

it's a tool way better than the mysqlcli.. A command line client for MySQL that can do auto-completion and syntax highlighting

Find a commit on GitHub given the commit hash

View single commit:
https://github.com/<user>/<project>/commit/<hash>

View log:
https://github.com/<user>/<project>/commits/<hash>

View full repo:
https://github.com/<user>/<project>/tree/<hash>

<hash> can be any length as long as it is unique.

SQL Error: ORA-01861: literal does not match format string 01861

Try replacing the string literal for date '1989-12-09' with TO_DATE('1989-12-09','YYYY-MM-DD')

Listing available com ports with Python

A possible refinement to Thomas's excellent answer is to have Linux and possibly OSX also try to open ports and return only those which could be opened. This is because Linux, at least, lists a boatload of ports as files in /dev/ which aren't connected to anything. If you're running in a terminal, /dev/tty is the terminal in which you're working and opening and closing it can goof up your command line, so the glob is designed to not do that. Code:

    # ... Windows code unchanged ...

    elif sys.platform.startswith ('linux'):
        temp_list = glob.glob ('/dev/tty[A-Za-z]*')

    result = []
    for a_port in temp_list:

        try:
            s = serial.Serial(a_port)
            s.close()
            result.append(a_port)
        except serial.SerialException:
            pass

    return result

This modification to Thomas's code has been tested on Ubuntu 14.04 only.

If else in stored procedure sql server

Instead of writing:

Select top 1 ParLngId from T_Param where ParStrNom = 'Extranet Client'

Write:

Select top 1 ParLngId from T_Param where ParStrNom IN 'Extranet Client'

i.e. replace '=' sign by 'IN'

How do I make jQuery wait for an Ajax call to finish before it returns?

If you don't want the $.ajax() function to return immediately, set the async option to false:

$(".my_link").click(
    function(){
    $.ajax({
        url: $(this).attr('href'),
        type: 'GET',
        async: false,
        cache: false,
        timeout: 30000,
        fail: function(){
            return true;
        },
        done: function(msg){ 
            if (parseFloat(msg)){
                return false;
            } else {
                return true;
            }
        }
    });
});

But, I would note that this would be counter to the point of AJAX. Also, you should be handling the response in the fail and done functions. Those functions will only be called when the response is received from the server.

HTML/CSS: how to put text both right and left aligned in a paragraph

I have used this in the past:

html

January<span class="right">2014</span>

Css

.right {
    margin-left:100%;
}

Demonstration

How to get the url parameters using AngularJS

I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProvider and routeParams is the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.

Check out the Angular seed project. Within the app.js you'll find an example for the route provider. To use params simply append them like this:

$routeProvider.when('/view1/:param1/:param2', {
    templateUrl: 'partials/partial1.html',    
    controller: 'MyCtrl1'
});

Then in your controller inject $routeParams:

.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
  var param1 = $routeParams.param1;
  var param2 = $routeParams.param2;
  ...
}]);

With this approach you can use params with a url such as: "http://www.example.com/view1/param1/param2"

Why is PHP session_destroy() not working?

If you need to clear the values of $_SESSION, set the array equal to an empty array:

$_SESSION = array();

Of course, you can't access the values of $_SESSION on another page once you call session_destroy, so it doesn't matter that much.

Try the following:

session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable

How to find files modified in last x minutes (find -mmin does not work as expected)

I can reproduce your problem if there are no files in the directory that were modified in the last hour. In that case, find . -mmin -60 returns nothing. The command find . -mmin -60 |xargs ls -l, however, returns every file in the directory which is consistent with what happens when ls -l is run without an argument.

To make sure that ls -l is only run when a file is found, try:

find . -mmin -60 -type f -exec ls -l {} +

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

I had a similar issue where I also continuously got the same error. I tried many things like changing the listener port number, turning off the firewall etc. Finally I was able to resolve the issue by changing listener.ora file. I changed the following line:

(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))

to

(ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521)) 

I also added an entry in the /etc/hosts file.

you can use Oracle net manager to change the above line in listener.ora file. See Oracle Net Services Administrator's Guide for more information on how to do it using net manager.

Also you can use the service name (database_name.domain_name) instead of SID while making the connnection.

I Hope it helps.

How to add message box with 'OK' button?

The code compiles ok for me. May be you have forgotten to add the import:

import android.app.AlertDialog;

Anyway, you have a good tutorial here.

String, StringBuffer, and StringBuilder

  • You use String when an immutable structure is appropriate; obtaining a new character sequence from a String may carry an unacceptable performance penalty, either in CPU time or memory (obtaining substrings is CPU efficient because the data is not copied, but this means a potentially much larger amount of data may remain allocated).
  • You use StringBuilder when you need to create a mutable character sequence, usually to concatenate several character sequences together.
  • You use StringBuffer in the same circumstances you would use StringBuilder, but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).

See an example here.

Where can I download IntelliJ IDEA Color Schemes?

Here is a theme I created which was inspired by GitHub's embedded source view. I love how elegant their color scheme is, but lately I prefer a darker theme. This is theme is only for Java. Sorry. Download it here: GitHubInspiredDark.xml

Inspired by GitHub

How do I get out of 'screen' without typing 'exit'?

  • Ctrl + A, Ctrl + \ - Exit screen and terminate all programs in this screen. It is helpful, for example, if you need to close a tty connection.

  • Ctrl + D, D or - Ctrl + A, Ctrl + D - "minimize" screen and screen -r to restore it.

How can I write text on a HTML5 canvas element?

It is really easy to write text on a canvas. It was not clear if you want someone to enter text in the HTML page and then have that text appear on the canvas, or if you were going to use JavaScript to write the information to the screen.

The following code will write some text in different fonts and formats to your canvas. You can modify this as you wish to test other aspects of writing onto a canvas.

 <canvas id="YourCanvasNameHere" width="500" height="500">Canvas not supported</canvas>

 var c = document.getElementById('YourCanvasNameHere');
 var context = c.getContext('2d'); //returns drawing functions to allow the user to draw on the canvas with graphic tools. 

You can either place the canvas ID tag in the HTML and then reference the name or you can create the canvas in the JavaScript code. I think that for the most part I see the <canvas> tag in the HTML code and on occasion see it created dynamically in the JavaScript code itself.

Code:

  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  context.font = 'bold 10pt Calibri';
  context.fillText('Hello World!', 150, 100);
  context.font = 'italic 40pt Times Roman';
  context.fillStyle = 'blue';
  context.fillText('Hello World!', 200, 150);
  context.font = '60pt Calibri';
  context.lineWidth = 4;
  context.strokeStyle = 'blue';
  context.strokeText('Hello World!', 70, 70);

Scroll to bottom of div?

You can use the Element.scrollTo() method.

It can be animated using the built-in browser/OS animation, so it's super smooth.

_x000D_
_x000D_
function scrollToBottom() {
    const scrollContainer = document.getElementById('container');
    scrollContainer.scrollTo({
        top: scrollContainer.scrollHeight,
        left: 0,
        behavior: 'smooth'
    });
}

// initialize dummy content
const scrollContainer = document.getElementById('container');
const numCards = 100;
let contentInnerHtml = '';
for (let i=0; i<numCards; i++) {
  contentInnerHtml += `<div class="card mb-2"><div class="card-body">Card ${i + 1}</div></div>`;
}
scrollContainer.innerHTML = contentInnerHtml;
_x000D_
.overflow-y-scroll {
  overflow-y: scroll;
}
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>

<div class="d-flex flex-column vh-100">
  <div id="container" class="overflow-y-scroll flex-grow-1"></div>
  <div>
    <button class="btn btn-primary" onclick="scrollToBottom()">Scroll to bottom</button>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Negation in Python

try instead:

if not os.path.exists(pathName):
    do this

Cannot declare instance members in a static class in C#

I know this post is old but...

I was able to do this, my problem was that I forgot to make my property static.

public static class MyStaticClass
{
    private static NonStaticObject _myObject = new NonStaticObject();

    //property
    public static NonStaticObject MyObject
    {
        get { return _myObject; }
        set { _myObject = value; }
    }
}

Check if datetime instance falls in between other two datetime objects

You can, use:

if (date >= startDate && date<= EndDate) { return true; }

How to set JAVA_HOME for multiple Tomcat instances?

One thing that you could do would be to modify the catalina.sh (Unix based) or the catalina.bat (windows based).

Within each of the scripts you can set certain variables which only processes created under the shell will inherit. So for catalina.sh, use the following line:

export JAVA_HOME="intented java home"

And for windows use

set JAVA_HOME="intented java home"

To get total number of columns in a table in sql

You can try below query:

select 
  count(*) 
from 
  all_tab_columns
where 
  table_name = 'your_table'

How do you create a dropdownlist from an enum in ASP.NET MVC?

UPDATED - I would suggest using the suggestion by Rune below rather than this option!


I assume that you want something like the following spat out:

<select name="blah">
    <option value="1">Movie</option>
    <option value="2">Game</option>
    <option value="3">Book</option>
</select>

which you could do with an extension method something like the following:

public static string DropdownEnum(this System.Web.Mvc.HtmlHelper helper,
                                  Enum values)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append("<select name=\"blah\">");
    string[] names = Enum.GetNames(values.GetType());
    foreach(string name in names)
    {
        sb.Append("<option value=\"");
        sb.Append(((int)Enum.Parse(values.GetType(), name)).ToString());
        sb.Append("\">");
        sb.Append(name);
        sb.Append("</option>");
    }
    sb.Append("</select>");
    return sb.ToString();
}

BUT things like this aren't localisable (i.e. it will be hard to translate into another language).

Note: you need to call the static method with an instance of the Enumeration, i.e. Html.DropdownEnum(ItemTypes.Movie);

There may be a more elegant way of doing this, but the above does work.

Get the time difference between two datetimes

Typescript: following should work,

export const getTimeBetweenDates = ({
  until,
  format
}: {
  until: number;
  format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
  const date = new Date();
  const remainingTime = new Date(until * 1000);
  const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
  const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
  const diff = getUntil.diff(getFrom, format);
  return !isNaN(diff) ? diff : null;
};

Find a string between 2 known values

  Regex regex = new Regex("<tag1>(.*)</tag1>");
  var v = regex.Match("morenonxmldata<tag1>0002</tag1>morenonxmldata");
  string s = v.Groups[1].ToString();

Or (as mentioned in the comments) to match the minimal subset:

  Regex regex = new Regex("<tag1>(.*?)</tag1>");

Regex class is in System.Text.RegularExpressions namespace.

How can one display images side by side in a GitHub README.md?

This will display the three images side by side if the images are not too wide.

<p float="left">
  <img src="/img1.png" width="100" />
  <img src="/img2.png" width="100" /> 
  <img src="/img3.png" width="100" />
</p>

Jenkins not executing jobs (pending - waiting for next executor)

In my case I've to set Execute concurrent builds if necessary in job's General settings.

Monitor network activity in Android Phones

The common approach is to call "cat /proc/net/netstat" as described here:

Android network stats

jQuery Set Select Index

Even simpler:

$('#selectBox option')[3].selected = true;

Reading/Writing a MS Word file in PHP

Source gotten from

Use following class directly to read word document

class DocxConversion{
    private $filename;

    public function __construct($filePath) {
        $this->filename = $filePath;
    }

    private function read_doc() {
        $fileHandle = fopen($this->filename, "r");
        $line = @fread($fileHandle, filesize($this->filename));   
        $lines = explode(chr(0x0D),$line);
        $outtext = "";
        foreach($lines as $thisline)
          {
            $pos = strpos($thisline, chr(0x00));
            if (($pos !== FALSE)||(strlen($thisline)==0))
              {
              } else {
                $outtext .= $thisline." ";
              }
          }
         $outtext = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/","",$outtext);
        return $outtext;
    }

    private function read_docx(){

        $striped_content = '';
        $content = '';

        $zip = zip_open($this->filename);

        if (!$zip || is_numeric($zip)) return false;

        while ($zip_entry = zip_read($zip)) {

            if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

            if (zip_entry_name($zip_entry) != "word/document.xml") continue;

            $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

            zip_entry_close($zip_entry);
        }// end while

        zip_close($zip);

        $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
        $content = str_replace('</w:r></w:p>', "\r\n", $content);
        $striped_content = strip_tags($content);

        return $striped_content;
    }

 /************************excel sheet************************************/

function xlsx_to_text($input_file){
    $xml_filename = "xl/sharedStrings.xml"; //content file name
    $zip_handle = new ZipArchive;
    $output_text = "";
    if(true === $zip_handle->open($input_file)){
        if(($xml_index = $zip_handle->locateName($xml_filename)) !== false){
            $xml_datas = $zip_handle->getFromIndex($xml_index);
            $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            $output_text = strip_tags($xml_handle->saveXML());
        }else{
            $output_text .="";
        }
        $zip_handle->close();
    }else{
    $output_text .="";
    }
    return $output_text;
}

/*************************power point files*****************************/
function pptx_to_text($input_file){
    $zip_handle = new ZipArchive;
    $output_text = "";
    if(true === $zip_handle->open($input_file)){
        $slide_number = 1; //loop through slide files
        while(($xml_index = $zip_handle->locateName("ppt/slides/slide".$slide_number.".xml")) !== false){
            $xml_datas = $zip_handle->getFromIndex($xml_index);
            $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            $output_text .= strip_tags($xml_handle->saveXML());
            $slide_number++;
        }
        if($slide_number == 1){
            $output_text .="";
        }
        $zip_handle->close();
    }else{
    $output_text .="";
    }
    return $output_text;
}


    public function convertToText() {

        if(isset($this->filename) && !file_exists($this->filename)) {
            return "File Not exists";
        }

        $fileArray = pathinfo($this->filename);
        $file_ext  = $fileArray['extension'];
        if($file_ext == "doc" || $file_ext == "docx" || $file_ext == "xlsx" || $file_ext == "pptx")
        {
            if($file_ext == "doc") {
                return $this->read_doc();
            } elseif($file_ext == "docx") {
                return $this->read_docx();
            } elseif($file_ext == "xlsx") {
                return $this->xlsx_to_text();
            }elseif($file_ext == "pptx") {
                return $this->pptx_to_text();
            }
        } else {
            return "Invalid File Type";
        }
    }

}

$docObj = new DocxConversion("test.docx"); //replace your document name with correct extension doc or docx 
echo $docText= $docObj->convertToText();

Node.js client for a socket.io server

Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!

const socket = require('socket.io-client')('http://192.168.0.8:5000', {
            reconnection: true,
            reconnectionDelay: 10000
          });
    
        socket.on('connect', (data) => {
            console.log('Connected to Socket');
        });
        
        socket.on('event_name', (data) => {
            console.log("-----------------received event data from the socket io server");
        });
    
        //either 'io server disconnect' or 'io client disconnect'
        socket.on('disconnect', (reason) => {
            console.log("client disconnected");
            if (reason === 'io server disconnect') {
              // the disconnection was initiated by the server, you need to reconnect manually
              console.log("server disconnected the client, trying to reconnect");
              socket.connect();
            }else{
                console.log("trying to reconnect again with server");
            }
            // else the socket will automatically try to reconnect
          });
    
        socket.on('error', (error) => {
            console.log(error);
        });

Determine the process pid listening on a certain port

Since sockstat wasn't natively installed on my machine I hacked up stanwise's answer to use netstat instead..

netstat -nlp | grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:2000" | awk '{print $7}' | sed -e "s/\/.*//g""

Skip Git commit hooks

From man githooks:

pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.

Better way to find control in ASP.NET

All the highlighted solutions are using recursion (which is performance costly). Here is cleaner way without recursion:

public T GetControlByType<T>(Control root, Func<T, bool> predicate = null) where T : Control 
{
    if (root == null) {
        throw new ArgumentNullException("root");
    }

    var stack = new Stack<Control>(new Control[] { root });

    while (stack.Count > 0) {
        var control = stack.Pop();
        T match = control as T;

        if (match != null && (predicate == null || predicate(match))) {
            return match;
        }

        foreach (Control childControl in control.Controls) {
           stack.Push(childControl);
        }
    }

    return default(T);
}

How to replace url parameter with javascript/jquery?

In modern browsers (everything except IE9 and below), our lives are a little easier now with the new URL api

var url = new window.URL(document.location); // fx. http://host.com/endpoint?abc=123
url.searchParams.set("foo", "bar");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=bar
url.searchParams.set("foo", "ooft");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=ooft

Find out the history of SQL queries

For recent SQL:

select * from v$sql

For history:

select * from dba_hist_sqltext

C# 4.0: Convert pdf to byte[] and vice versa

using (FileStream fs = new FileStream("sample.pdf", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fs.Length];
                int numBytesToRead = (int)fs.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    // Read may return anything from 0 to numBytesToRead.
                    int n = fs.Read(bytes, numBytesRead, numBytesToRead);

                    // Break when the end of the file is reached.
                    if (n == 0)
                    {
                        break;
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
}

How to disable javax.swing.JButton in java?

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

input type=file show only button

That's going to be very hard. The problem with the file input type is that it usually consists of two visual elements, while being treated as a single DOM-element. Add to that that several browsers have their own distinct look and feel for the file input, and you're set for nightmare. See this article on quirksmode.org about the quirks the file input has. I guarantee you it won't make you happy (I speak from experience).

[EDIT]

Actually, I think you might get away with putting your input in a container element (like a div), and adding a negative margin to the element. Effectively hiding the textbox part off screen. Another option would be to use the technique in the article I linked, to try to style it like a button.

Javascript regular expression password validation having special characters

I use the following script for min 8 letter password, with at least a symbol, upper and lower case letters and a number

function checkPassword(str)
{
    var re = /^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
    return re.test(str);
}

'if' in prolog?

I found this helpful for using an if statement in a rule.

max(X,Y,Z) :-
    (  X =< Y
    -> Z = Y
    ;  Z = X
    ).

Thanks to http://cs.union.edu/~striegnk/learn-prolog-now/html/node89.html

How to combine two or more querysets in a Django view?

This can be achieved by two ways either.

1st way to do this

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator.

For an instance

pagelist1 = Page.objects.filter(
    Q(title__icontains=cleaned_search_term) | 
    Q(body__icontains=cleaned_search_term))
pagelist2 = Page.objects.filter(
    Q(title__icontains=cleaned_search_term) | 
    Q(body__icontains=cleaned_search_term))
combined_list = pagelist1 | pagelist2 # this would take union of two querysets

2nd way to do this

One other way to achieve combine operation between two queryset is to use itertools chain function.

from itertools import chain
combined_results = list(chain(pagelist1, pagelist2))

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

Your query appears to have a double negative, you want to exclude all rows where x is not 5, so in other words you want to include all rows where x is 5. I believe this will do the trick:

results = Model.objects.filter(x=5).exclude(a=True)

To answer your specific question, there is no "not equal to" field lookup but that's probably because Django has both filter and exclude methods available so you can always just switch the logic around to get the desired result.

how to force maven to update local repo

If you are installing into local repository, there is no special index/cache update needed.

Make sure that:

  1. You have installed the first artifact in your local repository properly. Simply copying the file to .m2 may not work as expected. Make sure you install it by mvn install

  2. The dependency in 2nd project is setup correctly. Check on any typo in groupId/artifactId/version, or unmatched artifact type/classifier.

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

Can we pass model as a parameter in RedirectToAction?

i did find something like this, helps get rid of hardcoded tempdata tags

public class AccountController : Controller
{
    [HttpGet]
    public ActionResult Index(IndexPresentationModel model)
    {
        return View(model);
    }

    [HttpPost]
    public ActionResult Save(SaveUpdateModel model)
    {
        // save the information

        var presentationModel = new IndexPresentationModel();

        presentationModel.Message = model.Message;

        return this.RedirectToAction(c => c.Index(presentationModel));
    }
}

How to see query history in SQL Server Management Studio

The system doesn't record queries in that way. If you know you want to do that ahead of time though, you can use SQL Profiler to record what is coming in and track queries during the time Profiler is running.

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

I had such crash on Samsung devices even though the activity did use Theme.AppCompat. The root cause was related to weird optimizations on Samsung side:

- if one activity of your app has theme not inherited from Theme.AppCompat
- and it has also `android:launchMode="singleTask"`
- then all the activities that are launched from it will share the same Theme

My solution was just removing android:launchMode="singleTask"

jQuery checkbox event handling

I have try the code from first answer, it not working but I have play around and this work for me

$('#vip').change(function(){
    if ($(this).is(':checked')) {
        alert('checked');
    } else {
        alert('uncheck');
    }
});

How to detect a mobile device with JavaScript?

Testing for user agent is complex, messy and invariably fails. I also didn't find that the media match for "handheld" worked for me. The simplest solution was to detect if the mouse was available. And that can be done like this:

var result = window.matchMedia("(any-pointer:coarse)").matches;

That will tell you if you need to show hover items or not and anything else that requires a physical pointer. The sizing can then be done on further media queries based on width.

The following little library is a belt braces version of the query above, should cover most "are you a tablet or a phone with no mouse" scenarios.

https://patrickhlauke.github.io/touch/touchscreen-detection/

Media matches have been supported since 2015 and you can check the compatibility here: https://caniuse.com/#search=matchMedia

In short you should maintain variables relating to whether the screen is touch screen and also what size the screen is. In theory I could have a tiny screen on a mouse operated desktop.

How to test the type of a thrown exception in Jest

Try:

expect(t).rejects.toThrow()

Write HTML file using Java

You can use jsoup or wffweb (HTML5) based.

Sample code for jsoup:-

Document doc = Jsoup.parse("<html></html>");
doc.body().addClass("body-styles-cls");
doc.body().appendElement("div");
System.out.println(doc.toString());

prints

<html>
 <head></head>
 <body class=" body-styles-cls">
  <div></div>
 </body>
</html>

Sample code for wffweb:-

Html html = new Html(null) {{
    new Head(this);
    new Body(this,
        new ClassAttribute("body-styles-cls"));
}};

Body body = TagRepository.findOneTagAssignableToTag(Body.class, html);
body.appendChild(new Div(null));

System.out.println(html.toHtmlString());
//directly writes to file
html.toOutputStream(new FileOutputStream("/home/user/filepath/filename.html"), "UTF-8");

prints (in minified format):-

<html>
<head></head>
<body class="body-styles-cls">
    <div></div>
</body>
</html>

dd: How to calculate optimal blocksize?

I've found my optimal blocksize to be 8 MB (equal to disk cache?) I needed to wipe (some say: wash) the empty space on a disk before creating a compressed image of it. I used:

cd /media/DiskToWash/
dd if=/dev/zero of=zero bs=8M; rm zero

I experimented with values from 4K to 100M.

After letting dd to run for a while I killed it (Ctlr+C) and read the output:

36+0 records in
36+0 records out
301989888 bytes (302 MB) copied, 15.8341 s, 19.1 MB/s

As dd displays the input/output rate (19.1MB/s in this case) it's easy to see if the value you've picked is performing better than the previous one or worse.

My scores:

bs=   I/O rate
---------------
4K    13.5 MB/s
64K   18.3 MB/s
8M    19.1 MB/s <--- winner!
10M   19.0 MB/s
20M   18.6 MB/s
100M  18.6 MB/s   

Note: To check what your disk cache/buffer size is, you can use sudo hdparm -i /dev/sda

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

The best thing you can do is leave out the action attribute altogether. If you leave it out, the form will be submitted to the document's address, i.e. the same page.

It is also possible to leave it empty, and any browser implementing HTML's form submission algorithm will treat it as equivalent to the document's address, which it does mainly because that's how browsers currently work:

8. Let action be the submitter element's action.

9. If action is the empty string, let action be the document's address.

Note: This step is a willful violation of RFC 3986, which would require base URL processing here. This violation is motivated by a desire for compatibility with legacy content. [RFC3986]

This definitely works in all current browsers, but may not work as expected in some older browsers ("browsers do weird things with an empty action="" attribute"), which is why the spec strongly discourages authors from leaving it empty:

The action and formaction content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces.

Twitter bootstrap float div right

To float a div to the right pull-right is the recommend way, I feel you are doing things right may be you only need to use text-align:right;

  <div class="container">
     <div class="row-fluid">
      <div class="span6">
           <p>Text left</p>
      </div>
      <div class="span6 pull-right" style="text-align:right">
           <p>text right</p>
      </div>
  </div>
 </div>      
 </div>

How to open Emacs inside Bash

Try emacs —daemon to have Emacs running in the background, and emacsclient to connect to the Emacs server.

It’s not much time overhead saved on modern systems, but it’s a lot better than running several instances of Emacs.

Volatile boolean vs AtomicBoolean

If there are multiple threads accessing class level variable then each thread can keep copy of that variable in its threadlocal cache.

Making the variable volatile will prevent threads from keeping the copy of variable in threadlocal cache.

Atomic variables are different and they allow atomic modification of their values.

Unexpected end of file error

If you do not use precompiled headers in your project, set the Create/Use Precompiled Header property of source files to Not Using Precompiled Headers. To set this compiler option, follow these steps:

  • In the Solution Explorer pane of the project, right-click the project name, and then click Properties.
  • In the left pane, click the C/C++ folder.
  • Click the Precompiled Headers node.
  • In the right pane, click Create/Use Precompiled Header, and then click Not Using Precompiled Headers.

Stop mouse event propagation

Adding to the answer from @AndroidUniversity. In a single line you can write it like so:

<component (click)="$event.stopPropagation()"></component>

Split string using a newline delimiter with Python

data = """a,b,c
d,e,f
g,h,i
j,k,l"""

print(data.split())       # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

str.split, by default, splits by all the whitespace characters. If the actual string has any other whitespace characters, you might want to use

print(data.split("\n"))   # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

Or as @Ashwini Chaudhary suggested in the comments, you can use

print(data.splitlines())