Programs & Examples On #Nic

A Network Interface Card is a computer component which connects to a physical network in order to send and receive data.

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

Alternatively, if you want to get the IP address of whichever interface is used to connect to the network without having to know its name, you can use this:

import socket
def get_ip_address():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    return s.getsockname()[0]

I know it's a little different than your question, but others may arrive here and find this one more useful. You do not have to have a route to 8.8.8.8 to use this. All it is doing is opening a socket, but not sending any data.

Maximum on http header values?

If you are going to use any DDOS provider like Akamai, they have a maximum limitation of 8k in the response header size. So essentially try to limit your response header size below 8k.

How can you tell if a value is not numeric in Oracle?

REGEXP_LIKE(column, '^[[:digit:]]+$')

returns TRUE if column holds only numeric characters

convert string array to string

Try:

String.Join("", test);

which should return a string joining the two elements together. "" indicates that you want the strings joined together without any separators.

Run R script from command line

You need the ?Rscript command to run an R script from the terminal.

Check out http://stat.ethz.ch/R-manual/R-devel/library/utils/html/Rscript.html

Example

## example #! script for a Unix-alike

#! /path/to/Rscript --vanilla --default-packages=utils
args <- commandArgs(TRUE)
res <- try(install.packages(args))
if(inherits(res, "try-error")) q(status=1) else q()

How do I put an already-running process under nohup?

  1. ctrl + z - this will pause the job (not going to cancel!)
  2. bg - this will put the job in background and return in running process
  3. disown -a - this will cut all the attachment with job (so you can close the terminal and it will still run)

These simple steps will allow you to close the terminal while keeping process running.

It wont put on nohup (based on my understanding of your question, you don't need it here).

Making an asynchronous task in Flask

You can also try using multiprocessing.Process with daemon=True; the process.start() method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.

I experienced similar problem while working with falcon framework and using daemon process helped.

You'd need to do the following:

from multiprocessing import Process

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    heavy_process = Process(  # Create a daemonic process with heavy "my_func"
        target=my_func,
        daemon=True
    )
    heavy_process.start()
    return Response(
        mimetype='application/json',
        status=200
    )

# Define some heavy function
def my_func():
    time.sleep(10)
    print("Process finished")

You should get a response immediately and, after 10s you should see a printed message in the console.

NOTE: Keep in mind that daemonic processes are not allowed to spawn any child processes.

How do you roll back (reset) a Git repository to a particular commit?

git reset --hard <tag/branch/commit id>

Notes:

  • git reset without the --hard option resets the commit history, but not the files. With the --hard option the files in working tree are also reset. (credited user)

  • If you wish to commit that state so that the remote repository also points to the rolled back commit do: git push <reponame> -f (credited user)

Merging Cells in Excel using C#

You can use NPOI to do it.

Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");

Row row = sheet.createRow((short) 1);
Cell cell = row.createCell((short) 1);
cell.setCellValue("This is a test of merging");

sheet.addMergedRegion(new CellRangeAddress(
        1, //first row (0-based)
        1, //last row  (0-based)
        1, //first column (0-based)
        2  //last column  (0-based)
));

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

What is the difference between a var and val definition in Scala?

val is final, that is, cannot be set. Think final in java.

ObjectiveC Parse Integer from String

NSArray *_returnedArguments = [serverOutput componentsSeparatedByString:@":"];

_returnedArguments is an array of NSStrings which the UITextField text property is expecting. No need to convert.

Syntax error:

[_appDelegate loggedIn:usernameField.text:passwordField.text:(int)[[_returnedArguments objectAtIndex:2] intValue]];

If your _appDelegate has a passwordField property, then you can set the text using the following

[[_appDelegate passwordField] setText:[_returnedArguments objectAtIndex:2]];

How can I use different certificates on specific connections?

I read through LOTS of places online to solve this thing. This is the code I wrote to make it work:

ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();

TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());

app.certificateString is a String that contains the Certificate, for example:

static public String certificateString=
        "-----BEGIN CERTIFICATE-----\n" +
        "MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
        "BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
        ... a bunch of characters...
        "5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
        "-----END CERTIFICATE-----";

I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line.

Convert Base64 string to an image file?

That's an old thread, but in case you want to upload the image having same extension-

    $image = $request->image;
    $imageInfo = explode(";base64,", $image);
    $imgExt = str_replace('data:image/', '', $imageInfo[0]);      
    $image = str_replace(' ', '+', $imageInfo[1]);
    $imageName = "post-".time().".".$imgExt;
    Storage::disk('public_feeds')->put($imageName, base64_decode($image));

You can create 'public_feeds' in laravel's filesystem.php-

   'public_feeds' => [
        'driver' => 'local',
        'root'   => public_path() . '/uploads/feeds',
    ],

Web API optional parameters

Sku is an int, can't be defaulted to string "sku". Please check Optional URI Parameters and Default Values

Passing an array by reference in C?

In plain C you can use a pointer/size combination in your API.

void doSomething(MyStruct* mystruct, size_t numElements)
{
    for (size_t i = 0; i < numElements; ++i)
    {
        MyStruct current = mystruct[i];
        handleElement(current);
    }
}

Using pointers is the closest to call-by-reference available in C.

Android WebView progress bar

According to Md. Sajedul Karim answer I wrote a similar one.

webView = (WebView) view.findViewById(R.id.web);
progressBar = (ProgressBar) view.findViewById(R.id.progress);
webView.setWebChromeClient(new WebChromeClient());

setProgressBarVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        setProgressBarVisibility(View.VISIBLE);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        setProgressBarVisibility(View.GONE);
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        Toast.makeText(getActivity(), "Cannot load page", Toast.LENGTH_SHORT).show();
        setProgressBarVisibility(View.GONE);
    }
});

webView.loadUrl(url);

private void setProgressBarVisibility(int visibility) {
    // If a user returns back, a NPE may occur if WebView is still loading a page and then tries to hide a ProgressBar.
    if (progressBar != null) {
        progressBar.setVisibility(visibility);
    }
}

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

HTML - Alert Box when loading page

You can use a variety of methods, one uses Javascript window.onload function in a simple function call from a script or from the body as in the solutions above, you can also use jQuery to do this but its just a modification of Javascript...Just add Jquery to your header by pasting

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

to your head section and open another script tag where you display the alert when the DOM is ready i.e. `

<script>
    $("document").ready( function () {
        alert("Hello, world");
    }); 
</script>

`

This uses Jquery to run the function but since jQuery is a Javascript framework it contains Javascript code hence the Javascript alert function..hope this helps...

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

Kill detached screen session

add this to your ~/.bashrc:

alias cleanscreen="screen -ls | tail -n +2 | head -n -2 | awk '{print $1}'| xargs -I{} screen -S {} -X quit"

Then use cleanscreen to clean all screen session.

Eclipse will not start and I haven't changed anything

I deleted the workbench.xmi in the folder workspace/.metadata/.plugins/org.eclipse.e4.workbench/.

I got this error because a build hung and then I tried to quit. However, I had unsaved changes. This prompted the following errors in logfile about unsaved changes and jobs that are not finished.

MySQL: What's the difference between float and double?

Float has 32 bit (4 bytes) with 8 places accuracy. Double has 64 bit (8 bytes) with 16 places accuracy.

If you need better accuracy, use Double instead of Float.

How do I select between the 1st day of the current month and current day in MySQL?

SET @date:='2012-07-11';
SELECT date_add(date_add(LAST_DAY(@date),interval 1 DAY), 
       interval -1 MONTH) AS first_day

Excel formula to get week number in month (having Monday)

Finding of week number for each date of a month (considering Monday as beginning of the week)

Keep the first date of month contant $B$13

=WEEKNUM(B18,2)-WEEKNUM($B$13,2)+1

WEEKNUM(B18,2) - returns the week number of the date mentioned in cell B18

WEEKNUM($B$13,2) - returns the week number of the 1st date of month in cell B13

How do you import an Eclipse project into Android Studio now?

In newer versions of Android Studio, the best way to bring in an Eclipse/ADT (Android Development Tool) project is to import it directly into Android Studio; we used to recommend you export it from Eclipse to Gradle first, but we haven't been updating ADT often enough to keep pace with Android Studio.

In any event, if you choose "Import Project" from the File menu or from the Welcome screen when you launch Android Studio, it should take you through a specialized wizard that will prompt you that it intends to copy the files into a new directory structure instead of importing them in-place, and it will offer to fix up some common things like converting dependencies into Maven-style includes and such.

It doesn't seem like you're getting this specialized flow. I think it may not be recognizing your imported project as an ADT project, and it's defaulting to the old built-into-IntelliJ behavior which doesn't know about Gradle. To get the specialized import working, the following must be true:

  • The root directory of the project you import must have an AndroidManifest.xml file.
  • Either:
    • The root directory must contain the .project and .classpath files from Eclipse
  • or
    • The root directory must contain res and src directories.

If your project is complex, perhaps you're not pointing it as the root directory it wants to see for the import to succeed.

How to autosize a textarea using Prototype?

My solution not using jQuery (because sometimes they don't have to be the same thing) is below. Though it was only tested in Internet Explorer 7, so the community can point out all the reasons this is wrong:

textarea.onkeyup = function () { this.style.height = this.scrollHeight + 'px'; }

So far I really like how it's working, and I don't care about other browsers, so I'll probably apply it to all my textareas:

// Make all textareas auto-resize vertically
var textareas = document.getElementsByTagName('textarea');

for (i = 0; i<textareas.length; i++)
{
    // Retain textarea's starting height as its minimum height
    textareas[i].minHeight = textareas[i].offsetHeight;

    textareas[i].onkeyup = function () {
        this.style.height = Math.max(this.scrollHeight, this.minHeight) + 'px';
    }
    textareas[i].onkeyup(); // Trigger once to set initial height
}

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

How to print out all the elements of a List in Java?

I wrote a dump function, which basicly prints out the public members of an object if it has not overriden toString(). One could easily expand it to call getters. Javadoc:

Dumps an given Object to System.out, using the following rules:

  • If the Object is Iterable, all of its components are dumped.
  • If the Object or one of its superclasses overrides toString(), the "toString" is dumped
  • Else the method is called recursively for all public members of the Object

/**
 * Dumps an given Object to System.out, using the following rules:<br>
 * <ul>
 * <li> If the Object is {@link Iterable}, all of its components are dumped.</li>
 * <li> If the Object or one of its superclasses overrides {@link #toString()}, the "toString" is dumped</li>
 * <li> Else the method is called recursively for all public members of the Object </li>
 * </ul>
 * @param input
 * @throws Exception
 */
public static void dump(Object input) throws Exception{
    dump(input, 0);
}

private static void dump(Object input, int depth) throws Exception{
    if(input==null){
        System.out.print("null\n"+indent(depth));
        return;
    }

    Class<? extends Object> clazz = input.getClass();
    System.out.print(clazz.getSimpleName()+" ");
    if(input instanceof Iterable<?>){
        for(Object o: ((Iterable<?>)input)){
            System.out.print("\n"+indent(depth+1));
            dump(o, depth+1);
        }
    }else if(clazz.getMethod("toString").getDeclaringClass().equals(Object.class)){
        Field[] fields = clazz.getFields();
        if(fields.length == 0){
            System.out.print(input+"\n"+indent(depth));
        }
        System.out.print("\n"+indent(depth+1));
        for(Field field: fields){
            Object o = field.get(input);
            String s = "|- "+field.getName()+": ";
            System.out.print(s);
            dump(o, depth+1);
        }
    }else{

        System.out.print(input+"\n"+indent(depth));
    }
}

private static String indent(int depth) {
    StringBuilder sb = new StringBuilder();
    for(int i=0; i<depth; i++)
        sb.append("  ");
    return sb.toString();
}

Using the "start" command with parameters passed to the started program

The answer in "peculiarity" is correct and directly answers the question. As TimF answered, since the first parameter is in quotes, it is treated as a window title.

Also note that the Virtual PC options are being treated as options to the 'start' command itself, and are not valid for 'start'. This is true for all versions of Windows that have the 'start' command.

This problem with 'start' treating the quoted parameter as a title is even more annoying that just the posted problem. If you run this:

start "some valid command with spaces"

You get a new command prompt window, with the obvious result for a window title. Even more annoying, this new window doesn't inherit customized font, colors or window size, it's just the default for cmd.exe.

What's a concise way to check that environment variables are set in a Unix shell script?

Your question is dependent on the shell that you are using.

Bourne shell leaves very little in the way of what you're after.

BUT...

It does work, just about everywhere.

Just try and stay away from csh. It was good for the bells and whistles it added, compared the Bourne shell, but it is really creaking now. If you don't believe me, just try and separate out STDERR in csh! (-:

There are two possibilities here. The example above, namely using:

${MyVariable:=SomeDefault}

for the first time you need to refer to $MyVariable. This takes the env. var MyVariable and, if it is currently not set, assigns the value of SomeDefault to the variable for later use.

You also have the possibility of:

${MyVariable:-SomeDefault}

which just substitutes SomeDefault for the variable where you are using this construct. It doesn't assign the value SomeDefault to the variable, and the value of MyVariable will still be null after this statement is encountered.

Connect to SQL Server through PDO using SQL Server Driver

Mind you that in my experience and also of other (PHP - Why is new SQLSRV driver slower than the old mssql driver?) that using PDO_SQLSRV is way slower than through PDO_ODBC.

If you want to use the faster PDO_ODBC you can use:

//use any of these or check exact MSSQL ODBC drivername in "ODBC Data Source Administrator"
$mssqldriver = '{SQL Server}'; 
$mssqldriver = '{SQL Server Native Client 11.0}';
$mssqldriver = '{ODBC Driver 11 for SQL Server}';

$hostname='127.0.0.1';
$dbname='test';
$username='user';
$password='pw';
$dbDB = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=$dbname", $username, $password);

return query based on date

Just been implementing something similar in Mongo v3.2.3 using Node v0.12.7 and v4.4.4 and used:

{ $gte: new Date(dateVar).toISOString() }

I'm passing in an ISODate (e.g. 2016-04-22T00:00:00Z) and this works for a .find() query with or without the toISOString function. But when using in an .aggregate() $match query it doesn't like the toISOString function!

Does Java have something like C#'s ref and out keywords?

Actually there is neither ref nor out keyword equivalent in Java language as far as I know. However I've just transformed a C# code into Java that uses out parameter and will advise what I've just done. You should wrap whatever object into a wrapper class and pass the values wrapped in wrapper object instance as follows;

A Simple Example For Using Wrapper

Here is the Wrapper Class;

public class Wrapper {
    public Object ref1; // use this as ref
    public Object ref2; // use this as out

    public Wrapper(Object ref1) {
        this.ref1 = ref1;
    }
}

And here is the test code;

public class Test {

    public static void main(String[] args) {
        String abc = "abc";
        changeString(abc);
        System.out.println("Initial object: " + abc); //wont print "def"

        Wrapper w = new Wrapper(abc);
        changeStringWithWrapper(w);
        System.out.println("Updated object: " + w.ref1);
        System.out.println("Out     object: " + w.ref2);
    }

    // This won't work
    public static void changeString(String str) {
        str = "def";
    }

    // This will work
    public static void changeStringWithWrapper(Wrapper w) {
        w.ref1 = "def";
        w.ref2 = "And this should be used as out!";
    }

}

A Real World Example

A C#.NET method using out parameter

Here there is a C#.NET method that is using out keyword;

public bool Contains(T value)
{
    BinaryTreeNode<T> parent;
    return FindWithParent(value, out parent) != null;
}

private BinaryTreeNode<T> FindWithParent(T value, out BinaryTreeNode<T> parent)
{
    BinaryTreeNode<T> current = _head;
    parent = null;

    while(current != null)
    {
        int result = current.CompareTo(value);

        if (result > 0)
        {
            parent = current;
            current = current.Left;
        }
        else if (result < 0)
        {
            parent = current;
            current = current.Right;
        }
        else
        {
            break;
        }
    }

    return current;
}

Java Equivalent of the C# code that is using the out parameter

And the Java equivalent of this method with the help of wrapper class is as follows;

public boolean contains(T value) {
    BinaryTreeNodeGeneration<T> result = findWithParent(value);

    return (result != null);
}

private BinaryTreeNodeGeneration<T> findWithParent(T value) {
    BinaryTreeNode<T> current = head;
    BinaryTreeNode<T> parent = null;
    BinaryTreeNodeGeneration<T> resultGeneration = new BinaryTreeNodeGeneration<T>();
    resultGeneration.setParentNode(null);

    while(current != null) {
        int result = current.compareTo(value);

        if(result >0) {
            parent = current;
            current = current.left;
        } else if(result < 0) {
            parent = current;
            current = current.right;
        } else {
            break;
        }
    }

    resultGeneration.setChildNode(current);
    resultGeneration.setParentNode(parent);

    return resultGeneration;
}

Wrapper Class

And the wrapper class used in this Java code is as below;

public class BinaryTreeNodeGeneration<TNode extends Comparable<TNode>>  {

    private BinaryTreeNode<TNode>   parentNode;
    private BinaryTreeNode<TNode>   childNode;

    public BinaryTreeNodeGeneration() {
        this.parentNode = null;
        this.childNode = null;
    }

    public BinaryTreeNode<TNode> getParentNode() {
        return parentNode;
    }

    public void setParentNode(BinaryTreeNode<TNode> parentNode) {
        this.parentNode = parentNode;
    }

    public BinaryTreeNode<TNode> getChildNode() {
        return childNode;
    }

    public void setChildNode(BinaryTreeNode<TNode> childNode) {
        this.childNode = childNode;
    }

}

Using the AND and NOT Operator in Python

It's called and and or in Python.

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

You can use a double cast.

return (List<Customer>) (List) getList();

How should I store GUID in MySQL tables?

My DBA asked me when I asked about the best way to store GUIDs for my objects why I needed to store 16 bytes when I could do the same thing in 4 bytes with an Integer. Since he put that challenge out there to me I thought now was a good time to mention it. That being said...

You can store a guid as a CHAR(16) binary if you want to make the most optimal use of storage space.

How to extract text from a PDF file?

I recommend to use pymupdf or pdfminer.six.

Those packages are not maintained:

  • PyPDF2, PyPDF3, PyPDF4
  • pdfminer (without .six)

How to read pure text with pymupdf

There are different options which will give different results, but the most basic one is:

import fitz  # this is pymupdf

with fitz.open("my.pdf") as doc:
    text = ""
    for page in doc:
        text += page.getText()

print(text)

How do I get an empty array of any size in python?

You can't do exactly what you want in Python (if I read you correctly). You need to put values in for each element of the list (or as you called it, array).

But, try this:

a = [0 for x in range(N)]  # N = size of list you want
a[i] = 5  # as long as i < N, you're okay

For lists of other types, use something besides 0. None is often a good choice as well.

Can't bind to 'dataSource' since it isn't a known property of 'table'

  • Angular Core v6.0.2,
  • Angular Material, v6.0.2,
  • Angular CLI v6.0.0 (globally v6.1.2)

I had this issue when running ng test, so to fix it, I added to my xyz.component.spec.ts file:

import { MatTableModule } from '@angular/material';

And added it to imports section in TestBed.configureTestingModule({}):

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ReactiveFormsModule, HttpClientModule, RouterTestingModule, MatTableModule ],
      declarations: [ BookComponent ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
    .compileComponents();
}));

What REALLY happens when you don't free after malloc?

This code will usually work alright, but consider the problem of code reuse.

You may have written some code snippet which doesn't free allocated memory, it is run in such a way that memory is then automatically reclaimed. Seems allright.

Then someone else copies your snippet into his project in such a way that it is executed one thousand times per second. That person now has a huge memory leak in his program. Not very good in general, usually fatal for a server application.

Code reuse is typical in enterprises. Usually the company owns all the code its employees produce and every department may reuse whatever the company owns. So by writing such "innocently-looking" code you cause potential headache to other people. This may get you fired.

How to install pip in CentOS 7?

Below are the steps I followed to install python34 and pip

yum update -y
yum -y install yum-utils
yum -y groupinstall development
yum -y install https://centos7.iuscommunity.org/ius-release.rpm
yum makecache
yum -y install python34u  python34u-pip
python3.6 -v
echo "alias python=/usr/bin/python3.4" >> ~/.bash_profile
source ~/.bash_profile
pip3 install --upgrade pip

# if yum install python34u-pip doesnt work, try 

curl https://bootstrap.pypa.io/get-pip.py | python

How to show all shared libraries used by executables in Linux?

I didn't have ldd on my ARM toolchain so I used objdump:

$(CROSS_COMPILE)objdump -p

For instance:

objdump -p /usr/bin/python:

Dynamic Section:
  NEEDED               libpthread.so.0
  NEEDED               libdl.so.2
  NEEDED               libutil.so.1
  NEEDED               libssl.so.1.0.0
  NEEDED               libcrypto.so.1.0.0
  NEEDED               libz.so.1
  NEEDED               libm.so.6
  NEEDED               libc.so.6
  INIT                 0x0000000000416a98
  FINI                 0x000000000053c058
  GNU_HASH             0x0000000000400298
  STRTAB               0x000000000040c858
  SYMTAB               0x0000000000402aa8
  STRSZ                0x0000000000006cdb
  SYMENT               0x0000000000000018
  DEBUG                0x0000000000000000
  PLTGOT               0x0000000000832fe8
  PLTRELSZ             0x0000000000002688
  PLTREL               0x0000000000000007
  JMPREL               0x0000000000414410
  RELA                 0x0000000000414398
  RELASZ               0x0000000000000078
  RELAENT              0x0000000000000018
  VERNEED              0x0000000000414258
  VERNEEDNUM           0x0000000000000008
  VERSYM               0x0000000000413534

ImportError: No module named model_selection

In Late September 2016, SciKit Learn 0.18 was released and there was a slight change to the code. With SciKit Learn 0.18 the train_test_split function is now imported from model_selection instead of cross_validation.

from sklearn.cross_validation import train_test_split

has been changed to :

from sklearn.model_selection import train_test_split

The same has also happened for GridSearchCV.

PHP Include for HTML?

First: what the others said. Forget the echo statement and just write your navbar.php as a regular HTML file.

Second: your include paths are probably messed up. To make sure you include files that are in the same directory as the current file, use __DIR__:

include __DIR__.'/navbar.php'; // PHP 5.3 and later
include dirname(__FILE__).'/navbar.php'; // PHP 5.2

Why do we need to use flatMap?

When I started to have a look at Rxjs I also stumbled on that stone. What helped me is the following:

  • documentation from reactivex.io . For instance, for flatMap: http://reactivex.io/documentation/operators/flatmap.html
  • documentation from rxmarbles : http://rxmarbles.com/. You will not find flatMap there, you must look at mergeMap instead (another name).
  • the introduction to Rx that you have been missing: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754. It addresses a very similar example. In particular it addresses the fact that a promise is akin to an observable emitting only one value.
  • finally looking at the type information from RxJava. Javascript not being typed does not help here. Basically if Observable<T> denotes an observable object which pushes values of type T, then flatMap takes a function of type T' -> Observable<T> as its argument, and returns Observable<T>. map takes a function of type T' -> T and returns Observable<T>.

    Going back to your example, you have a function which produces promises from an url string. So T' : string, and T : promise. And from what we said before promise : Observable<T''>, so T : Observable<T''>, with T'' : html. If you put that promise producing function in map, you get Observable<Observable<T''>> when what you want is Observable<T''>: you want the observable to emit the html values. flatMap is called like that because it flattens (removes an observable layer) the result from map. Depending on your background, this might be chinese to you, but everything became crystal clear to me with typing info and the drawing from here: http://reactivex.io/documentation/operators/flatmap.html.

Create multiple threads and wait all of them to complete

If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.

Example:

List<Thread> threads = new List<Thread>();


// Start threads
for(int i = 0; i<10; i++)
{
    int tmp = i; // Copy value for closure
    Thread t = new Thread(() => Console.WriteLine(tmp));
    t.Start;
    threads.Add(t);
}

// Await threads
foreach(Thread thread in threads)
{
    thread.Join();
}

How can I add the sqlite3 module to Python?

I have python 2.7.3 and this solved my problem:

pip install pysqlite

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

Use formula in custom calculated field in Pivot Table

Some of it is possible, specifically accessing subtotals:

"In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)

enter image description here

  • And make sure the field in question is a number field that can be summed, it does not work for text fields for which only count is normally informative.

Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/

Two inline-block, width 50% elements wrap to second line

It is because display:inline-block takes into account white-space in the html. If you remove the white-space between the div's it works as expected. Live Example: http://jsfiddle.net/XCDsu/4/

<div id="col1">content</div><div id="col2">content</div>

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

While installing the node modules for mocha I had tried the below commands

  • npm install
  • npm install mocha
  • npm install --save-dev mocha
  • npm install mocha -g # to install it globally also

and on running or executing the mocha test I was trying

  • mocha test
  • npm run test
  • mocha test test\index.test.js
  • npm test

but I was getting the below error as:

'Mocha' is not recognized as internal or external command

So , after trying everything it came out to be just set the path to environment variables under the System Variables as:

C:\Program Files\nodejs\

and it worked :)

What is the "double tilde" (~~) operator in JavaScript?

That ~~ is a double NOT bitwise operator.

It is used as a faster substitute for Math.floor() for positive numbers. It does not return the same result as Math.floor() for negative numbers, as it just chops off the part after the decimal (see other answers for examples of this).

Anaconda Navigator won't launch (windows 10)

I struggled with this problem for a couple of hours (got the same error message you showed in your attachment). I knew the problem had to do with the path variable, specifically the PYTHONHOME variable.

I finally found I had set the PYTHONHOME path to the python.exe file (C:\Anaconda3\python.exe). It should be set to the Anaconda folder that contains the python.exe file (C:\Anaconda3).

After that I could run the Anaconda Navigator.

How to set Java SDK path in AndroidStudio?

Generally speaking, it is set in the "Project Structure" dialog.

Go to File > Project Structure > SDK Location. The third field is "JDK Location" where you can set it. This will set it for the current project.

enter image description here

To set the default for new projects, go to File > Other Settings > Default Project Structure > SDK Location and set the "JDK Location".

Older Versions

Go to File > Project Structure > [Platform Settings] > SDKs. You'll need to either update you current SDK configuration to use the new directory, or define a new one and then change your project's settings to use the new one. This will set it for the current project.

To set the default for new projects, go to File > Other Settings > Structure for New Projects > [Platform Settings] > SDKs and set the SDK to use when creating a new project.

Update multiple tables in SQL Server using INNER JOIN

You can update with a join if you only affect one table like this:

UPDATE table1 
SET table1.name = table2.name 
FROM table1, table2 
WHERE table1.id = table2.id 
AND table2.foobar ='stuff'

But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.

However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.

SQL JOINS

But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

Create boolean column in MySQL with false as default value?

Use ENUM in MySQL for true / false it gives and accepts the true / false values without any extra code.

ALTER TABLE `itemcategory` ADD `aaa` ENUM('false', 'true') NOT NULL DEFAULT 'false'

What is 'PermSize' in Java?

lace to store your loaded class definition and metadata. If a large code-base project is loaded, the insufficient Perm Gen size will cause the popular Java.Lang.OutOfMemoryError: PermGen.

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="..."> it will work.

Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module

Vue.js get selected option on @change

You can save your @change="onChange()" an use watchers. Vue computes and watches, it´s designed for that. In case you only need the value and not other complex Event atributes.

Something like:

  ...
  watch: {
    leaveType () {
      this.whateverMethod(this.leaveType)
    }
  },
  methods: {
     onChange() {
         console.log('The new value is: ', this.leaveType)
     }
  }

I need an unordered list without any bullets

To completely remove the ul default style:

    list-style-type: none;

    margin: 0;
    margin-block-start: 0;
    margin-block-end: 0;
    margin-inline-start: 0;
    margin-inline-end: 0;
    padding-inline-start: 0;

How to check whether mod_rewrite is enable on server?

This works on CentOS:

$ sudo httpd -M |grep rewrite_module

Should output rewrite_module (shared)

VBA Convert String to Date

Try using Replace to see if it will work for you. The problem as I see it which has been mentioned a few times above is the CDate function is choking on the periods. You can use replace to change them to slashes. To answer your question about a Function in vba that can parse any date format, there is not any you have very limited options.

Dim current as Date, highest as Date, result() as Date 
For Each itemDate in DeliveryDateArray
    Dim tempDate As String
    itemDate = IIf(Trim(itemDate) = "", "0", itemDate) 'Added per OP's request.
    tempDate = Replace(itemDate, ".", "/")
    current = Format(CDate(tempDate),"dd/mm/yyyy")
    if current > highest then 
        highest = current 
    end if 
    ' some more operations an put dates into result array 
Next itemDate 
'After activating final sheet... 
Range("A1").Resize(UBound(result), 1).Value = Application.Transpose(result) 

How do I find where JDK is installed on my windows machine?

Plain and simple on Windows platforms:

where java

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

Why is volatile needed in C?

As rightly suggested by many here, the volatile keyword's popular use is to skip the optimisation of the volatile variable.

The best advantage that comes to mind, and worth mentioning after reading about volatile is -- to prevent rolling back of the variable in case of a longjmp. A non-local jump.

What does this mean?

It simply means that the last value will be retained after you do stack unwinding, to return to some previous stack frame; typically in case of some erroneous scenario.

Since it'd be out of scope of this question, I am not going into details of setjmp/longjmp here, but it's worth reading about it; and how the volatility feature can be used to retain the last value.

Item frequency count in Python

Can't you just use count?

words = 'the quick brown fox jumps over the lazy gray dog'
words.count('z')
#output: 1

How to read file with space separated values in pandas

you can use regex as the delimiter:

pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")

How to disable anchor "jump" when loading a page?

While the accepted answer does work well, I did find that sometimes, especially on pages containing large images that the scroll bar will jump about wildly using

 window.scrollTo(0, 0);

Which can be quite distracting for the user.

The solution I settled on in the end is actually pretty simple, and that's to use a different ID on the target to the one used in location.hash

Eg:

Here is the link on some other page

<a href="/page/with/tabs#tab2">Some info found in tab2 on tabs page</a>

So of course if there is an element with an ID of tab2 on the tabs page the window will jump to it on load.

So you can append something to the ID to prevent it:

<div id="tab2-noScroll">tab2 content</div>

And then you can append "-noScroll" to location.hash in the javascript:

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

        var tabContent = $(".tab_content");
        var tabs = $("#menu li");
        var hash = window.location.hash;


     tabContent.not(hash + '-noScroll').hide();                           
        if(hash=="") {       //^ here
      $('#tab1-noScroll').fadeIn();
     }
        tabs.find('[href=' + hash + ']').parent().addClass('active');

        tabs.click(function() {
            $(this).addClass('active').siblings().removeClass('active');
            tabContent.hide();
            var activeTab = $(this).find("a").attr("href") + '-noScroll'; 
                                                               //^ and here

            $(activeTab).fadeIn();
           return false;
        });

    });
</script>

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

Get rid of your quotes around your command. When you quote it, docker tries to run the full string "lsb_release -a" as a command, which doesn't exist. Instead, you want to run the command lsb_release with an argument -a, and no quotes.

sudo docker exec -it c44f29d30753 lsb_release -a

Note, everything after the container name is the command and arguments to run inside the container, docker will not process any of that as options to the docker command.

Remove all unused resources from an android project

Maybe useful Andround Unused Resources is a Java application that will scan your project for unused resources. Unused resources needlessly take up space, increase the build time, and clutter the IDE's autocomplete list.

To use it, ensure your working directory is the root of your Android project, and run:

java -jar AndroidUnusedResources.jar

https://code.google.com/p/android-unused-resources/

How to register ASP.NET 2.0 to web server(IIS7)?

I got it resolved by doing Repir on .NET framework Extended, in Add/Remove program ;

Using win2008R2, .NET framework 4.0

Run a controller function whenever a view is opened/shown

Considering Ionic's ability to cache view elements and scope data mentioned above, this might be another way of doing, if you want to run the controller every time the view gets loaded. You can globally disable the caching mechanism used by ionic by doing:

$ionicConfigProvider.views.maxCache(0);

Else, the way I had it working for me was doing

$scope.$on("$ionicView.afterLeave", function () {
     $ionicHistory.clearCache();
}); 

This is to clear the cache before leaving the view to re-run controller every time you enter back again.

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

Validate fields after user has left a field

I solved this by expanding on what @jlmcdonald suggested. I created a directive that would automatically be applied to all input and select elements:

var blurFocusDirective = function () {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, elm, attr, ctrl) {
            if (!ctrl) {
                return;
            }

            elm.on('focus', function () {
                elm.addClass('has-focus');

                scope.$apply(function () {
                    ctrl.hasFocus = true;
                });
            });

            elm.on('blur', function () {
                elm.removeClass('has-focus');
                elm.addClass('has-visited');

                scope.$apply(function () {
                    ctrl.hasFocus = false;
                    ctrl.hasVisited = true;
                });
            });

            elm.closest('form').on('submit', function () {
                elm.addClass('has-visited');

                scope.$apply(function () {
                    ctrl.hasFocus = false;
                    ctrl.hasVisited = true;
                });
            });

        }
    };
};

app.directive('input', blurFocusDirective);
app.directive('select', blurFocusDirective);

This will add has-focus and has-visited classes to various elements as the user focuses/visits the elements. You can then add these classes to your CSS rules to show validation errors:

input.has-visited.ng-invalid:not(.has-focus) {
    background-color: #ffeeee;   
}

This works well in that elements still get $invalid properties etc, but the CSS can be used to give the user a better experience.

How to implement a confirmation (yes/no) DialogPreference?

Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below

intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
    Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);

    intentClearCookies.setIntent(clearcookies);
    intentClearCookies.setTitle(R.string.ClearCookies);
    intentClearCookies.setEnabled(true);
    launchPrefCat.addPreference(intentClearCookies);

And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.

public class ClearCookies extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    showDialog();
}

/**
 * @throws NotFoundException
 */
private void showDialog() throws NotFoundException {
    new AlertDialog.Builder(this)
            .setTitle(getResources().getString(R.string.ClearCookies))
            .setMessage(
                    getResources().getString(R.string.ClearCookieQuestion))
            .setIcon(
                    getResources().getDrawable(
                            android.R.drawable.ic_dialog_alert))
            .setPositiveButton(
                    getResources().getString(R.string.PostiveYesButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here

                        }
                    })
            .setNegativeButton(
                    getResources().getString(R.string.NegativeNoButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here
                        }
                    }).show();
}}

As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.

json_encode sparse PHP array as JSON array, not JSON object

Try this,

<?php
$arr1=array('result1'=>'abcd','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
print (json_encode($arr3)); 
?>

select a value where it doesn't exist in another table

For your first question there are at least three common methods to choose from:

  • NOT EXISTS
  • NOT IN
  • LEFT JOIN

The SQL looks like this:

SELECT * FROM TableA WHERE NOT EXISTS (
    SELECT NULL
    FROM TableB
    WHERE TableB.ID = TableA.ID
)

SELECT * FROM TableA WHERE ID NOT IN (
    SELECT ID FROM TableB
)

SELECT TableA.* FROM TableA 
LEFT JOIN TableB
ON TableA.ID = TableB.ID
WHERE TableB.ID IS NULL

Depending on which database you are using, the performance of each can vary. For SQL Server (not nullable columns):

NOT EXISTS and NOT IN predicates are the best way to search for missing values, as long as both columns in question are NOT NULL.

Get file name from URI string in C#

Uri.IsFile doesn't work with http urls. It only works for "file://". From MSDN : "The IsFile property is true when the Scheme property equals UriSchemeFile." So you can't depend on that.

Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.LocalPath);

Bootstrap table without stripe / borders

In some cases, one must also use border-spacing in the table class, like:

border-spacing: 0 !important;

How to set custom ActionBar color / style?

in the style.xml add this code

<resources>
    <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/MyAction</item>
    </style>

    <style name="MyActionBarTheme" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">#333333</item>
    </style>
</resources>

Convert hex string to int

An additional option to the ones suggested, is to use the BigInteger class. Since hex values are often large numbers, such as sha256 or sha512 values, they will easily overflow an int and a long. While converting to a byte array is an option as other answers show, BigInterger, the often forgotten class in java, is an option as well.

String sha256 = "65f4b384672c2776116d8d6533c69d4b19d140ddec5c191ea4d2cfad7d025ca2";
BigInteger value = new BigInteger(sha256, 16);
System.out.println("value = " + value);
// 46115947372890196580627454674591875001875183744738980595815219240926424751266

How to use regex with find command?

The -regex find expression matches the whole name, including the relative path from the current directory. For find . this always starts with ./, then any directories.

Also, these are emacs regular expressions, which have other escaping rules than the usual egrep regular expressions.

If these are all directly in the current directory, then

find . -regex '\./[a-f0-9\-]\{36\}\.jpg'

should work. (I'm not really sure - I can't get the counted repetition to work here.) You can switch to egrep expressions by -regextype posix-egrep:

find . -regextype posix-egrep -regex '\./[a-f0-9\-]{36}\.jpg'

(Note that everything said here is for GNU find, I don't know anything about the BSD one which is also the default on Mac.)

Sum one number to every element in a list (or array) in Python

if you want to operate with list of numbers it is better to use NumPy arrays:

import numpy
a = [1, 1, 1 ,1, 1]
ar = numpy.array(a)
print ar + 2

gives

[3, 3, 3, 3, 3]

What is Join() in jQuery?

The practical use of this construct? It is a javascript replaceAll() on strings.

var s = 'stackoverflow_is_cool';  
s = s.split('_').join(' ');  
console.log(s);

will output:

stackoverflow is cool

MVC Razor Radio Button

This works for me.

@{ var dic = new Dictionary<string, string>() { { "checked", "" } }; }
@Html.RadioButtonFor(_ => _.BoolProperty, true, (@Model.BoolProperty)? dic: null) Yes
@Html.RadioButtonFor(_ => _.BoolProperty, false, ([email protected])? dic: null) No

iOS application: how to clear notifications?

Update for iOS 10 (Swift 3)

In order to clear all local notifications in iOS 10 apps, you should use the following code:

import UserNotifications

...

if #available(iOS 10.0, *) {
    let center = UNUserNotificationCenter.current()
    center.removeAllPendingNotificationRequests() // To remove all pending notifications which are not delivered yet but scheduled.
    center.removeAllDeliveredNotifications() // To remove all delivered notifications
} else {
    UIApplication.shared.cancelAllLocalNotifications()
}

This code handles the clearing of local notifications for iOS 10.x and all preceding versions of iOS. You will need to import UserNotifications for the iOS 10.x code.

How to get all the AD groups for a particular user?

This code works even faster (two 1.5 faster than my previous version):

    public List<String> GetUserGroups(WindowsIdentity identity)
    {
        List<String> groups = new List<String>();

        String userName = identity.Name;
        int pos = userName.IndexOf(@"\");
        if (pos > 0) userName = userName.Substring(pos + 1);

        PrincipalContext domain = new PrincipalContext(ContextType.Domain, "riomc.com");
        UserPrincipal user = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, userName); // NGeodakov

        DirectoryEntry de = new DirectoryEntry("LDAP://RIOMC.com");
        DirectorySearcher search = new DirectorySearcher(de);
        search.Filter = "(&(objectClass=group)(member=" + user.DistinguishedName + "))";
        search.PropertiesToLoad.Add("cn");
        search.PropertiesToLoad.Add("samaccountname");
        search.PropertiesToLoad.Add("memberOf");

        SearchResultCollection results = search.FindAll();
        foreach (SearchResult sr in results)
        {
            GetUserGroupsRecursive(groups, sr, de);
        }

        return groups;
    }

    public void GetUserGroupsRecursive(List<String> groups, SearchResult sr, DirectoryEntry de)
    {
        if (sr == null) return;

        String group = (String)sr.Properties["cn"][0];
        if (String.IsNullOrEmpty(group))
        {
            group = (String)sr.Properties["samaccountname"][0];
        }
        if (!groups.Contains(group))
        {
            groups.Add(group);
        }

        DirectorySearcher search;
        SearchResult sr1;
        String name;
        int equalsIndex, commaIndex;
        foreach (String dn in sr.Properties["memberof"])
        {
            equalsIndex = dn.IndexOf("=", 1);
            if (equalsIndex > 0)
            {
                commaIndex = dn.IndexOf(",", equalsIndex + 1);
                name = dn.Substring(equalsIndex + 1, commaIndex - equalsIndex - 1);

                search = new DirectorySearcher(de);
                search.Filter = "(&(objectClass=group)(|(cn=" + name + ")(samaccountname=" + name + ")))";
                search.PropertiesToLoad.Add("cn");
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("memberOf");
                sr1 = search.FindOne();
                GetUserGroupsRecursive(groups, sr1, de);
            }
        }
    }

Sort Array of object by object field in Angular 6

Try this

products.sort(function (a, b) {
  return a.title.rendered - b.title.rendered;
});

OR

You can import lodash/underscore library, it has many build functions available for manipulating, filtering, sorting the array and all.

Using underscore: (below one is just an example)

import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title'); 

Fatal error: [] operator not supported for strings

You get this error when attempting to use the short array push syntax on a string.

For example, this

$foo = 'foo';
$foo[] = 'bar'; // ERROR!

I'd hazard a guess that one or more of your $name, $date, $text or $date2 variables has been initialised as a string.

Edit: Looking again at your question, it looks like you don't actually want to use them as arrays as you're treating them as strings further down.

If so, change your assignments to

$name = $row['name'];
$date = $row['date'];
$text = $row['text'];
$date2 = $row['date2'];

It seems there are some issues with PHP 7 and code using the empty-index array push syntax.

To make it clear, these work fine in PHP 7+

$previouslyUndeclaredVariableName[] = 'value'; // creates an array and adds one entry

$emptyArray = []; // creates an array
$emptyArray[] = 'value'; // pushes in an entry

What does not work is attempting to use empty-index push on any variable declared as a string, number, object, etc, ie

$declaredAsString = '';
$declaredAsString[] = 'value';

$declaredAsNumber = 1;
$declaredAsNumber[] = 'value';

$declaredAsObject = new stdclass();
$declaredAsObject[] = 'value';

All result in a fatal error.

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

Nested rows with bootstrap grid system?

Bootstrap Version 3.x

As always, read Bootstrap's great documentation:

3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting

Make sure the parent level row is inside of a .container element. Whenever you'd like to nest rows, just open up a new .row inside of your column.

Here's a simple layout to work from:

<div class="container">
    <div class="row">
        <div class="col-xs-6">
            <div class="big-box">image</div>
        </div>
        <div class="col-xs-6">
            <div class="row">
                <div class="col-xs-6"><div class="mini-box">1</div></div>
                <div class="col-xs-6"><div class="mini-box">2</div></div>
                <div class="col-xs-6"><div class="mini-box">3</div></div>
                <div class="col-xs-6"><div class="mini-box">4</div></div>
            </div>
        </div>
    </div>
</div>

Bootstrap Version 4.0

4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting

Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature

<div class="container">
  <div class="row">
    <div class="col big-box">
      image
    </div>

    <div class="col">
      <div class="row">
        <div class="col mini-box">1</div>
        <div class="col mini-box">2</div>
      </div>
      <div class="row">
        <div class="col mini-box">3</div>
        <div class="col mini-box">4</div>
      </div>
    </div>

  </div>
</div>

Demo in Fiddle jsFiddle 3.x | jsFiddle 4.0

Which will look like this (with a little bit of added styling):

screenshot

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How to use conditional breakpoint in Eclipse?

A way that might be more convenient: where you want a breakpoint, write a no-op if statement and set a breakpoint in its contents.

if(tablist[i].equalsIgnoreCase("LEADDELEGATES")) {
-->    int noop = 0; //don't do anything
}

(the breakpoint is represented by the arrow)

This way, the breakpoint only triggers if your condition is true. This could potentially be easier without that many pop-ups.

Ellipsis for overflow text in dropdown boxes

CSS file

.selectDD {
 overflow: hidden;
 white-space: nowrap;
 text-overflow: ellipsis;     
}

JS file

$(document).ready(function () {
    $("#selectDropdownID").next().children().eq(0).addClass("selectDD");
});

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

Simple pagination in javascript

So you can use a library for pagination logic https://github.com/pagino/pagino-js

How to get VM arguments from inside of Java application?

I haven't tried specifically getting the VM settings, but there is a wealth of information in the JMX utilities specifically the MXBean utilities. This would be where I would start. Hopefully you find something there to help you.

The sun website has a bunch on the technology:

http://java.sun.com/javase/6/docs/technotes/guides/management/mxbeans.html

get next and previous day with PHP

always make sure to have set your default timezone

date_default_timezone_set('Europe/Berlin');

create DateTime instance, holding the current datetime

$datetime = new DateTime();

create one day interval

$interval = new DateInterval('P1D');

modify the DateTime instance

$datetime->sub($interval);

display the result, or print_r($datetime); for more insight

echo $datetime->format('Y-m-d');

TIP:

If you don't want to change the default timezone, use the DateTimeZone class instead.

$myTimezone = new DateTimeZone('Europe/Berlin');
$datetime->setTimezone($myTimezone); 

or just include it inside the constructor in this form new DateTime("now", $myTimezone);

How to save a data.frame in R?

If you are only saving a single object (your data frame), you could also use saveRDS.
To save:

saveRDS(foo, file="data.Rda")

Then read it with:

bar <- readRDS(file="data.Rda")

The difference between saveRDS and save is that in the former only one object can be saved and the name of the object is not forced to be the same after you load it.

sqlite3.OperationalError: unable to open database file

had the same problem but top answer is too long for me so I suggest to open another shell window type cd #enter and try again

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 add Action bar options menu in Android Fragments

You need to call setHasOptionsMenu(true) in onCreate().

For backwards compatibility it's better to place this call as late as possible at the end of onCreate() or even later in onActivityCreated() or something like that.

See: https://developer.android.com/reference/android/app/Fragment.html#setHasOptionsMenu(boolean)

What's the difference between the Window.Loaded and Window.ContentRendered events

This is not about the difference between Window.ContentRendered and Window.Loaded but about what how the Window.Loaded event can be used:

I use it to avoid splash screens in all applications which need a long time to come up.

    // initializing my main window
    public MyAppMainWindow()
    {
        InitializeComponent();

        // Set the event
        this.ContentRendered += MyAppMainWindow_ContentRendered;
    }

    private void MyAppMainWindow_ContentRendered(object sender, EventArgs e)
    {
        // ... comes up quick when the controls are loaded and rendered

        // unset the event
        this.ContentRendered -= MyAppMainWindow_ContentRendered;

        // ... make the time comsuming init stuff here
    }

Access to Image from origin 'null' has been blocked by CORS policy

A solution to this is to serve your code, and make it run on a server, you could use web server for chrome to easily serve your pages.

"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

I had this problem with an F# project that had been here and there between Visual Studio and MonoDevelop, perhaps originating in the latter (I forget). In VS, the optimize box was unchecked, yet optimization certainly seemed to be occuring as far as the debugger was concerned.

After comparing the XML of the project file against that of a healthy one, the problem was obvious: the healthy project had an explicit <optimize>false</optimize> line, whereas the bad one was missing it completely. VS was obviously inferring from its absence that optimization was disabled, while the compiler was doing the opposite.

The solution was to add this property to the project file, and reload.

Conversion of a datetime2 data type to a datetime data type results out-of-range value

The Entity Framework 4 works with the datetime2 data type so in db the corresponding field must be datetime2 for SQL Server 2008.

To achive the solution there are two ways.

  1. To use the datetime data type in Entity Framwork 4 you have to switch the ProviderManifestToken in the edmx-file to "2005".
  2. If you set corresponding field as Allow Null (it converts it to NULLABLE) so then EF automatically uses date objects as datetime.

How to Initialize char array from a string

Here is obscure solution: define macro function:

#define Z(x) \
        (x==0 ? 'A' : \
        (x==1 ? 'B' : \
        (x==2 ? 'C' : '\0')))

char x[] = { Z(0), Z(1), Z(2) };

c# replace \" characters

\ => \\ and " => \"

so Replace("\\\"","")

Python Library Path

You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to:

import sys
sys.path.append('/home/user/python-libs')

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

Add horizontal scrollbar to html table

I couldn't get any of the above solutions to work. However, I found a hack:

_x000D_
_x000D_
body {_x000D_
  background-color: #ccc;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  width: 300px;_x000D_
  background-color: white;_x000D_
}_x000D_
_x000D_
table {_x000D_
  width: 100%;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
/* try removing the "hack" below to see how the table overflows the .body */_x000D_
.hack1 {_x000D_
  display: table;_x000D_
  table-layout: fixed;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.hack2 {_x000D_
  display: table-cell;_x000D_
  overflow-x: auto;_x000D_
  width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
  <div class="hack1">_x000D_
    <div class="hack2">_x000D_
_x000D_
      <table>_x000D_
        <tr>_x000D_
          <td>table or other arbitrary content</td>_x000D_
          <td>that will cause your page to stretch</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>uncontrollably</td>_x000D_
          <td>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can one change the timestamp of an old commit in Git?

Use git filter-branch with an env filter that sets GIT_AUTHOR_DATE and GIT_COMMITTER_DATE for the specific hash of the commit you're looking to fix.

This will invalidate that and all future hashes.

Example:

If you wanted to change the dates of commit 119f9ecf58069b265ab22f1f97d2b648faf932e0, you could do so with something like this:

git filter-branch --env-filter \
    'if [ $GIT_COMMIT = 119f9ecf58069b265ab22f1f97d2b648faf932e0 ]
     then
         export GIT_AUTHOR_DATE="Fri Jan 2 21:38:53 2009 -0800"
         export GIT_COMMITTER_DATE="Sat May 19 01:01:01 2007 -0700"
     fi'

How to set the default value for radio buttons in AngularJS?

<input type="radio" name="gender" value="male"<%=rs.getString(6).equals("male") ? "checked='checked'": "" %>: "checked='checked'" %> >Male
               <%=rs.getString(6).equals("male") ? "checked='checked'": "" %>

Simple way to understand Encapsulation and Abstraction

Well I will explain abstraction with a real world example. Say in your house you do have an electric plug and many devices can connect to the same plug but plug will never have an idea which device it is connected to, in other words the details of the devices is abstracted (hidden) to the plug.

Think what if we connect a device directly to electric wire without a plug? Say connect a bulb directly to a wire, then wire knows which device it is connected to and when ever we need to replace the bulb then we have to remove the wire connection from the bulb, which means bulb is tightly coupled with the wire. In other words bulb and wire knows the details where it is connected to, means not abstracted.

In object oriented world abstraction works exactly same. The class which consume other classes function/property doesn't need to know which classes function/property it is consuming and everything should be abstracted with an interface / abstract class.

Let me code the same example. Here I have a class "ElectricPlug", which is running a device. But the class "ElectricPlug" doesn't have any idea which device it is running. It can be any class implementing the interface "IDevice", which means the implementation of "RunDevice" is abstracted from "ElectricPlug". Here is the full sample code,

class Program
{
    static void Main(string[] args)
    {
        ElectricPlug electricPlug = new ElectricPlug(new Bulb());
    }
}

public class ElectricPlug
{
    private readonly IDevice _device;
    public ElectricPlug(IDevice device)
    {
        _device = device;
    }

    public void Run()
    {
        _device.Rundevice();
    }
}


public interface IDevice
{
    void Rundevice();
}


public class Bulb : IDevice
{
    public void Rundevice()
    {
       Console.WriteLine("Switched on bulb");
    }
}

java - iterating a linked list

As the definition of Linkedlist says, it is a sequence and you are guaranteed to get the elements in order.

eg:

import java.util.LinkedList;

public class ForEachDemonstrater {
  public static void main(String args[]) {
    LinkedList<Character> pl = new LinkedList<Character>();
    pl.add('j');
    pl.add('a');
    pl.add('v');
    pl.add('a');
    for (char s : pl)
      System.out.print(s+"->");
  }
}

initializing strings as null vs. empty string

There's a function empty() ready for you in std::string:

std::string a;
if(a.empty())
{
    //do stuff. You will enter this block if the string is declared like this
}

or

std::string a;
if(!a.empty())
{
    //You will not enter this block now
}
a = "42";
if(!a.empty())
{
    //And now you will enter this block.
}

What is a handle in C++?

In C++/CLI, a handle is a pointer to an object located on the GC heap. Creating an object on the (unmanaged) C++ heap is achieved using new and the result of a new expression is a "normal" pointer. A managed object is allocated on the GC (managed) heap with a gcnew expression. The result will be a handle. You can't do pointer arithmetic on handles. You don't free handles. The GC will take care of them. Also, the GC is free to relocate objects on the managed heap and update the handles to point to the new locations while the program is running.

Best way to randomize an array with .NET

Randomizing the array is intensive as you have to shift around a bunch of strings. Why not just randomly read from the array? In the worst case you could even create a wrapper class with a getNextString(). If you really do need to create a random array then you could do something like

for i = 0 -> i= array.length * 5
   swap two strings in random places

The *5 is arbitrary.

How do I run git log to see changes only for a specific branch?

For those using Magit, hit l and =m to toggle --no-merges and =pto toggle --first-parent.

Then either just hit l again to show commits from the current branch (with none of commits merged onto it) down to end of history, or, if you want the log to end where it was branched off from master, hit o and type master.. as your range:

enter image description here

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

It might be easier for you to understand using Functionoids which are expressively neater and more powerful to use, see this excellent and highly recommended C++ FAQ lite, in particular, look at section 33.12 onwards, but nonetheless, read it from the start of that section to gain a grasp and understanding of it.

To answer your question:

typedef void (*foobar)() fubarfn;

void Fun(fubarfn& baz){
   fubarfn = baz;
   baz();
}

Edit:

  • & means the reference address
  • * means the value of what's contained at the reference address, called de-referencing

So using the reference, example below, shows that we are passing in a parameter, and directly modify it.

void FunByRef(int& iPtr){
    iPtr = 2;
}

int main(void){
    // ...
    int n;
    FunByRef(n);
    cout << n << endl; // n will have value of 2
}

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

Finding the length of a Character Array in C

By saying "Character array" you mean a string? Like "hello" or "hahaha this is a string of characters"..

Anyway, use strlen(). Read a bit about it, there's plenty of info about it, like here.

Call to a member function fetch_assoc() on boolean in <path>

You have to update the php.ini config file with in your host provider's server, trust me on this, more than likely there is nothing wrong with your code. It took me almost a month and a half to realize that most hosting servers are not up to date on php.ini files, eg. php 5.5 or later, I believe.

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

When and where to use GetType() or typeof()?

You may find it easier to use the is keyword:

if (mycontrol is TextBox)

Call and receive output from Python script in Java?

You can include the Jython library in your Java Project. You can download the source code from the Jython project itself.

Jython does offers support for JSR-223 which basically lets you run a Python script from Java.

You can use a ScriptContext to configure where you want to send your output of the execution.

For instance, let's suppose you have the following Python script in a file named numbers.py:

for i in range(1,10):
    print(i)

So, you can run it from Java as follows:

public static void main(String[] args) throws ScriptException, IOException {

    StringWriter writer = new StringWriter(); //ouput will be stored here

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptContext context = new SimpleScriptContext();

    context.setWriter(writer); //configures output redirection
    ScriptEngine engine = manager.getEngineByName("python");
    engine.eval(new FileReader("numbers.py"), context);
    System.out.println(writer.toString()); 
}

And the output will be:

1
2
3
4
5
6
7
8
9

As long as your Python script is compatible with Python 2.5 you will not have any problems running this with Jython.

How do I redirect to another webpage?

It would help if you were a little more descriptive in what you are trying to do. If you are trying to generate paged data, there are some options in how you do this. You can generate separate links for each page that you want to be able to get directly to.

<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...

Note that the current page in the example is handled differently in the code and with CSS.

If you want the paged data to be changed via AJAX, this is where jQuery would come in. What you would do is add a click handler to each of the anchor tags corresponding to a different page. This click handler would invoke some jQuery code that goes and fetches the next page via AJAX and updates the table with the new data. The example below assumes that you have a web service that returns the new page data.

$(document).ready( function() {
    $('a.pager-link').click( function() {
        var page = $(this).attr('href').split(/\?/)[1];
        $.ajax({
            type: 'POST',
            url: '/path-to-service',
            data: page,
            success: function(content) {
               $('#myTable').html(content);  // replace
            }
        });
        return false; // to stop link
    });
});

Convert String to Uri

You can use the parse static method from Uri

//...
import android.net.Uri;
//...

Uri myUri = Uri.parse("http://stackoverflow.com")

How to use format() on a moment.js duration?

You don't need .format. Use durations like this:

const duration = moment.duration(83, 'seconds');
console.log(duration.minutes() + ':' +duration.seconds());
// output: 1:23

I found this solution here: https://github.com/moment/moment/issues/463

EDIT:

And with padding for seconds, minutes and hours:

const withPadding = (duration) => {
    if (duration.asDays() > 0) {
        return 'at least one day';
    } else {
        return [
            ('0' + duration.hours()).slice(-2),
            ('0' + duration.minutes()).slice(-2),
            ('0' + duration.seconds()).slice(-2),
        ].join(':')
    }
}

withPadding(moment.duration(83, 'seconds'))
// 00:01:23

withPadding(moment.duration(6048000, 'seconds'))
// at least one day

Find and extract a number from a string

here is my solution

string var = "Hello345wor705Ld";
string alpha = string.Empty;
string numer = string.Empty;
foreach (char str in var)
{
    if (char.IsDigit(str))
        numer += str.ToString();
    else
        alpha += str.ToString();
}
Console.WriteLine("String is: " + alpha);
Console.WriteLine("Numeric character is: " + numer);
Console.Read();

What does "|=" mean? (pipe equal operator)

You have already got sufficient answer for your question. But may be my answer help you more about |= kind of binary operators.

I am writing table for bitwise operators:
Following are valid:

----------------------------------------------------------------------------------------
Operator   Description                                   Example
----------------------------------------------------------------------------------------
|=        bitwise inclusive OR and assignment operator   C |= 2 is same as C = C | 2
^=        bitwise exclusive OR and assignment operator   C ^= 2 is same as C = C ^ 2
&=        Bitwise AND assignment operator                C &= 2 is same as C = C & 2
<<=       Left shift AND assignment operator             C <<= 2 is same as C = C << 2
>>=       Right shift AND assignment operator            C >>= 2 is same as C = C >> 2  
----------------------------------------------------------------------------------------

note all operators are binary operators.

Also Note: (for below points I wanted to add my answer)

  • >>> is bitwise operator in Java that is called Unsigned shift
    but >>>= not an operator in Java. >>>= operator

  • ~ is bitwise complement bits, 0 to 1 and 1 to 0 (Unary operator) but ~= not an operator.

  • Additionally, ! Called Logical NOT Operator, but != Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. e.g. (A != B) is true. where as A=!B means if B is true then A become false (and if B is false then A become true).

side note: | is not called pipe, instead its called OR, pipe is shell terminology transfer one process out to next..

ggplot2 legend to bottom and horizontal

If you want to move the position of the legend please use the following code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")

This should give you the desired result. Legend at bottom

How to select all textareas and textboxes using jQuery?

$('input[type=text], textarea').css({width: '90%'});

That uses standard CSS selectors, jQuery also has a set of pseudo-selector filters for various form elements, for example:

$(':text').css({width: '90%'});

will match all <input type="text"> elements. See Selectors documentation for more info.

How to handle button clicks using the XML onClick within Fragments

As I see answers they're somehow old. Recently Google introduce DataBinding which is much easier to handle onClick or assigning in your xml.

Here is good example which you can see how to handle this :

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <variable name="handlers" type="com.example.Handlers"/>
       <variable name="user" type="com.example.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.firstName}"
           android:onClick="@{user.isFriend ? handlers.onClickFriend : handlers.onClickEnemy}"/>
       <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.lastName}"
           android:onClick="@{user.isFriend ? handlers.onClickFriend : handlers.onClickEnemy}"/>
   </LinearLayout>
</layout>

There is also very nice tutorial about DataBinding you can find it Here.

DB query builder toArray() laravel 4

If you prefer to use Query Builder instead of Eloquent here is the solutions

$result = DB::table('user')->where('name',=,'Jhon')->get();

First Solution

$array = (array) $result;

Second Solution

$array = get_object_vars($result);

Third Solution

$array = json_decode(json_encode($result), true);

hope it may help

What Are Some Good .NET Profilers?

AQTime is reasonable, but has a bit of a learning curve and isn't as easy to use as the built in one in Team Suite

Getting a machine's external IP address with Python

In [1]: import stun

stun.get_ip_info()
('Restric NAT', 'xx.xx.xx.xx', 55320)

How do I hide certain files from the sidebar in Visual Studio Code?

I would also like to recommend vscode extension Peep, which allows you to toggle hide on the excluded files in your projects settings.json.

Hit F1 for vscode command line (command palette), then

ext install [enter] peep [enter]

You can bind "extension.peepToggle" to a key like Ctrl+Shift+P (same as F1 by default) for easy toggling. Hit Ctrl+K Ctrl+S for key bindings, enter peep, select Peep Toggle and add your binding.

Download image with JavaScript

As @Ian explained, the problem is that jQuery's click() is not the same as the native one.

Therefore, consider using vanilla-js instead of jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

Demo

Error "library not found for" after putting application in AdMob

For my case Xcode 7, also worked in Xcode 9.1

ld: library not found for -ldAfnetworking
clang: error: linker command failed with exit code 1 (use -v to see invocation)

set Build Active architecture Only to Yes

enter image description here

Can the Android layout folder contain subfolders?

I think the most elegant solution to this problem (given that subfolders are not allowed) is to prepend the file names with the name of the folder you would have placed it inside of. For example, if you have a bunch of layouts for an Activity, Fragment, or just general view called "places" then you should just prepend it with places_my_layout_name. At least this solves the problem of organizing them in a way that they are easier to find within the IDE. It's not the most awesome solution, but it's better than nothing.

How do I get a list of all subdomains of a domain?

If the DNS server is configured properly, you won't be able to get the entire domain. If for some reason is allows zone transfers from any host, you'll have to send it the correct packet to make that request. I suspect that's what the dig statement you included does.

Getting session value in javascript

If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".

Example for VB:

<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>  

How do I define a method which takes a lambda as a parameter in Java 8?

For anyone who is googling this, a good method would be to use java.util.function.BiConsumer. ex:

Import java.util.function.Consumer
public Class Main {
    public static void runLambda(BiConsumer<Integer, Integer> lambda) {
        lambda.accept(102, 54)
    }

    public static void main(String[] args) {
        runLambda((int1, int2) -> System.out.println(int1 + " + " + int2 + " = " + (int1 + int2)));
    }

The outprint would be: 166

Android - how to replace part of a string by another string?

rekaszeru

I noticed that you commented in 2011 but i thought i should post this answer anyway, in case anyone needs to "replace the original string" and runs into this answer ..

Im using a EditText as an example


// GIVE TARGET TEXT BOX A NAME

 EditText textbox = (EditText) findViewById(R.id.your_textboxID);

// STRING TO REPLACE

 String oldText = "hello"
 String newText = "Hi";      
 String textBoxText = textbox.getText().toString();

// REPLACE STRINGS WITH RETURNED STRINGS

String returnedString = textBoxText.replace( oldText, newText );

// USE RETURNED STRINGS TO REPLACE NEW STRING INSIDE TEXTBOX

textbox.setText(returnedString);

This is untested, but it's just an example of using the returned string to replace the original layouts string with setText() !

Obviously this example requires that you have a EditText with the ID set to your_textboxID

VBA check if file exists

A way that is clean and short:

Public Function IsFile(s)
    IsFile = CreateObject("Scripting.FileSystemObject").FileExists(s)
End Function

IE6/IE7 css border on select element

To do a border along one side of a select in IE use IE's filters:

select.required { border-left:2px solid red; filter: progid:DXImageTransform.Microsoft.dropshadow(OffX=-2, OffY=0,color=#FF0000) }

I put a border on one side only of all my inputs for required status.

There is probably an effects that do a better job for an all-round border ...

http://msdn.microsoft.com/en-us/library/ms532853(v=VS.85).aspx

How to make rectangular image appear circular with CSS

For those who use Bootstrap 3, it has a great CSS class to do the job:

<img src="..." class="img-circle">

How to change Java version used by TOMCAT?

There are several good answers on here but I wanted to add one since it may be helpful for users like me who have Tomcat installed as a service on a Windows machine.

Option 3 here: http://www.codejava.net/servers/tomcat/4-ways-to-change-jre-for-tomcat

Basically, open tomcatw.exe and point Tomcat to the version of the JVM you need to use then restart the service. Ensure your deployed applications still work as well.

When to encode space to plus (+) or %20?

http://www.example.com/some/path/to/resource?param1=value1

The part before the question mark must use % encoding (so %20 for space), after the question mark you can use either %20 or + for a space. If you need an actual + after the question mark use %2B.

Installation of VB6 on Windows 7 / 8 / 10

I've installed and use VB6 for legacy projects many times on Windows 7.

What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.

Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721

Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm

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

Try making the whole sheet font size smaller. Then zoom and save. Make a practice sheet first because it really screws everything up.

How To Upload Files on GitHub

Well, there really is a lot to this. I'm assuming you have an account on http://github.com/. If not, go get one.

After that, you really can just follow their guide, its very simple and easy and the explanation is much more clear than mine: http://help.github.com/ >> http://help.github.com/mac-set-up-git/

To answer your specific question: You upload files to github through the git push command after you have added your files you needed through git add 'files' and commmited them git commit -m "my commit messsage"

good postgresql client for windows?

Actually there is a freeware version of EMS's SQL Manager which is quite powerful

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

For any array of length n, elements of the array will have an index from 0 to n-1.

If your program is trying to access any element (or memory) having array index greater than n-1, then Java will throw ArrayIndexOutOfBoundsException

So here are two solutions that we can use in a program

  1. Maintaining count:

    for(int count = 0; count < array.length; count++) {
        System.out.println(array[count]);
    }
    

    Or some other looping statement like

    int count = 0;
    while(count < array.length) {
        System.out.println(array[count]);
        count++;
    }
    
  2. A better way go with a for each loop, in this method a programmer has no need to bother about the number of elements in the array.

    for(String str : array) {
        System.out.println(str);
    }
    

Why would $_FILES be empty when uploading files to PHP?

I have a same problem looking 2 hours ,is very simple to we check our server configuration first.

Example:

echo $upload_max_size = ini_get('upload_max_filesize');  
echo $post_max_size=ini_get('post_max_size');   

any type of file size is :20mb, but our upload_max_size is above 20mb but array is null. Answer is our post_max_size should be greater than upload_max_filesize

post_max_size = 750M  
upload_max_filesize = 750M

Disable form auto submit on button click

<button>'s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!

$('form button').on("click",function(e){
    e.preventDefault();
});

.NET 4.0 has a new GAC, why?

It doesn't make a lot of sense, the original GAC was already quite capable of storing different versions of assemblies. And there's little reason to assume a program will ever accidentally reference the wrong assembly, all the .NET 4 assemblies got the [AssemblyVersion] bumped up to 4.0.0.0. The new in-process side-by-side feature should not change this.

My guess: there were already too many .NET projects out there that broke the "never reference anything in the GAC directly" rule. I've seen it done on this site several times.

Only one way to avoid breaking those projects: move the GAC. Back-compat is sacred at Microsoft.

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

WPF What is the correct way of using SVG files as icons in WPF

Install the SharpVectors library

Install-Package SharpVectors

Add the following in XAML

<UserControl xmlns:svgc="http://sharpvectors.codeplex.com/svgc">
    <svgc:SvgViewbox Source="/Icons/icon.svg"/>
</UserControl>

Accessing localhost of PC from USB connected Android mobile device

I finally solved this problem. I used Samsung Galaxy S with Froyo. The "port" below is the same port what you use for the emulator (10.0.2.2:port). What I did:

  1. first connect your real device with the USB cable (make sure you can upload the app on your device)
  2. get the IP address from the device you connect, which starts with 192.168.x.x:port
  3. open the "Network and Sharing Center"
  4. click on the "Local Area Connection" from the device and choose "Details"
  5. copy the "IPv4 address" to your app and replace it like: http://192.168.x.x:port/test.php
  6. upload your app (again) to your real device
  7. go to properties and turn "USB tethering" on
  8. run your application on the device

It should now work.

How can I debug my JavaScript code?

Visual Studio 2008 has some very good JavaScript debugging tools. You can drop a breakpoint in your client side JavaScript code and step through it using the exact same tools as you would the server side code. There is no need to attach to a process or do anything tricky to enable it.

Convert Iterable to Stream using Java 8 JDK

If you happen to use Vavr(formerly known as Javaslang), this can be as easy as:

Iterable i = //...
Stream.ofAll(i);

Convert hex string (char []) to int?

Something like this could be useful:

char str[] = "0x1800785";
int num;

sscanf(str, "%x", &num);
printf("0x%x %i\n", num, num); 

Read man sscanf

How to fix height of TR?

Tables are iffy (at least, in IE) when it comes to fixing heights and not wrapping text. I think you'll find that the only solution is to put the text inside a div element, like so:

_x000D_
_x000D_
td.container > div {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    overflow:hidden;_x000D_
}_x000D_
td.container {_x000D_
    height: 20px;_x000D_
}
_x000D_
<table>_x000D_
    <tr>_x000D_
        <td class="container">_x000D_
            <div>This is a long line of text designed not to wrap _x000D_
                 when the container becomes too small.</div>_x000D_
        </td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This way, the div's height is that of the containing cell and the text cannot grow the div, keeping the cell/row the same height no matter what the window size is.

What does [object Object] mean? (JavaScript)

It means you are alerting an instance of an object. When alerting the object, toString() is called on the object, and the default implementation returns [object Object].

var objA = {};
var objB = new Object;
var objC = {};

objC.toString = function () { return "objC" };

alert(objA); // [object Object]
alert(objB); // [object Object]
alert(objC); // objC

If you want to inspect the object, you should either console.log it, JSON.stringify() it, or enumerate over it's properties and inspect them individually using for in.

Array vs. Object efficiency in JavaScript

It depends on usage. If the case is lookup objects is very faster.

Here is a Plunker example to test performance of array and object lookups.

https://plnkr.co/edit/n2expPWVmsdR3zmXvX4C?p=preview

You will see that; Looking up for 5.000 items in 5.000 length array collection, take over 3000 milisecons

However Looking up for 5.000 items in object has 5.000 properties, take only 2 or 3 milisecons

Also making object tree don't make huge difference

Opposite of %in%: exclude rows with values specified in a vector

Another solution could be using setdiff

D1 = c("A",..., "Z") ; D0 = c("B","N","T")

D2 = setdiff(D1, D0)

D2 is your desired subset.

How to make Twitter Bootstrap menu dropdown on hover rather than click

To get the menu to automatically drop on hover then this can achieved using basic CSS. You need to work out the selector to the hidden menu option and then set it to display as block when the appropriate li tag is hovered over. Taking the example from the twitter bootstrap page, the selector would be as follows:

ul.nav li.dropdown:hover > ul.dropdown-menu {
    display: block;    
}

However, if you are using Bootstrap's responsive features, you will not want this functionality on a collapsed navbar (on smaller screens). To avoid this, wrap the code above in a media query:

@media (min-width: 979px) {
  ul.nav li.dropdown:hover > ul.dropdown-menu {
    display: block;
  }
}

To hide the arrow (caret) this is done in different ways depending on whether you are using Twitter Bootstrap version 2 and lower or version 3:

Bootstrap 3

To remove the caret in version 3 you just need to remove the HTML <b class="caret"></b> from the .dropdown-toggle anchor element:

<a class="dropdown-toggle" data-toggle="dropdown" href="#">
    Dropdown
    <b class="caret"></b>    <-- remove this line
</a>

Bootstrap 2 & lower

To remove the caret in version 2 you need a little more insight into CSS and I suggest looking at how the :after pseudo element works in more detail. To get you started on your way to understanding, to target and remove the arrows in the twitter bootstrap example, you would use the following CSS selector and code:

a.menu:after, .dropdown-toggle:after {
    content: none;
}

It will work in your favour if you look further into how these work and not just use the answers that I have given you.

Thanks to @CocaAkat for pointing out that we were missing the ">" child combinator to prevent sub menus being shown on the parent hover

JBoss vs Tomcat again

I'd certainly look to TomEE since the idea behind is to keep Tomcat bringing all the JavaEE 6 integration missing by default. That's a kind of very good compromise

Prevent WebView from displaying "web page not available"

The best solution I have found is to load an empty page in the OnReceivedError event like this:

@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    super.onReceivedError(view, errorCode, description, failingUrl);

    view.loadUrl("about:blank");
}

css3 transition animation on load?

Not really, as CSS is applied as soon as possible, but the elements might not be drawn yet. You could guess a delay of 1 or 2 seconds, but this won't look right for most people, depending on the speed of their internet.

In addition, if you want to fade something in for instance, it would require CSS that hides the content to be delivered. If the user doesn't have CSS3 transitions then they would never see it.

I'd recommend using jQuery (for ease of use + you may wish to add animation for other UAs) and some JS like this:

$(document).ready(function() {
    $('#id_to_fade_in')
        .css({"opacity":0})   // Set to 0 as soon as possible – may result in flicker, but it's not hidden for users with no JS (Googlebot for instance!)
        .delay(200)           // Wait for a bit so the user notices it fade in
        .css({"opacity":1});  // Fade it back in. Swap css for animate in legacy browsers if required.
});

Along with the transitions added in the CSS. This has the advantage of easily allowing the use of animate instead of the second CSS in legacy browsers if required.

AppSettings get value from .config file

For web application, i normally will write this method and just call it with the key.

private String GetConfigValue(String key)
    {
       return System.Web.Configuration.WebConfigurationManager.AppSettings[key].ToString();
    }

SQLiteDatabase.query method

if your SQL query is like this

SELECT col-1, col-2 FROM tableName WHERE col-1=apple,col-2=mango
GROUPBY col-3 HAVING Count(col-4) > 5  ORDERBY col-2 DESC LIMIT 15;

Then for query() method, we can do as:-

String table = "tableName";
String[] columns = {"col-1", "col-2"};
String selection = "col-1 =? AND col-2=?";       
String[] selectionArgs = {"apple","mango"};
String groupBy =col-3;
String having =" COUNT(col-4) > 5";
String orderBy = "col-2 DESC";
String limit = "15";

query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);

jQuery rotate/transform

Simply remove the line that rotates it one degree at a time and calls the script forever.

// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);

Then pass the desired value into the function... in this example 45 for 45 degrees.

$(function() {

    var $elie = $("#bkgimg");
    rotate(45);

        function rotate(degree) {
      // For webkit browsers: e.g. Chrome
           $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
      // For Mozilla browser: e.g. Firefox
           $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
        }

});

Change .css() to .animate() in order to animate the rotation with jQuery. We also need to add a duration for the animation, 5000 for 5 seconds. And updating your original function to remove some redundancy and support more browsers...

$(function() {

    var $elie = $("#bkgimg");
    rotate(45);

        function rotate(degree) {
            $elie.animate({
                        '-webkit-transform': 'rotate(' + degree + 'deg)',
                        '-moz-transform': 'rotate(' + degree + 'deg)',
                        '-ms-transform': 'rotate(' + degree + 'deg)',
                        '-o-transform': 'rotate(' + degree + 'deg)',
                        'transform': 'rotate(' + degree + 'deg)',
                        'zoom': 1
            }, 5000);
        }
});

EDIT: The standard jQuery CSS animation code above is not working because apparently, jQuery .animate() does not yet support the CSS3 transforms.

This jQuery plugin is supposed to animate the rotation:

http://plugins.jquery.com/project/QTransform

Filtering lists using LINQ

Have a look at the Except method, which you use like this:

var resultingList = 
    listOfOriginalItems.Except(listOfItemsToLeaveOut, equalityComparer)

You'll want to use the overload I've linked to, which lets you specify a custom IEqualityComparer. That way you can specify how items match based on your composite key. (If you've already overridden Equals, though, you shouldn't need the IEqualityComparer.)

Edit: Since it appears you're using two different types of classes, here's another way that might be simpler. Assuming a List<Person> called persons and a List<Exclusion> called exclusions:

var exclusionKeys = 
        exclusions.Select(x => x.compositeKey);
var resultingPersons = 
        persons.Where(x => !exclusionKeys.Contains(x.compositeKey));

In other words: Select from exclusions just the keys, then pick from persons all the Person objects that don't have any of those keys.

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

I was getting this exception, fixed it by adding throwIfV1Schema: false to my DbContext constructor:

public class AppDb : IdentityDbContext<User>
{
    public AppDb()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }
}

How to encode the plus (+) symbol in a URL

It's safer to always percent-encode all characters except those defined as "unreserved" in RFC-3986.

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

So, percent-encode the plus character and other special characters.

The problem that you are having with pluses is because, according to RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1., "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped"). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

Python function to convert seconds into minutes, hours, and days

def seconds_to_dhms(time):
    seconds_to_minute   = 60
    seconds_to_hour     = 60 * seconds_to_minute
    seconds_to_day      = 24 * seconds_to_hour

    days    =   time // seconds_to_day
    time    %=  seconds_to_day

    hours   =   time // seconds_to_hour
    time    %=  seconds_to_hour

    minutes =   time // seconds_to_minute
    time    %=  seconds_to_minute

    seconds = time

    print("%d days, %d hours, %d minutes, %d seconds" % (days, hours, minutes, seconds))


time = int(input("Enter the number of seconds: "))
seconds_to_dhms(time)

Output: Enter the number of seconds: 2434234232

Result: 28174 days, 0 hours, 10 minutes, 32 seconds

Using the star sign in grep

The dot character means match any character, so .* means zero or more occurrences of any character. You probably mean to use .* rather than just *.

Combating AngularJS executing controller twice

Just want to add one more case when controller can init twice (this is actual for angular.js 1.3.1):

<div ng-if="loading">Loading...</div>
<div ng-if="!loading">
    <div ng-view></div>
</div>

In this case $route.current will be already set when ng-view will init. That cause double initialization.

To fix it just change ng-if to ng-show/ng-hide and all will work well.

How do I check in python if an element of a list is empty?

Just check if that element is equal to None type or make use of NOT operator ,which is equivalent to the NULL type you observe in other languages.

if not A[i]:
    ## do whatever

Anyway if you know the size of your list then you don't need to do all this.

Grunt watch error - Waiting...Fatal error: watch ENOSPC

In my case I found that I have an aggressive plugin for Vim, just restarted it.

bash "if [ false ];" returns true instead of false -- why?

as noted by @tripleee, this is tangential, at best.

still, in case you arrived here searching for something like that (as i did), here is my solution

having to deal with user acessible configuration files, i use this function :

function isTrue() {
    if [[ "${@^^}" =~ ^(TRUE|OUI|Y|O$|ON$|[1-9]) ]]; then return 0;fi
    return 1
    }

wich can be used like that

if isTrue "$whatever"; then..

You can alter the "truth list" in the regexp, the one in this sample is french compatible and considers strings like "Yeah, yup, on,1, Oui,y,true to be "True".

note that the '^^' provides case insensivity

EXC_BAD_ACCESS signal received

I just had this problem. For me the reason was deleting a CoreData managed object ans trying to read it afterwards from another place.

How to set a cron job to run at a exact time?

My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!

I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:

# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root          virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root         virsh start download

I think this is correct, and hope it helps someone else too.

What does $@ mean in a shell script?

These are the command line arguments where:

$@ = stores all the arguments in a list of string
$* = stores all the arguments as a single string
$# = stores the number of arguments

Format output string, right alignment

To do it by using f-string and with control of the number of trailing digits:

print(f'A number -> {my_number:>20.5f}')

Android Horizontal RecyclerView scroll Direction

XML approach using androidx:

<androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:id="@+id/my_recycler_view"
        android:orientation="horizontal"
        tools:listitem="@layout/my_item"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" 
        android:layout_height="wrap_content">

iReport not starting using JRE 8

I was tired of searching on google how to run iReport with java 8.

I did everything as said on the Internet,But I don't know why they weren't work for me.

Then I Change My Computer JDK Current Version form 1.8 to 1.7 Using Registry Editor.

Now it work fine.

To Change Current Version

Start => Type regedit (Press Enter) => HKEY_LOCAL_MACHINE => SOFTWARE => JavaSoft => Java Development Kit => Change Key Value of CurrentVersion From 1.8 to 1.7

Checking if an object is null in C#

With c#9 (2020) you can now check a parameter is null with this code:

if (name is null) { }

if (name is not null) { }

You can have more information here

How to disable Hyper-V in command line?

Open a command prompt as admin and run this command:

bcdedit /set {current} hypervisorlaunchtype off

After a reboot, Hyper-V is still installed but the Hypervisor is no longer running. Now you can use VMware without any issues.

If you need Hyper-V again, open a command prompt as admin and run this command:

bcdedit /set {current} hypervisorlaunchtype auto

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

<a href="http://www.omsaicreche.blogspot.com" onclick="location.href='http://www.omsaivatikanoida.blogspot.com';" target="_blank">Open Two Links With One Click</a>

I tried the above codes. I could not get success in old page. Than I created a new page in blogger and types following codes... I was successful

How to convert milliseconds into a readable date?

You can use datejs and convert in different formate. I have tested some formate and working fine.

var d = new Date(1469433907836);

d.toLocaleString()     // 7/25/2016, 1:35:07 PM
d.toLocaleDateString() // 7/25/2016
d.toDateString()       // Mon Jul 25 2016
d.toTimeString()       // 13:35:07 GMT+0530 (India Standard Time)
d.toLocaleTimeString() // 1:35:07 PM
d.toISOString();       // 2016-07-25T08:05:07.836Z
d.toJSON();            // 2016-07-25T08:05:07.836Z
d.toString();          // Mon Jul 25 2016 13:35:07 GMT+0530 (India Standard Time)
d.toUTCString();       // Mon, 25 Jul 2016 08:05:07 GMT

How do I create a unique constraint that also allows nulls?

As stated before, SQL Server doesn't implement the ANSI standard when it comes to UNIQUE CONSTRAINT. There is a ticket on Microsoft Connect for this since 2007. As suggested there and here the best options as of today are to use a filtered index as stated in another answer or a computed column, e.g.:

CREATE TABLE [Orders] (
  [OrderId] INT IDENTITY(1,1) NOT NULL,
  [TrackingId] varchar(11) NULL,
  ...
  [ComputedUniqueTrackingId] AS (
      CASE WHEN [TrackingId] IS NULL
      THEN '#' + cast([OrderId] as varchar(12))
      ELSE [TrackingId_Unique] END
  ),
  CONSTRAINT [UQ_TrackingId] UNIQUE ([ComputedUniqueTrackingId])
)

Selecting a row of pandas series/dataframe by integer index

you can loop through the data frame like this .

for ad in range(1,dataframe_c.size):
    print(dataframe_c.values[ad])