Programs & Examples On #Audio comparison

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

There is no need to make a query string. Just put your values in an object and jQuery will take care of the rest for you.

var data = {
    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
};
$.ajax({
    type: "POST",
    url: "email.php",
    data: data,
    success: function(){
        $('.success').fadeIn(1000);
    }
});

Why do we use Base64?

Most computers store data in 8-bit binary format, but this is not a requirement. Some machines and transmission media can only handle 7 bits (or maybe even lesser) at a time. Such a medium would interpret the stream in multiples of 7 bits, so if you were to send 8-bit data, you won't receive what you expect on the other side. Base-64 is just one way to solve this problem: you encode the input into a 6-bit format, send it over your medium and decode it back to 8-bit format at the receiving end.

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

I had tried most of the above solution and in past some of them had worked.

But this time none of them worked, so i had deleted my library project's .jar file. and rebuild both library and application project.

And this time it's worked!

How to set thymeleaf th:field value from other variable

You could approach this method.

Instead of using th:field use html id & name. Set value using th:value

<input class="form-control"
           type="text"
           th:value="${client.name}" id="clientName" name="clientName" />

Hope this will help you

How does the FetchMode work in Spring Data JPA

I think that Spring Data ignores the FetchMode. I always use the @NamedEntityGraph and @EntityGraph annotations when working with Spring Data

@Entity
@NamedEntityGraph(name = "GroupInfo.detail",
  attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {

  // default fetch mode is lazy.
  @ManyToMany
  List<GroupMember> members = new ArrayList<GroupMember>();

  …
}

@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {

  @EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
  GroupInfo getByGroupName(String name);

}

Check the documentation here

How can I use an array of function pointers?

This simple example for multidimensional array with function pointers":

void one( int a, int b){    printf(" \n[ ONE ]  a =  %d   b = %d",a,b);}
void two( int a, int b){    printf(" \n[ TWO ]  a =  %d   b = %d",a,b);}
void three( int a, int b){    printf("\n [ THREE ]  a =  %d   b = %d",a,b);}
void four( int a, int b){    printf(" \n[ FOUR ]  a =  %d   b = %d",a,b);}
void five( int a, int b){    printf(" \n [ FIVE ]  a =  %d   b = %d",a,b);}
void(*p[2][2])(int,int)   ;
int main()
{
    int i,j;
    printf("multidimensional array with function pointers\n");

    p[0][0] = one;    p[0][1] = two;    p[1][0] = three;    p[1][1] = four;
    for (  i  = 1 ; i >=0; i--)
        for (  j  = 0 ; j <2; j++)
            (*p[i][j])( (i, i*j);
    return 0;
}

Validating input using java.util.Scanner

Overview of Scanner.hasNextXXX methods

java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them:

Scanner is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern), which lets you define what pattern separates your tokens. There are also find and skip methods that ignores delimiters.

The following discussion will keep the regex as simple as possible, so the focus remains on Scanner.


Example 1: Validating positive ints

Here's a simple example of using hasNextInt() to validate positive int from the input.

Scanner sc = new Scanner(System.in);
int number;
do {
    System.out.println("Please enter a positive number!");
    while (!sc.hasNextInt()) {
        System.out.println("That's not a number!");
        sc.next(); // this is important!
    }
    number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);

Here's an example session:

Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5

Note how much easier Scanner.hasNextInt() is to use compared to the more verbose try/catch Integer.parseInt/NumberFormatException combo. By contract, a Scanner guarantees that if it hasNextInt(), then nextInt() will peacefully give you that int, and will not throw any NumberFormatException/InputMismatchException/NoSuchElementException.

Related questions


Example 2: Multiple hasNextXXX on the same token

Note that the snippet above contains a sc.next() statement to advance the Scanner until it hasNextInt(). It's important to realize that none of the hasNextXXX methods advance the Scanner past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!

This has two consequences:

  • If you need to skip the "garbage" input that fails your hasNextXXX test, then you need to advance the Scanner one way or another (e.g. next(), nextLine(), skip, etc).
  • If one hasNextXXX test fails, you can still test if it perhaps hasNextYYY!

Here's an example of performing multiple hasNextXXX tests.

Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
    System.out.println(
        sc.hasNextInt() ? "(int) " + sc.nextInt() :
        sc.hasNextLong() ? "(long) " + sc.nextLong() :  
        sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
        sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
        "(String) " + sc.next()
    );
}

Here's an example session:

5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit

Note that the order of the tests matters. If a Scanner hasNextInt(), then it also hasNextLong(), but it's not necessarily true the other way around. More often than not you'd want to do the more specific test before the more general test.


Example 3 : Validating vowels

Scanner has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
    System.out.println("That's not a vowel!");
    sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);

Here's an example session:

Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e

In regex, as a Java string literal, the pattern "[aeiou]" is what is called a "character class"; it matches any of the letters a, e, i, o, u. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner.

API links

Related questions

References


Example 4: Using two Scanner at once

Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner, where the second Scanner takes the nextLine() from the first Scanner as input. Here's an example:

Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
    Scanner lineSc = new Scanner(sc.nextLine());
    int sum = 0;
    while (lineSc.hasNextInt()) {
        sum += lineSc.nextInt();
    }
    System.out.println("Sum is " + sum);
}

Here's an example session:

Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit

In addition to Scanner(String) constructor, there's also Scanner(java.io.File) among others.


Summary

  • Scanner provides a rich set of features, such as hasNextXXX methods for validation.
  • Proper usage of hasNextXXX/nextXXX in combination means that a Scanner will NEVER throw an InputMismatchException/NoSuchElementException.
  • Always remember that hasNextXXX does not advance the Scanner past any input.
  • Don't be shy to create multiple Scanner if necessary. Two simple Scanner is often better than one overly complex Scanner.
  • Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any Scanner method that takes a String pattern argument is regex-based.
    • Tip: an easy way to turn any String into a literal pattern is to Pattern.quote it.

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

In my case the form (which I cannot modify) was always sending POST.
While in my Web Service I tried to implement GET method (due to lack of documentation I expected that both are allowed).

Thus, it was failing as "Not allowed", since there was no method with POST type on my end.

Changing @GET to @POST above my WS method fixed the issue.

Resize background image in div using css

Answer

You have multiple options:

  1. background-size: 100% 100%; - image gets stretched (aspect ratio may be preserved, depending on browser)
  2. background-size: contain; - image is stretched without cutting it while preserving aspect ratio
  3. background-size: cover; - image is completely covering the element while preserving aspect ratio (image can be cut off)

/edit: And now, there is even more: https://alligator.io/css/cropping-images-object-fit

Demo on Codepen

Update 2017: Preview

Here are screenshots for some browsers to show their differences.

Chrome

preview background types chrome


Firefox

preview background types firefox


Edge

preview background types edge


IE11

preview background types ie11

Takeaway Message

background-size: 100% 100%; produces the least predictable result.

Resources

What is the iPad user agent?

It's worth noting that when running in web-app mode (using the apple-mobile-web-app-capable meta tag) the user agent changes from:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B405 Safari/531.21.10

to:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405

Why do we need virtual functions in C++?

i think you are referring to the fact once a method is declared virtual you don't need to use the 'virtual' keyword in overrides.

class Base { virtual void foo(); };

class Derived : Base 
{ 
  void foo(); // this is overriding Base::foo
};

If you don't use 'virtual' in Base's foo declaration then Derived's foo would just be shadowing it.

Visual Studio 2017 errors on standard headers

I upgraded VS2017 from version 15.2 to 15.8. With version 15.8 here's what happened:

Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0 no longer worked for me! I had to change it to 10.0.17134.0 and then everything built again. After the upgrade and without making this change, I was getting the same header file errors.

I would have submitted this as a comment on one of the other answers but I don't have enough reputation yet.

How to modify a global variable within a function in bash?

It's because command substitution is performed in a subshell, so while the subshell inherits the variables, changes to them are lost when the subshell ends.

Reference:

Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment

How do I install g++ for Fedora?

instead of g++ you have to write gcc-c++

sudo dnf install gcc-c++

Bootstrap 3 - disable navbar collapse

If you're not using the less version, here is the line you need to change:

@media (max-width: 767px) { /* Change this to 0 */
  .navbar-nav .open .dropdown-menu {
    position: static;
    float: none;
    width: auto;
    margin-top: 0;
    background-color: transparent;
    border: 0;
    box-shadow: none;
  }
  .navbar-nav .open .dropdown-menu > li > a,
  .navbar-nav .open .dropdown-menu .dropdown-header {
    padding: 5px 15px 5px 25px;
  }
  .navbar-nav .open .dropdown-menu > li > a {
    line-height: 20px;
  }
  .navbar-nav .open .dropdown-menu > li > a:hover,
  .navbar-nav .open .dropdown-menu > li > a:focus {
    background-image: none;
  }
}

How do I get Maven to use the correct repositories?

tl;dr

All maven POMs inherit from a base Super POM.
The snippet below is part of the Super POM for Maven 3.5.4.

  <repositories>
    <repository>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
      <layout>default</layout>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
  </repositories>

How to make a round button?

Fully rounded circle shape.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#FFFFFF" />
    <stroke
        android:width="1dp"
        android:color="#F0F0F0" />
    <corners
        android:radius="90dp"/>
</shape>

Happy Coding!

How to replace all strings to numbers contained in each string in Notepad++?

I have Notepad++ v6.8.8

Find: [([a-zA-Z])]

Replace: [\'\1\']

Will produce: $array[XYZ] => $array['XYZ']

What are forward declarations in C++?

When the compiler sees add(3, 4) it needs to know what that means. With the forward declaration you basically tell the compiler that add is a function that takes two ints and returns an int. This is important information for the compiler becaus it needs to put 4 and 5 in the correct representation onto the stack and needs to know what type the thing returned by add is.

At that time, the compiler is not worried about the actual implementation of add, ie where it is (or if there is even one) and if it compiles. That comes into view later, after compiling the source files when the linker is invoked.

Spring default behavior for lazy-init

When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".

If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".

What's the difference between xsd:include and xsd:import?

I'm interested in this as well. The only explanation I've found is that xsd:include is used for intra-namespace inclusions, while xsd:import is for inter-namespace inclusion.

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Use getElementById on HTMLElement instead of HTMLDocument

Thanks to dee for the answer above with the Scrape() subroutine. The code worked perfectly as written, and I was able to then convert the code to work with the specific website I am trying to scrape.

I do not have enough reputation to upvote or to comment, but I do actually have some minor improvements to add to dee's answer:

  1. You will need to add the VBA Reference via "Tools\References" to "Microsoft HTML Object Library in order for the code to compile.

  2. I commented out the Browser.Visible line and added the comment as follows

    'if you need to debug the browser page, uncomment this line:
    'Browser.Visible = True
    
  3. And I added a line to close the browser before Set Browser = Nothing:

    Browser.Quit
    

Thanks again dee!

ETA: this works on machines with IE9, but not machines with IE8. Anyone have a fix?

Found the fix myself, so came back here to post it. The ClassName function is available in IE9. For this to work in IE8, you use querySelectorAll, with a dot preceding the class name of the object you are looking for:

'Set repList = doc.getElementsByClassName("reportList") 'only works in IE9, not in IE8
Set repList = doc.querySelectorAll(".reportList")       'this works in IE8+

What is the garbage collector in Java?

The garbage collector is a program which runs on the Java Virtual Machine which gets rid of objects which are not being used by a Java application anymore. It is a form of automatic memory management.

When a typical Java application is running, it is creating new objects, such as Strings and Files, but after a certain time, those objects are not used anymore. For example, take a look at the following code:

for (File f : files) {
    String s = f.getName();
}

In the above code, the String s is being created on each iteration of the for loop. This means that in every iteration, a little bit of memory is being allocated to make a String object.

Going back to the code, we can see that once a single iteration is executed, in the next iteration, the String object that was created in the previous iteration is not being used anymore -- that object is now considered "garbage".

Eventually, we'll start getting a lot of garbage, and memory will be used for objects which aren't being used anymore. If this keeps going on, eventually the Java Virtual Machine will run out of space to make new objects.

That's where the garbage collector steps in.

The garbage collector will look for objects which aren't being used anymore, and gets rid of them, freeing up the memory so other new objects can use that piece of memory.

In Java, memory management is taken care of by the garbage collector, but in other languages such as C, one needs to perform memory management on their own using functions such as malloc and free. Memory management is one of those things which are easy to make mistakes, which can lead to what are called memory leaks -- places where memory is not reclaimed when they are not in use anymore.

Automatic memory management schemes like garbage collection makes it so the programmer does not have to worry so much about memory management issues, so he or she can focus more on developing the applications they need to develop.

super() raises "TypeError: must be type, not classobj" for new-style class

The problem is that super needs an object as an ancestor:

>>> class oldstyle:
...     def __init__(self): self.os = True

>>> class myclass(oldstyle):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass()
TypeError: must be type, not classobj

On closer examination one finds:

>>> type(myclass)
classobj

But:

>>> class newstyle(object): pass

>>> type(newstyle)
type    

So the solution to your problem would be to inherit from object as well as from HTMLParser. But make sure object comes last in the classes MRO:

>>> class myclass(oldstyle, object):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass().os
True

Passing arguments to an interactive program non-interactively

You can put the data in a file and re-direct it like this:

$ cat file.sh
#!/bin/bash

read x
read y
echo $x
echo $y

Data for the script:

$ cat data.txt
2
3

Executing the script:

$ file.sh < data.txt
2
3

Automatically open default email client and pre-populate content

Implemented this way without using Jquery:

<button class="emailReplyButton" onClick="sendEmail(message)">Reply</button>

sendEmail(message) {
    var email = message.emailId;
    var subject = message.subject;
    var emailBody = 'Hi '+message.from;
    document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody;
}

Fully backup a git repo?

Here are two options:

  1. You can directly take a tar of the git repo directory as it has the whole bare contents of the repo on server. There is a slight possibility that somebody may be working on repo while taking backup.

  2. The following command will give you the bare clone of repo (just like it is in server), then you can take a tar of the location where you have cloned without any issue.

    git clone --bare {your backup local repo} {new location where you want to clone}
    

Get month and year from a datetime in SQL Server 2005

select 
datepart(month,getdate()) -- integer (1,2,3...)
,datepart(year,getdate()) -- integer
,datename(month,getdate()) -- string ('September',...)

Variable name as a string in Javascript

You can use the following solution to solve your problem:

const myFirstName = 'John'
Object.keys({myFirstName})[0]

// returns "myFirstName"

How do I add comments to package.json for npm install?

To summarise all of these answers:

  1. Add a single top-level field called // that contains a comment string. This works, but it sucks because you can't put comments near the thing they are commenting on.

  2. Add multiple top-level fields starting with //, e.g. //dependencies that contains a comment string. This is better, but it still only allows you to make top-level comments. You can't comment individual dependencies.

  3. Add echo commands to your scripts. This works, but it sucks because you can only use it in scripts.

These solutions are also all not very readable. They add a ton of visual noise and IDEs will not syntax highlight them as comments.

I think the only reasonable solution is to generate the package.json from another file. The simplest way is to write your JSON as JavaScript and use Node.js to write it to package.json. Save this file as package.json.mjs, chmod +x it, and then you can just run it to generate your package.json.

#!/usr/bin/env node

import { writeFileSync } from "fs";

const config = {
  // TODO: Think of better name.
  name: "foo",
  dependencies: {
    // Bar 2.0 does not work due to bug 12345.
    bar: "^1.2.0",
  },
  // Look at these beautify comments. Perfectly syntax highlighted, you
  // can put them anywhere and there no risk of some tool removing them.
};

writeFileSync("package.json", JSON.stringify({
    "//": "This file is \x40generated from package.json.mjs; do not edit.",
    ...config
  }, null, 2));

It uses the // key to warn people from editing it. \x40generated is deliberate. It turns into @generated in package.json and means some code review systems will collapse that file by default.

It's an extra step in your build system, but it beats all of the other hacks here.

Convert Int to String in Swift

To convert String into Int

var numberA = Int("10")

Print(numberA) // It will print 10

To covert Int into String

var numberA = 10

1st way)

print("numberA is \(numberA)") // It will print 10

2nd way)

var strSomeNumber = String(numberA)

or

var strSomeNumber = "\(numberA)"

java.util.zip.ZipException: error in opening zip file

Liquibase was getting this error for me. I resolved this after I debugged and watched liquibase try to load the libraries and found that it was erroring on the manifest files for commons-codec-1.6.jar. Essentially, there is either a corrupt zip file somewhere in your path or there is a incompatible version being used. When I did an explore on Maven repository for this library, I found there were newer versions and added the newer version to the pom.xml. I was able to proceed at this point.

How can I serve static html from spring boot?

Static files should be served from resources, not from controller.

Spring Boot will automatically add static web resources located within any of the following directories:

/META-INF/resources/  
/resources/  
/static/  
/public/

refs:
https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot
https://spring.io/guides/gs/serving-web-content/

Java "lambda expressions not supported at this language level"

Check below settings:

  1. File->Project Structure->Project Tab.

    *Project SDK should be set to 8 or above.*
    
  2. File->Project Structure->Modules.

    *Check that your or all modules has Language level set to 8 or above.*
    
  3. File->Settings(or Other Settings->Preference for new projects in newer Idea version)

    *Search for Java compiler and check if Project byte code version 
    and per module byte code version is set 8 or above.*
    

You problem may fall into any one of the category defined above.

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

A SpringApplication will attempt to create the right type of ApplicationContext on your behalf. By default, an AnnotationConfigApplicationContext or AnnotationConfigEmbeddedWebApplicationContext will be used, depending on whether you are developing a web application or not.

The algorithm used to determine a ‘web environment’ is fairly simplistic (based on the presence of a few classes). You can use setWebEnvironment(boolean webEnvironment) if you need to override the default.

It is also possible to take complete control of the ApplicationContext type that will be used by calling setApplicationContextClass(…?).

[Tip] It is often desirable to call setWebEnvironment(false) when using SpringApplication within a JUnit test.

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

Thanks to @user2630576 and @Ed.S.

the following worked a treat:

BACKUP LOG [database] TO DISK = 'D:\database.bak'
GO

ALTER DATABASE [database] SET RECOVERY SIMPLE

use [database]

declare @log_File_Name varchar(200)

select @log_File_Name = name from sysfiles where filename like '%LDF'

declare @i int = FILE_IDEX ( @log_File_Name)

dbcc shrinkfile ( @i , 50)

ALTER DATABASE [database] SET RECOVERY FULL

How to squash commits in git after they have been pushed?

Squash commits locally with

git rebase -i origin/master~4 master

and then force push with

git push origin +master

Difference between --force and +

From the documentation of git push:

Note that --force applies to all the refs that are pushed, hence using it with push.default set to matching or with multiple push destinations configured with remote.*.push may overwrite refs other than the current branch (including local refs that are strictly behind their remote counterpart). To force a push to only one branch, use a + in front of the refspec to push (e.g git push origin +master to force a push to the master branch).

Python coding standards/best practices

I follow it extremely rigorously. The only god before PEP-8 is existing code bases.

Finding index of character in Swift String

To get index of a substring in a string with Swift 2:

let text = "abc"
if let range = text.rangeOfString("b") {
   var index: Int = text.startIndex.distanceTo(range.startIndex) 
   ...
}

String replace a Backslash

Try replaceAll("\\\\", "") or replaceAll("\\\\/", "/").

The problem here is that a backslash is (1) an escape chararacter in Java string literals, and (2) an escape character in regular expressions – each of this uses need doubling the character, in effect needing 4 \ in row.

Of course, as Bozho said, you need to do something with the result (assign it to some variable) and not throw it away. And in this case the non-regex variant is better.

Quickly create a large file on a Linux system

Linux & all filesystems

xfs_mkfile 10240m 10Gigfile

Linux & and some filesystems (ext4, xfs, btrfs and ocfs2)

fallocate -l 10G 10Gigfile

OS X, Solaris, SunOS and probably other UNIXes

mkfile 10240m 10Gigfile

HP-UX

prealloc 10Gigfile 10737418240

Explanation

Try mkfile <size> myfile as an alternative of dd. With the -n option the size is noted, but disk blocks aren't allocated until data is written to them. Without the -n option, the space is zero-filled, which means writing to the disk, which means taking time.

mkfile is derived from SunOS and is not available everywhere. Most Linux systems have xfs_mkfile which works exactly the same way, and not just on XFS file systems despite the name. It's included in xfsprogs (for Debian/Ubuntu) or similar named packages.

Most Linux systems also have fallocate, which only works on certain file systems (such as btrfs, ext4, ocfs2, and xfs), but is the fastest, as it allocates all the file space (creates non-holey files) but does not initialize any of it.

How to catch segmentation fault in Linux?

For portability, one should probably use std::signal from the standard C++ library, but there is a lot of restriction on what a signal handler can do. Unfortunately, it is not possible to catch a SIGSEGV from within a C++ program without introducing undefined behavior because the specification says:

  1. it is undefined behavior to call any library function from within the handler other than a very narrow subset of the standard library functions (abort, exit, some atomic functions, reinstall current signal handler, memcpy, memmove, type traits, `std::move, std::forward, and some more).
  2. it is undefined behavior if handler use a throw expression.
  3. it is undefined behavior if the handler returns when handling SIGFPE, SIGILL, SIGSEGV

This proves that it is impossible to catch SIGSEGV from within a program using strictly standard and portable C++. SIGSEGV is still caught by the operating system and is normally reported to the parent process when a wait family function is called.

You will probably run into the same kind of trouble using POSIX signal because there is a clause that says in 2.4.3 Signal Actions:

The behavior of a process is undefined after it returns normally from a signal-catching function for a SIGBUS, SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill(), sigqueue(), or raise().

A word about the longjumps. Assuming we are using POSIX signals, using longjump to simulate stack unwinding won't help:

Although longjmp() is an async-signal-safe function, if it is invoked from a signal handler which interrupted a non-async-signal-safe function or equivalent (such as the processing equivalent to exit() performed after a return from the initial call to main()), the behavior of any subsequent call to a non-async-signal-safe function or equivalent is undefined.

This means that the continuation invoked by the call to longjump cannot reliably call usually useful library function such as printf, malloc or exit or return from main without inducing undefined behavior. As such, the continuation can only do a restricted operations and may only exit through some abnormal termination mechanism.

To put things short, catching a SIGSEGV and resuming execution of the program in a portable is probably infeasible without introducing UB. Even if you are working on a Windows platform for which you have access to Structured exception handling, it is worth mentioning that MSDN suggest to never attempt to handle hardware exceptions: Hardware Exceptions.

At last but not least, whether any SIGSEGV would be raised when dereferencing a null valued pointer (or invalid valued pointer) is not a requirement from the standard. Because indirection through a null valued pointer or any invalid valued pointer is an undefined behaviour, which means the compiler assumes your code will never attempt such a thing at runtime, the compiler is free to make code transformation that would elide such undefined behavior. For example, from cppreference,

int foo(int* p) {
    int x = *p;
    if(!p)
        return x; // Either UB above or this branch is never taken
    else
        return 0;
}
 
int main() {
    int* p = nullptr;
    std::cout << foo(p);
}

Here the true path of the if could be completely elided by the compiler as an optimization; only the else part could be kept. Said otherwise, the compiler infers foo() will never receive a null valued pointer at runtime since it would lead to an undefined behaviour. Invoking it with a null valued pointer, you may observe the value 0 printed to standard output and no crash, you may observe a crash with SIGSEG, in fact you could observe anything since no sensible requirements are imposed on programs that are not free of undefined behaviors.

Get data from php array - AJAX - jQuery

you cannot access array (php array) from js try

<?php
$array = array(1,2,3,4,5,6);
echo implode('~',$array);
?>

and js

$(document).ready( function() {
$('#prev').click(function() {
  $.ajax({
  type: 'POST',
  url: 'ajax.php',
  data: 'id=testdata',
  cache: false,
  success: function(data) {
    result=data.split('~');
    $('#content1').html(result[0]);
  },
  });
});
});

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

Accessing nested JavaScript objects and arrays by string path

using eval:

var part1name = eval("someObject.part1.name");

wrap to return undefined on error

function path(obj, path) {
    try {
        return eval("obj." + path);
    } catch(e) {
        return undefined;
    }
}

http://jsfiddle.net/shanimal/b3xTw/

Please use common sense and caution when wielding the power of eval. It's a bit like a light saber, if you turn it on there's a 90% chance you'll sever a limb. Its not for everybody.

How to install pandas from pip on windows cmd?

Assuming you are using Windows OS.

All you need to add the pip.exe path to the Environment Variables (Path).

Generally, you can find it under ..Python\Scripts folder.

For me it is, C:\Program Files\Python36\Scripts\

Solr vs. ElasticSearch

Add an nested document in solr very complex and nested data search also very complex. but Elastic Search easy to add nested document and search

Static class initializer in PHP

Actually, I use a public static method __init__() on my static classes that require initialization (or at least need to execute some code). Then, in my autoloader, when it loads a class it checks is_callable($class, '__init__'). If it is, it calls that method. Quick, simple and effective...

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How to make a JSON call to a url?

It seems they offer a js option for the format parameter, which will return JSONP. You can retrieve JSONP like so:

function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);

}

getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
    console.log(data);
});  

String, StringBuffer, and StringBuilder

Note that if you are using Java 5 or newer, you should use StringBuilder instead of StringBuffer. From the API documentation:

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

In practice, you will almost never use this from multiple threads at the same time, so the synchronization that StringBuffer does is almost always unnecessary overhead.

Android Studio: Module won't show up in "Edit Configuration"

The following are methods to help you:

  1. Close and Open Project again
  2. Close and Open Android Studio
  3. Clean Project
  4. Rebuild Project
  5. Instantiate and Restart
  6. Make sure you have included :app
  7. Import the Project

How can I update npm on Windows?

For what it's worth, I had to combine several answers...

  1. Uninstall Node.js in control panel Add/remove programs.
  2. Delete directories, both C:\Program Files (x86)\nodejs\ and C:\Program Files\nodejs\ if they exist.
  3. Install the latest version, http://nodejs.org/download/

How do I tell Maven to use the latest version of a dependency?

The truth is even in 3.x it still works, surprisingly the projects builds and deploys. But the LATEST/RELEASE keyword causing problems in m2e and eclipse all over the place, ALSO projects depends on the dependency which deployed through the LATEST/RELEASE fail to recognize the version.

It will also causing problem if you are try to define the version as property, and reference it else where.

So the conclusion is use the versions-maven-plugin if you can.

How to avoid a System.Runtime.InteropServices.COMException?

I came across System.Runtime.InteropServices.COMException while opening a project solution. Sometimes user doesn't have enough priveleges to run some COM Methods. I ran Visual Studio as Administrator and the exception was gone.

Equivalent of String.format in jQuery

None of the answers presented so far has no obvious optimization of using enclosure to initialize once and store regular expressions, for subsequent usages.

// DBJ.ORG string.format function
// usage:   "{0} means 'zero'".format("nula") 
// returns: "nula means 'zero'"
// place holders must be in a range 0-99.
// if no argument given for the placeholder, 
// no replacement will be done, so
// "oops {99}".format("!")
// returns the input
// same placeholders will be all replaced 
// with the same argument :
// "oops {0}{0}".format("!","?")
// returns "oops !!"
//
if ("function" != typeof "".format) 
// add format() if one does not exist already
  String.prototype.format = (function() {
    var rx1 = /\{(\d|\d\d)\}/g, rx2 = /\d+/ ;
    return function() {
        var args = arguments;
        return this.replace(rx1, function($0) {
            var idx = 1 * $0.match(rx2)[0];
            return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : $0);
        });
    }
}());

alert("{0},{0},{{0}}!".format("{X}"));

Also, none of the examples respects format() implementation if one already exists.

?: operator (the 'Elvis operator') in PHP

Elvis operator:

?: is the Elvis operator. This is a binary operator which does the following:

Coerces the value left of ?: to a boolean and checks if it is true. If true it will return the expression on the left side, if false it will return the expression on the right side.

Example:

var_dump(0 ?: "Expression not true");     // expression returns: Expression not true
var_dump("" ?: "Expression not true");    // expression returns: Expression not true
var_dump("hi" ?: "Expression not true");  // expression returns string hi
var_dump(null ?: "Expression not true");  // expression returns: Expression not true
var_dump(56 ?: "Expression not true");    // expression return int 56

When to use:

The Elvis operator is basically shorthand syntax for a specific case of the ternary operator which is:

$testedVar ? $ testedVar : $otherVar;

The Elvis operator will make the syntax more consise in the following manner:

$testedVar ?: $otherVar;

JavaScript - document.getElementByID with onClick

Perhaps you might want to use "addEventListener"

document.getElementById("test").addEventListener('click',function ()
{
    foo2();
   }  ); 

Hope it's still useful for you

NSURLConnection Using iOS Swift

Check Below Codes :

1. SynchronousRequest

Swift 1.2

    let urlPath: String = "YOUR_URL_HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)
    var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
    var err: NSError
    println(response)
    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary
    println("Synchronous\(jsonResult)")

Swift 2.0 +

let urlPath: String = "YOUR_URL_HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSURLRequest = NSURLRequest(URL: url)
    let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil


    do{

        let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)

            print(response)
            do {
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
                    print("Synchronous\(jsonResult)")
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }



    }catch let error as NSError
    {
         print(error.localizedDescription)
    }

2. AsynchonousRequest

Swift 1.2

let urlPath: String = "YOUR_URL_HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)
    let queue:NSOperationQueue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var err: NSError
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("Asynchronous\(jsonResult)")
       })

Swift 2.0 +

let urlPath: String = "YOUR_URL_HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSURLRequest = NSURLRequest(URL: url)
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

3. As usual URL connection

Swift 1.2

    var dataVal = NSMutableData()
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
    connection.start()

Then

 func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.dataVal?.appendData(data)
}


func connectionDidFinishLoading(connection: NSURLConnection!)
{
    var error: NSErrorPointer=nil

    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary

    println(jsonResult)



}

Swift 2.0 +

   var dataVal = NSMutableData()
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
    connection.start()

Then

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    dataVal.appendData(data)
}


func connectionDidFinishLoading(connection: NSURLConnection!)
{

    do {
        if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
            print(jsonResult)
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }

}

4. Asynchronous POST Request

Swift 1.2

    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
     var stringPost="deviceToken=123456" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in


        var err: NSError

        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")


        })

Swift 2.0 +

let urlPath: String = "YOUR URL HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
    let stringPost="deviceToken=123456" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

5. Asynchronous GET Request

Swift 1.2

    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "GET"
    request1.timeoutInterval = 60
    let queue:NSOperationQueue = NSOperationQueue()

     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in


        var err: NSError

        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")


        })

Swift 2.0 +

let urlPath: String = "YOUR URL HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "GET"
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

6. Image(File) Upload

Swift 2.0 +

  let mainURL = "YOUR_URL_HERE"

    let url = NSURL(string: mainURL)
    let request = NSMutableURLRequest(URL: url!)
    let boundary = "78876565564454554547676"
    request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


    request.HTTPMethod = "POST" // POST OR PUT What you want
    let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)

    let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)





    var body = NSMutableData()

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    // Append your parameters

    body.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


    // Append your Image/File Data

    var imageNameval = "HELLO.jpg"

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(imageData!)
    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    request.HTTPBody = body




    let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

        if error != nil {

            //handle error


        }
        else {




            let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!
            print("Response:\(outputString)")


        }
    }
    dataTask.resume()

7. GET,POST,Etc Swift 3.0 +

let request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE" ,param: param))!,
    cachePolicy: .useProtocolCachePolicy,
    timeoutInterval:60)
request.httpMethod = "POST" // POST ,GET, PUT What you want 

let session = URLSession.shared



  let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in

do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

    }
    dataTask.resume()

Unix shell script find out which directory the script file resides?

An earlier comment on an answer said it, but it is easy to miss among all the other answers.

When using bash:

echo this file: "$BASH_SOURCE"
echo this dir: "$(dirname "$BASH_SOURCE")"

Bash Reference Manual, 5.2 Bash Variables

Excel: replace part of cell's string value

I know this is old but I had a similar need for this and I did not want to do the find and replace version. It turns out that you can nest the substitute method like so:

=SUBSTITUTE(SUBSTITUTE(F149, "a", " AM"), "p", " PM")

In my case, I am using excel to view a DBF file and however it was populated has times like this:

9:16a
2:22p

So I just made a new column and put that formula in it to convert it to the excel time format.

tsql returning a table from a function or store procedure

You can't access Temporary Tables from within a SQL Function. You will need to use table variables so essentially:

ALTER FUNCTION FnGetCompanyIdWithCategories()
RETURNS  @rtnTable TABLE 
(
    -- columns returned by the function
    ID UNIQUEIDENTIFIER NOT NULL,
    Name nvarchar(255) NOT NULL
)
AS
BEGIN
DECLARE @TempTable table (id uniqueidentifier, name nvarchar(255)....)

insert into @myTable 
select from your stuff

--This select returns data
insert into @rtnTable
SELECT ID, name FROM @mytable 
return
END

Edit

Based on comments to this question here is my recommendation. You want to join the results of either a procedure or table-valued function in another query. I will show you how you can do it then you pick the one you prefer. I am going to be using sample code from one of my schemas, but you should be able to adapt it. Both are viable solutions first with a stored procedure.

declare @table as table (id int, name nvarchar(50),templateid int,account nvarchar(50))

insert into @table
execute industry_getall

select * 
from @table 
inner join [user] 
    on account=[user].loginname

In this case, you have to declare a temporary table or table variable to store the results of the procedure. Now Let's look at how you would do this if you were using a UDF

select *
from fn_Industry_GetAll()
inner join [user] 
    on account=[user].loginname

As you can see the UDF is a lot more concise easier to read, and probably performs a little bit better since you're not using the secondary temporary table (performance is a complete guess on my part).

If you're going to be reusing your function/procedure in lots of other places, I think the UDF is your best choice. The only catch is you will have to stop using #Temp tables and use table variables. Unless you're indexing your temp table, there should be no issue, and you will be using the tempDb less since table variables are kept in memory.

Question mark and colon in JavaScript

Properly parenthesized for clarity, it is

hsb.s = (max != 0) ? (255 * delta / max) : 0;

meaning return either

  • 255*delta/max if max != 0
  • 0 if max == 0

Test process.env with Jest

Another option is to add it to the jest.config.js file after the module.exports definition:

process.env = Object.assign(process.env, {
  VAR_NAME: 'varValue',
  VAR_NAME_2: 'varValue2'
});

This way it's not necessary to define the environment variables in each .spec file and they can be adjusted globally.

Grant Select on a view not base table when base table is in a different database

Create view Schema1.viewName1 as (select * from plaplapla)

Schema1 has all the tables

Create view Schema2.viewName2 as (select * from schema1.viewName1)

schema2 has no tables(only views schema)

In this case you can execute (select * from viewName2) in schema2 , BUT .. If you deleted viewNmae1 from Schema1 , Then ViewName2 will not work..

Amani El Gamal [email protected]

Spring JPA @Query with LIKE

For your case, you can directly use JPA methods. That is like bellow:

Containing: select ... like %:username%

List<User> findByUsernameContainingIgnoreCase(String username);

here, IgnoreCase will help you to search item with ignoring the case.

Here are some related methods:

  1. Like findByFirstnameLike

    … where x.firstname like ?1

  2. StartingWith findByFirstnameStartingWith

    … where x.firstname like ?1 (parameter bound with appended %)

  3. EndingWith findByFirstnameEndingWith

    … where x.firstname like ?1 (parameter bound with prepended %)

  4. Containing findByFirstnameContaining

    … where x.firstname like ?1 (parameter bound wrapped in %)

More info , view this link and this link

Hope this will help you :)

How to remove duplicate values from a multi-dimensional array in PHP

I had a similar problem but I found a 100% working solution for it.

<?php
    function super_unique($array,$key)
    {
       $temp_array = [];
       foreach ($array as &$v) {
           if (!isset($temp_array[$v[$key]]))
           $temp_array[$v[$key]] =& $v;
       }
       $array = array_values($temp_array);
       return $array;

    }


$arr="";
$arr[0]['id']=0;
$arr[0]['titel']="ABC";
$arr[1]['id']=1;
$arr[1]['titel']="DEF";
$arr[2]['id']=2;
$arr[2]['titel']="ABC";
$arr[3]['id']=3;
$arr[3]['titel']="XYZ";

echo "<pre>";
print_r($arr);
echo "unique*********************<br/>";
print_r(super_unique($arr,'titel'));

?>

How to check if IsNumeric

You should use TryParse - Parse throws an exception if the string is not a valid number - e.g. if you want to test for a valid integer:

int v;
if (Int32.TryParse(textMyText.Text.Trim(), out v)) {
  . . .
}

If you want to test for a valid floating-point number:

double v;
if (Double.TryParse(textMyText.Text.Trim(), out v)) {
  . . .
}

Note also that Double.TryParse has an overloaded version with extra parameters specifying various rules and options controlling the parsing process - e.g. localization ('.' or ',') - see http://msdn.microsoft.com/en-us/library/3s27fasw.aspx.

Get everything after and before certain character in SQL Server

use the following function

left(@test, charindex('/', @test) - 1)

error: cast from 'void*' to 'int' loses precision

The proper way is to cast it to another pointer type. Converting a void* to an int is non-portable way that may work or may not! If you need to keep the returned address, just keep it as void*.

How to specify the default error page in web.xml?

You can also specify <error-page> for exceptions using <exception-type>, eg below:

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errorpages/exception.html</location>
</error-page>

Or map a error code using <error-code>:

<error-page>
    <error-code>404</error-code>
    <location>/errorpages/404error.html</location>
</error-page>

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

How to display an IFRAME inside a jQuery UI dialog

There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:

$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});

Another would be to load the content of your external link into the dialog container using ajax.

$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});

Both works fine but depends on the external content.

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

How can I get a specific field of a csv file?

#!/usr/bin/env python
"""Print a field specified by row, column numbers from given csv file.

USAGE:
    %prog csv_filename row_number column_number
"""
import csv
import sys

filename = sys.argv[1]
row_number, column_number = [int(arg, 10)-1 for arg in sys.argv[2:])]

with open(filename, 'rb') as f:
     rows = list(csv.reader(f))
     print rows[row_number][column_number]

Example

$ python print-csv-field.py input.csv 2 2
ddddd

Note: list(csv.reader(f)) loads the whole file in memory. To avoid that you could use itertools:

import itertools
# ...
with open(filename, 'rb') as f:
     row = next(itertools.islice(csv.reader(f), row_number, row_number+1))
     print row[column_number]

Can I get the name of the currently running function in JavaScript?

A combination of the few responses I've seen here. (Tested in FF, Chrome, IE11)

function functionName() 
{
   var myName = functionName.caller.toString();
   myName = myName.substr('function '.length);
   myName = myName.substr(0, myName.indexOf('('));
   return myName;
}

function randomFunction(){
    var proof = "This proves that I found the name '" + functionName() + "'";
    alert(proof);
}

Calling randomFunction() will alert a string that contains the function name.

JS Fiddle Demo: http://jsfiddle.net/mjgqfhbe/

Most efficient way to create a zero filled JavaScript array?

It might be worth pointing out, that Array.prototype.fill had been added as part of the ECMAScript 6 (Harmony) proposal. I would rather go with the polyfill written below, before considering other options mentioned on the thread.

if (!Array.prototype.fill) {
  Array.prototype.fill = function(value) {

    // Steps 1-2.
    if (this == null) {
      throw new TypeError('this is null or not defined');
    }

    var O = Object(this);

    // Steps 3-5.
    var len = O.length >>> 0;

    // Steps 6-7.
    var start = arguments[1];
    var relativeStart = start >> 0;

    // Step 8.
    var k = relativeStart < 0 ?
      Math.max(len + relativeStart, 0) :
      Math.min(relativeStart, len);

    // Steps 9-10.
    var end = arguments[2];
    var relativeEnd = end === undefined ?
      len : end >> 0;

    // Step 11.
    var final = relativeEnd < 0 ?
      Math.max(len + relativeEnd, 0) :
      Math.min(relativeEnd, len);

    // Step 12.
    while (k < final) {
      O[k] = value;
      k++;
    }

    // Step 13.
    return O;
  };
}

:last-child not working as expected?

I encounter similar situation. I would like to have background of the last .item to be yellow in the elements that look like...

<div class="container">
  <div class="item">item 1</div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  ...
  <div class="item">item x</div>
  <div class="other">I'm here for some reasons</div>
</div>

I use nth-last-child(2) to achieve it.

.item:nth-last-child(2) {
  background-color: yellow;
}

It strange to me because nth-last-child of item suppose to be the second of the last item but it works and I got the result as I expect. I found this helpful trick from CSS Trick

Using the rJava package on Win7 64 bit with R

I solved the issue by uninstalling apparently redundant Java software from my windows 7 x64 machine. I achieved this by first uninstalling all Java applications and then installing a fresh Java version. (Later I pointed R 3.4.3 x86_64-w64-mingw32 to the Java path, just to mention though I don't think this was the real issue.) Today only Java 8 Update 161 (64-bit) 8.0.1610.12 was left then. After this, install.packages("rJava"); library(rJava) did work perfectly.

Get file name from URI string in C#

You can just make a System.Uri object, and use IsFile to verify it's a file, then Uri.LocalPath to extract the filename.

This is much safer, as it provides you a means to check the validity of the URI as well.


Edit in response to comment:

To get just the full filename, I'd use:

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

This does all of the error checking for you, and is platform-neutral. All of the special cases get handled for you quickly and easily.

Apply a function to every row of a matrix or a data frame

Another approach if you want to use a varying portion of the dataset instead of a single value is to use rollapply(data, width, FUN, ...). Using a vector of widths allows you to apply a function on a varying window of the dataset. I've used this to build an adaptive filtering routine, though it isn't very efficient.

Difference between decimal, float and double in .NET?

For applications such as games and embedded systems where memory and performance are both critical, float is usually the numeric type of choice as it is faster and half the size of a double. Integers used to be the weapon of choice, but floating point performance has overtaken integer in modern processors. Decimal is right out!

How to switch between frames in Selenium WebDriver using Java

to switchto a frame:

driver.switchTo.frame("Frame_ID");

to switch to the default again.

driver.switchTo().defaultContent();

How to split and modify a string in NodeJS?

var str = "123, 124, 234,252";
var arr = str.split(",");
for(var i=0;i<arr.length;i++) {
    arr[i] = ++arr[i];
}

finished with non zero exit value

i had the same problem i resolve it by removing files that i added in the assets folder and those files name contains insupported characteres like "é" , " ", "ï" "è"... by renaming those name files or removing them you will have no problem.

On postback, how can I check which control cause postback in Page_Init event

Either directly in form parameters or

string controlName = this.Request.Params.Get("__EVENTTARGET");

Edit: To check if a control caused a postback (manually):

// input Image with name="imageName"
if (this.Request["imageName"+".x"] != null) ...;//caused postBack

// Other input with name="name"
if (this.Request["name"] != null) ...;//caused postBack

You could also iterate through all the controls and check if one of them caused a postBack using the above code.

How can I change default dialog button text color in android 5

For me it was different, I used a button theme

<style name="ButtonLight_pink" parent="android:Widget.Button">
    <item name="android:background">@drawable/light_pink_btn_default_holo_light</item>
    <item name="android:minHeight">48dip</item>
    <item name="android:minWidth">64dip</item>
    <item name="android:textColor">@color/tab_background_light_pink</item>
</style>

and because android:textColor was white there… I didn't see any button text (Dialog buttons are basically buttons too). There we go, changed it, fixed it.

Fetch the row which has the Max value for a column

Not being at work, I don't have Oracle to hand, but I seem to recall that Oracle allows multiple columns to be matched in an IN clause, which should at least avoid the options that use a correlated subquery, which is seldom a good idea.

Something like this, perhaps (can't remember if the column list should be parenthesised or not):

SELECT * 
FROM MyTable
WHERE (User, Date) IN
  ( SELECT User, MAX(Date) FROM MyTable GROUP BY User)

EDIT: Just tried it for real:

SQL> create table MyTable (usr char(1), dt date);
SQL> insert into mytable values ('A','01-JAN-2009');
SQL> insert into mytable values ('B','01-JAN-2009');
SQL> insert into mytable values ('A', '31-DEC-2008');
SQL> insert into mytable values ('B', '31-DEC-2008');
SQL> select usr, dt from mytable
  2  where (usr, dt) in 
  3  ( select usr, max(dt) from mytable group by usr)
  4  /

U DT
- ---------
A 01-JAN-09
B 01-JAN-09

So it works, although some of the new-fangly stuff mentioned elsewhere may be more performant.

How to use executeReader() method to retrieve the value of just one cell

It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:

String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();

Here is more information about Connecting to database and managing data.

In Gradle, is there a better way to get Environment Variables?

In android gradle 0.4.0 you can just do:

println System.env.HOME

classpath com.android.tools.build:gradle-experimental:0.4.0

How to use timeit module

lets setup the same dictionary in each of the following and test the execution time.

The setup argument is basically setting up the dictionary

Number is to run the code 1000000 times. Not the setup but the stmt

When you run this you can see that index is way faster than get. You can run it multiple times to see.

The code basically tries to get the value of c in the dictionary.

import timeit

print('Getting value of C by index:', timeit.timeit(stmt="mydict['c']", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))
print('Getting value of C by get:', timeit.timeit(stmt="mydict.get('c')", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))

Here are my results, yours will differ.

by index: 0.20900007452246427

by get: 0.54841166886888

Can't use WAMP , port 80 is used by IIS 7.5

If you're using Windows 10, as I am, and the port is occupied by Microsoft-IIS/10.0, change the lines 62 and 63, of the httpd.conf, from:

Listen 0.0.0.0:80
Listen [::0]:80

To:

Listen 0.0.0.0:8080
Listen [::0]:8080

As the people here suggested.

And also, change the line 221, from:

ServerName localhost:80

To:

ServerName localhost:8080

Now, your host will be available at http://localhost:8080/.

Action Image MVC3 Razor

I have joined the answer from Lucas and "ASP.NET MVC Helpers, Merging two object htmlAttributes together" and plus controllerName to following code:

// Sample usage in CSHTML

 @Html.ActionImage("Edit",
       "EditController"
        new { id = MyId },
       "~/Content/Images/Image.bmp",
       new { width=108, height=129, alt="Edit" })

And the extension class for the code above:

using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;

namespace MVC.Extensions
{
    public static class MvcHtmlStringExt
    {
        // Extension method
        public static MvcHtmlString ActionImage(
          this HtmlHelper html,
          string action,
          string controllerName,
          object routeValues,
          string imagePath,
          object htmlAttributes)
        {
            //https://stackoverflow.com/questions/4896439/action-image-mvc3-razor
            var url = new UrlHelper(html.ViewContext.RequestContext);

            // build the <img> tag
            var imgBuilder = new TagBuilder("img");
            imgBuilder.MergeAttribute("src", url.Content(imagePath));

            var dictAttributes = htmlAttributes.ToDictionary();

            if (dictAttributes != null)
            {
                foreach (var attribute in dictAttributes)
                {
                    imgBuilder.MergeAttribute(attribute.Key, attribute.Value.ToString(), true);
                }
            }                        

            string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

            // build the <a> tag
            var anchorBuilder = new TagBuilder("a");
            anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
            anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside            
            string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(anchorHtml);
        }

        public static IDictionary<string, object> ToDictionary(this object data)
        {
            //https://stackoverflow.com/questions/6038255/asp-net-mvc-helpers-merging-two-object-htmlattributes-together

            if (data == null) return null; // Or throw an ArgumentNullException if you want

            BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
            Dictionary<string, object> dictionary = new Dictionary<string, object>();

            foreach (PropertyInfo property in
                     data.GetType().GetProperties(publicAttributes))
            {
                if (property.CanRead)
                {
                    dictionary.Add(property.Name, property.GetValue(data, null));
                }
            }
            return dictionary;
        }
    }
}

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

http://msdn.microsoft.com/en-us/library/ms182776.aspx

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

How to create batch file in Windows using "start" with a path and command with spaces

start "" "c:\path with spaces\app.exe" "C:\path parameter\param.exe"

When I used above suggestion, I've got:

'c:\path' is not recognized a an internal or external command, operable program or batch file.

I think second qoutation mark prevent command to run. After some search below solution save my day:

start "" CALL "c:\path with spaces\app.exe" "C:\path parameter\param.exe"

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

Your question is already answered here :

Basically, rt.jar contains all of the compiled class files for the base Java Runtime ("rt") Environment. Normally, javac should know the path to this file

Also, a good link on what happens if we try to include our class file in rt.jar.

How to get the name of a class without the package?

If using a StackTraceElement, use:

String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);

System.out.println(simpleClassName);

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

SQL Server query to find all current database names

Another to add to the mix:

EXEC sp_databases

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

If you have a manifest file which lists all the files that were installed with make install you can run this command which I have from another answer:

cat install_manifest.txt | xargs echo rm | sh

If you have sudo make install you will need to add a sudo to your uninstall:

cat install_manifest.txt | xargs echo sudo rm | sh

Go to first line in a file in vim?

If you are using gvim, you could just hit Ctrl + Home to go the first line. Similarly, Ctrl + End goes to the last line.

On select change, get data attribute value

Try the following:

$('select').change(function(){
  alert($(this).children('option:selected').data('id'));
});

Your change subscriber subscribes to the change event of the select, so the this parameter is the select element. You need to find the selected child to get the data-id from.

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

INSERT INTO mytable(col1,col2) 
    SELECT 'val1','val2' 
    WHERE NOT EXISTS (SELECT 1 FROM mytable WHERE col1='val1')

Operand type clash: uniqueidentifier is incompatible with int

Sounds to me like at least one of those tables has defined UserID as a uniqueidentifier, not an int. Did you check the data in each table? What does SELECT TOP 1 UserID FROM each table yield? An int or a GUID?

EDIT

I think you have built a procedure based on all tables that contain a column named UserID. I think you should not have included the aspnet_Membership table in your script, since it's not really one of "your" tables.

If you meant to design your tables around the aspnet_Membership database, then why are the rest of the columns int when that table clearly uses a uniqueidentifier for the UserID column?

Using a dictionary to select function to execute

Not proud of it, but:

def myMain(key):
    def ExecP1():
        pass
    def ExecP2():
        pass
    def ExecP3():
        pass
    def ExecPn():
        pass 
    locals()['Exec' + key]()

I do however recommend that you put those in a module/class whatever, this is truly horrible.

C pointer to array/array of pointers disambiguation

I don't know if it has an official name, but I call it the Right-Left Thingy(TM).

Start at the variable, then go right, and left, and right...and so on.

int* arr1[8];

arr1 is an array of 8 pointers to integers.

int (*arr2)[8];

arr2 is a pointer (the parenthesis block the right-left) to an array of 8 integers.

int *(arr3[8]);

arr3 is an array of 8 pointers to integers.

This should help you out with complex declarations.

Java for loop syntax: "for (T obj : objects)"

The variable objectSummary holds the current object of type S3ObjectSummary returned from the objectListing.getObjectSummaries() and iterate over the collection.

Here is an example of this enhanced for loop from Java Tutorials

class EnhancedForDemo {
 public static void main(String[] args){
      int[] numbers = {1,2,3,4,5,6,7,8,9,10};
      for (int item : numbers) {
        System.out.println("Count is: " + item);
      }
 }
}

In this example, the variable item holds the current value from the numbers array.

Output is as follows:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Hope this helps !

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

EL interprets ${bean.propretyName} as described - the propertyName becomes getPropertyName() on the assumption you are using explicit or implicit methods of generating getter/setters

You can override this behavior by explicitly identifying the name as a function: ${bean.methodName()} This calls the function method Name() directly without modification.

It isn't always true that your accessors are named "get...".

Default values and initialization in Java

In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.

In the second code sample, a is class member variable, hence it will be initialized to the default value.

Arithmetic overflow error converting numeric to data type numeric

If you want to reduce the size to decimal(7,2) from decimal(9,2) you will have to account for the existing data with values greater to fit into decimal(7,2). Either you will have to delete those numbers are truncate it down to fit into your new size. If there was no data for the field you are trying to update it will do it automatically without issues

Convert int to ASCII and back in Python

>>> ord("a")
97
>>> chr(97)
'a'

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

General Formula

Here, W and H are width and height of input, F are filter dimensions, P is padding size (i.e., number of rows or columns to be padded)

For SAME padding:

SAME Padding

For VALID padding:

VALID padding

Plot a legend outside of the plotting area in base graphics?

Another solution, besides the ondes already mentioned (using layout or par(xpd=TRUE)) is to overlay your plot with a transparent plot over the entire device and then add the legend to that.

The trick is to overlay a (empty) graph over the complete plotting area and adding the legend to that. We can use the par(fig=...) option. First we instruct R to create a new plot over the entire plotting device:

par(fig=c(0, 1, 0, 1), oma=c(0, 0, 0, 0), mar=c(0, 0, 0, 0), new=TRUE)

Setting oma and mar is needed since we want to have the interior of the plot cover the entire device. new=TRUE is needed to prevent R from starting a new device. We can then add the empty plot:

plot(0, 0, type='n', bty='n', xaxt='n', yaxt='n')

And we are ready to add the legend:

legend("bottomright", ...)

will add a legend to the bottom right of the device. Likewise, we can add the legend to the top or right margin. The only thing we need to ensure is that the margin of the original plot is large enough to accomodate the legend.

Putting all this into a function;

add_legend <- function(...) {
  opar <- par(fig=c(0, 1, 0, 1), oma=c(0, 0, 0, 0), 
    mar=c(0, 0, 0, 0), new=TRUE)
  on.exit(par(opar))
  plot(0, 0, type='n', bty='n', xaxt='n', yaxt='n')
  legend(...)
}

And an example. First create the plot making sure we have enough space at the bottom to add the legend:

par(mar = c(5, 4, 1.4, 0.2))
plot(rnorm(50), rnorm(50), col=c("steelblue", "indianred"), pch=20)

Then add the legend

add_legend("topright", legend=c("Foo", "Bar"), pch=20, 
   col=c("steelblue", "indianred"),
   horiz=TRUE, bty='n', cex=0.8)

Resulting in:

Example figure shown legend in top margin

How to set up Android emulator proxy settings

Sometime even after setting all it may not work. I have tried all the methods like

  1. Setting the proxy in Emulator APN
  2. Setting it thru eclipse preferences --> Android --> Launch

Nothing worked. Then I did the following which worked instantly.

Goto eclipse Run --> run configurations. Under Android Applications you can see you application. Now, on the right hand side click on the Target tab. Under the 'Additional Emulator Command line options' add the following.

-dns-server <DNS servers from your local machine upto three> -http-proxy http://<your proxy>:<your proxy port>

The catch here is that the DNS Server setting should be from your local system. Goto cmd prompt and run ipconfig to check your DNS servers. Same with the proxy server and port. Whatever works for your browser should be put in here.

The remote certificate is invalid according to the validation procedure

This usually occurs because either of the following are true:

  • The certificate is self-signed and not added as a trusted certificate.
  • The certificate is expired.
  • The certificate is signed by a root certificate that's not installed on your machine.
  • The certificate is signed using the fully qualified domain address of the server. Meaning: cannot use "xyzServerName" but instead must use "xyzServerName.ad.state.fl.us" because that's basically the server name as far as the SSL cert is concerned.
  • A revocation list is probed, but cannot be found/used.
  • The certificate is signed via intermediate CA certificate and server does not serve that intermediate certificate along with host certificate.

Try getting some information about the certificate of the server and see if you need to install any specific certs on your client to get it to work.

Best practice to validate null and empty collection in Java

If you use Spring frameworks, then you can use CollectionUtils to check against both Collections (List, Array) and Map etc.

if(CollectionUtils.isEmpty(...)) {...}

Pass variables to AngularJS controller, best practice?

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)" 

Show image using file_get_contents

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

exactly.

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

Detecting TCP Client Disconnect

I toyed with a few solutions but this one seems to work best for detecting host and/or client disconnection in Windows. It is for non-blocking sockets, and derived from IBM's example.

char buf;
int length=recv(socket, &buf, 0, 0);
int nError=WSAGetLastError();
if(nError!=WSAEWOULDBLOCK&&nError!=0){
    return 0;
}   
if (nError==0){
    if (length==0) return 0;
}

addEventListener vs onclick

An element can have only one event handler attached per event type, but can have multiple event listeners.


So, how does it look in action?

Only the last event handler assigned gets run:

const btn = document.querySelector(".btn")
button.onclick = () => {
  console.log("Hello World");
};
button.onclick = () => {
  console.log("How are you?");
};
button.click() // "Hello World" 

All event listeners will be triggered:

const btn = document.querySelector(".btn")
button.addEventListener("click", event => {
  console.log("Hello World");
})
button.addEventListener("click", event => {
  console.log("How are you?");
})
button.click() 
// "Hello World"
// "How are you?"

IE Note: attachEvent is no longer supported. Starting with IE 11, use addEventListener: docs.

PHP - print all properties of an object

To get more information use this custom TO($someObject) function:

I wrote this simple function which not only displays the methods of a given object, but also shows its properties, encapsulation and some other useful information like release notes if given.

function TO($object){ //Test Object
                if(!is_object($object)){
                    throw new Exception("This is not a Object"); 
                    return;
                }
                if(class_exists(get_class($object), true)) echo "<pre>CLASS NAME = ".get_class($object);
                $reflection = new ReflectionClass(get_class($object));
                echo "<br />";
                echo $reflection->getDocComment();

                echo "<br />";

                $metody = $reflection->getMethods();
                foreach($metody as $key => $value){
                    echo "<br />". $value;
                }

                echo "<br />";

                $vars = $reflection->getProperties();
                foreach($vars as $key => $value){
                    echo "<br />". $value;
                }
                echo "</pre>";
            }

To show you how it works I will create now some random example class. Lets create class called Person and lets place some release notes just above the class declaration:

        /**
         * DocNotes -  This is description of this class if given else it will display false
         */
        class Person{
            private $name;
            private $dob;
            private $height;
            private $weight;
            private static $num;

            function __construct($dbo, $height, $weight, $name) {
                $this->dob = $dbo;
                $this->height = (integer)$height;
                $this->weight = (integer)$weight;
                $this->name = $name;
                self::$num++;

            }
            public function eat($var="", $sar=""){
                echo $var;
            }
            public function potrzeba($var =""){
                return $var;
            }
        }

Now lets create a instance of a Person and wrap it with our function.

    $Wictor = new Person("27.04.1987", 170, 70, "Wictor");
    TO($Wictor);

This will output information about the class name, parameters and methods including encapsulation information and the number of parameters, names of parameters for each method, method location and lines of code where it exists. See the output below:

CLASS NAME = Person
/**
             * DocNotes -  This is description of this class if given else it will display false
             */

Method [  public method __construct ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 75 - 82

  - Parameters [4] {
    Parameter #0 [  $dbo ]
    Parameter #1 [  $height ]
    Parameter #2 [  $weight ]
    Parameter #3 [  $name ]
  }
}

Method [  public method eat ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 83 - 85

  - Parameters [2] {
    Parameter #0 [  $var = '' ]
    Parameter #1 [  $sar = '' ]
  }
}

Method [  public method potrzeba ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 86 - 88

  - Parameters [1] {
    Parameter #0 [  $var = '' ]
  }
}


Property [  private $name ]

Property [  private $dob ]

Property [  private $height ]

Property [  private $weight ]

Property [ private static $num ]

Making a mocked method return an argument that was passed to it

This is a pretty old question but i think still relevant. Also the accepted answer works only for String. Meanwhile there is Mockito 2.1 and some imports have changed, so i would like to share my current answer:

import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

@Mock
private MyClass myClass;

// this will return anything you pass, but it's pretty unrealistic
when(myClass.myFunction(any())).then(returnsFirstArg());
// it is more "life-like" to accept only the right type
when(myClass.myFunction(any(ClassOfArgument.class))).then(returnsFirstArg());

The myClass.myFunction would look like:

public class MyClass {
    public ClassOfArgument myFunction(ClassOfArgument argument){
        return argument;
    }  
}

How do I determine if my python shell is executing in 32bit or 64bit?

platform.architecture() is problematic (and expensive).

Conveniently test for sys.maxsize > 2**32 since Py2.6 .

This is a reliable test for the actual (default) pointer size and compatible at least since Py2.3: struct.calcsize('P') == 8. Also: ctypes.sizeof(ctypes.c_void_p) == 8.

Notes: There can be builds with gcc option -mx32 or so, which are 64bit architecture applications, but use 32bit pointers as default (saving memory and speed). 'sys.maxsize = ssize_t' may not strictly represent the C pointer size (its usually 2**31 - 1 anyway). And there were/are systems which have different pointer sizes for code and data and it needs to be clarified what exactly is the purpose of discerning "32bit or 64bit mode?"

validate natural input number with ngpattern

<label>Mobile Number(*)</label>
<input id="txtMobile" ng-maxlength="10" maxlength="10" Validate-phone  required  name='strMobileNo' ng-model="formModel.strMobileNo" type="text"  placeholder="Enter Mobile Number">
<span style="color:red" ng-show="regForm.strMobileNo.$dirty && regForm.strMobileNo.$invalid"><span ng-show="regForm.strMobileNo.$error.required">Phone is required.</span>

the following code will help for phone number validation and the respected directive is

app.directive('validatePhone', function() {
var PHONE_REGEXP = /^[789]\d{9}$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = PHONE_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

How to define an empty object in PHP

You can use new stdClass() (which is recommended):

$obj_a = new stdClass();
$obj_a->name = "John";
print_r($obj_a);

// outputs:
// stdClass Object ( [name] => John ) 

Or you can convert an empty array to an object which produces a new empty instance of the stdClass built-in class:

$obj_b = (object) [];
$obj_b->name = "John";
print_r($obj_b);

// outputs: 
// stdClass Object ( [name] => John )  

Or you can convert the null value to an object which produces a new empty instance of the stdClass built-in class:

$obj_c = (object) null;
$obj_c->name = "John";
print($obj_c);

// outputs:
// stdClass Object ( [name] => John ) 

Export data from Chrome developer tool

I was trying to copy the size data measured from Chrome Network and stumbled on this post. I just found an easier way to "export" the data out to excel which is to copy the table and paste to excel.

The trick is click Control + A (select all) and once the entire table will be highlighted, paste it to Microsoft Excel. The only issue is if there are too many fields, not all rows are copied and you might have to copy and paste several times.

UPDATED: I found that copying the data only works when I turn off the filter options (the funnel-looking button above the table). – bendur

Dynamically load a JavaScript file

I have tweaked some of the above post with working example. Here we can give css and js in same array also.

$(document).ready(function(){

if (Array.prototype.contains === undefined) {
Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) { if (this[i] === obj) return true; }
    return false;
};
};

/* define object that will wrap our logic */
var jsScriptCssLoader = {

jsExpr : new RegExp( "js$", "i" ),
cssExpr : new RegExp( "css$", "i" ),
loadedFiles: [],

loadFile: function (cssJsFileArray) {
    var self = this;
    // remove duplicates with in array
    cssJsFileArray.filter((item,index)=>cssJsFileArray.indexOf(item)==index)
    var loadedFileArray = this.loadedFiles;
    $.each(cssJsFileArray, function( index, url ) {
            // if multiple arrays are loaded the check the uniqueness
            if (loadedFileArray.contains(url)) return;
            if( self.jsExpr.test( url ) ){
                $.get(url, function(data) {
                    self.addScript(data);
                });

            }else if( self.cssExpr.test( url ) ){
                $.get(url, function(data) {
                    self.addCss(data);
                });
            }

            self.loadedFiles.push(url);
    });

    // don't load twice accross different arrays

},
addScript: function (code) {
    var oNew = document.createElement("script");
    oNew.type = "text/javascript";
    oNew.textContent = code;
    document.getElementsByTagName("head")[0].appendChild(oNew);
},
addCss: function (code) {
    var oNew = document.createElement("style");
    oNew.textContent = code;
    document.getElementsByTagName("head")[0].appendChild(oNew);
}

};


//jsScriptCssLoader.loadFile(["css/1.css","css/2.css","css/3.css"]);
jsScriptCssLoader.loadFile(["js/common/1.js","js/2.js","js/common/file/fileReader.js"]);
});

Does JavaScript guarantee object property order?

This whole answer is in the context of spec compliance, not what any engine does at a particular moment or historically.

Generally, no

The actual question is very vague.

will the properties be in the same order that I added them

In what context?

The answer is: it depends on a number of factors. In general, no.

Sometimes, yes

Here is where you can count on property key order for plain Objects:

  • ES2015 compliant engine
  • Own properties
  • Object.getOwnPropertyNames(), Reflect.ownKeys(), Object.getOwnPropertySymbols(O)

In all cases these methods include non-enumerable property keys and order keys as specified by [[OwnPropertyKeys]] (see below). They differ in the type of key values they include (String and / or Symbol). In this context String includes integer values.

Object.getOwnPropertyNames(O)

Returns O's own String-keyed properties (property names).

Reflect.ownKeys(O)

Returns O's own String- and Symbol-keyed properties.

Object.getOwnPropertySymbols(O)

Returns O's own Symbol-keyed properties.

[[OwnPropertyKeys]]

The order is essentially: integer-like Strings in ascending order, non-integer-like Strings in creation order, Symbols in creation order. Depending which function invokes this, some of these types may not be included.

The specific language is that keys are returned in the following order:

  1. ... each own property key P of O [the object being iterated] that is an integer index, in ascending numeric index order

  2. ... each own property key P of O that is a String but is not an integer index, in property creation order

  3. ... each own property key P of O that is a Symbol, in property creation order

Map

If you're interested in ordered maps you should consider using the Map type introduced in ES2015 instead of plain Objects.

How can I convert a DateTime to an int?

string date = DateTime.Now.ToString();

date = date.Replace("/", "");
date = date.Replace(":", "");
date = date.Replace(" ", "");
date = date.Replace("AM", "");
date = date.Replace("PM", "");            
return date;

How do I limit the number of returned items?

models.Post.find({published: true}, {sort: {'date': -1}, limit: 20}, function(err, posts) {
 // `posts` with sorted length of 20
});

Converting String to "Character" array in Java

another way to do it.

String str="I am a good boy";
    char[] chars=str.toCharArray();

    Character[] characters=new Character[chars.length];
    for (int i = 0; i < chars.length; i++) {
        characters[i]=chars[i];
        System.out.println(chars[i]);
    }

How to set up datasource with Spring for HikariCP?

I found it in http://www.baeldung.com/hikaricp and it works.

Your pom.xml

<dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>2.6.3</version>
        </dependency>

Your data.xml

<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="jdbcUrl" value="${jdbc.databaseurl}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <constructor-arg ref="hikariConfig" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
      p:dataSource-ref="dataSource"
/>

Your jdbc.properties

jdbc.driverClassName=org.postgresql.Driver
jdbc.dialect=org.hibernate.dialect.PostgreSQL94Dialect
jdbc.databaseurl=jdbc:postgresql://localhost:5432/dev_db
jdbc.username=dev
jdbc.password=dev

How to convert a selection to lowercase or uppercase in Sublime Text

For Windows OS

For Uppercase CTRL + K + U

For Lowercase CTRL + K + L

Eclipse change project files location

Using Neon - just happened to me too. You would have to delete the Eclipse version (not from disk) in your Project Explorer and import the projects as existing projects. Of course, ensure that the project folders as a whole were moved and that the Eclipse meta files are still there as mentioned by @koenpeters.

Refactor does not handle this.

Learning Ruby on Rails

http://railsforzombies.org/ is a nice one. Introducing an all new way to learn Ruby on Rails in the browser with no additional configuration needed.

How to style child components from parent component's CSS file?

I have solved it outside Angular. I have defined a shared scss that I'm importing to my children.

shared.scss

%cell {
  color: #333333;
  background: #eee;
  font-size: 13px;
  font-weight: 600;
}

child.scss

@import 'styles.scss';
.cell {
  @extend %cell;
}

My proposed approach is a way how to solve the problem the OP has asked about. As mentioned at multiple occasions, ::ng-deep, :ng-host will get depreciated and disabling encapsulation is just too much of a code leakage, in my view.

Using HTML5/Canvas/JavaScript to take in-browser screenshots

JavaScript can read the DOM and render a fairly accurate representation of that using canvas. I have been working on a script which converts HTML into a canvas image. Decided today to make an implementation of it into sending feedbacks like you described.

The script allows you to create feedback forms which include a screenshot, created on the client's browser, along with the form. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.

It does not require any rendering from the server, as the whole image is created on the client's browser. The HTML2Canvas script itself is still in a very experimental state, as it does not parse nearly as much of the CSS3 attributes I would want it to, nor does it have any support to load CORS images even if a proxy was available.

Still quite limited browser compatibility (not because more couldn't be supported, just haven't had time to make it more cross browser supported).

For more information, have a look at the examples here:

http://hertzen.com/experiments/jsfeedback/

edit The html2canvas script is now available separately here and some examples here.

edit 2 Another confirmation that Google uses a very similar method (in fact, based on the documentation, the only major difference is their async method of traversing/drawing) can be found in this presentation by Elliott Sprehn from the Google Feedback team: http://www.elliottsprehn.com/preso/fluentconf/

What is Bit Masking?

A mask defines which bits you want to keep, and which bits you want to clear.

Masking is the act of applying a mask to a value. This is accomplished by doing:

  • Bitwise ANDing in order to extract a subset of the bits in the value
  • Bitwise ORing in order to set a subset of the bits in the value
  • Bitwise XORing in order to toggle a subset of the bits in the value

Below is an example of extracting a subset of the bits in the value:

Mask:   00001111b
Value:  01010101b

Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:

Mask:   00001111b
Value:  01010101b
Result: 00000101b

Masking is implemented using AND, so in C we get:

uint8_t stuff(...) {
  uint8_t mask = 0x0f;   // 00001111b
  uint8_t value = 0x55;  // 01010101b
  return mask & value;
}

Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &, and >> (shift right). This is how we can extract the four bytes from a 32-bit integer:

void more_stuff(uint32_t value) {             // Example value: 0x01020304
    uint32_t byte1 = (value >> 24);           // 0x01020304 >> 24 is 0x01 so
                                              // no masking is necessary
    uint32_t byte2 = (value >> 16) & 0xff;    // 0x01020304 >> 16 is 0x0102 so
                                              // we must mask to get 0x02
    uint32_t byte3 = (value >> 8)  & 0xff;    // 0x01020304 >> 8 is 0x010203 so
                                              // we must mask to get 0x03
    uint32_t byte4 = value & 0xff;            // here we only mask, no shifting
                                              // is necessary
    ...
}

Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:

uint32_t byte3 = (value & 0xff00) >> 8;

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

No events get triggered when the element is having disabled attribute.

None of the below will get triggered.

$("[disabled]").click( function(){ console.log("clicked") });//No Impact
$("[disabled]").hover( function(){ console.log("hovered") });//No Impact
$("[disabled]").dblclick( function(){ console.log("double clicked") });//No Impact

While readonly will be triggered.

$("[readonly]").click( function(){ console.log("clicked") });//log - clicked
$("[readonly]").hover( function(){ console.log("hovered") });//log - hovered
$("[readonly]").dblclick( function(){ console.log("double clicked") });//log - double clicked

Vue.js: Conditional class style binding

<i class="fa" v-bind:class="cravings"></i>

and add in computed :

computed: {
    cravings: function() {
        return this.content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline';
    }
}

Has an event handler already been added?

If I understand your problem correctly you may have bigger issues. You said that other objects may subscribe to these events. When the object is serialized and deserialized the other objects (the ones that you don't have control of) will lose their event handlers.

If you're not worried about that then keeping a reference to your event handler should be good enough. If you are worried about the side-effects of other objects losing their event handlers, then you may want to rethink your caching strategy.

Why is @font-face throwing a 404 error on woff files?

In addition to Ian's answer, I had to allow the font extensions in the request filtering module to make it work.

<system.webServer>
  <staticContent>
    <remove fileExtension=".woff" />
    <remove fileExtension=".woff2" />
    <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
    <mimeMap fileExtension=".woff2" mimeType="application/x-font-woff" />
  </staticContent>
  <security>
      <requestFiltering>
          <fileExtensions>
              <add fileExtension=".woff" allowed="true" />
              <add fileExtension=".ttf" allowed="true" />
              <add fileExtension=".woff2" allowed="true" />
          </fileExtensions>
      </requestFiltering>
  </security>    
</system.webServer>

Git commit in terminal opens VIM, but can't get back to terminal

You need to return to normal mode and save the commit message with either

<Esc>:wq

or

<Esc>:x

or

<Esc>ZZ

The Esc key returns you from insert mode to normal mode. The :wq, :x or ZZ sequence writes the changes and exits the editor.

Fatal error: Class 'ZipArchive' not found in

For CentOS based server use

yum install php-pecl-zip.x86_64

Enable it by running: echo "extension=zip.so" >> /etc/php.d/zip.ini

Java ArrayList for integers

you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.

so if you want your code to work just put.

List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);

Do Java arrays have a maximum size?

Going by this article http://en.wikipedia.org/wiki/Criticism_of_Java#Large_arrays:

Java has been criticized for not supporting arrays of more than 231-1 (about 2.1 billion) elements. This is a limitation of the language; the Java Language Specification, Section 10.4, states that:

Arrays must be indexed by int values... An attempt to access an array component with a long index value results in a compile-time error.

Supporting large arrays would also require changes to the JVM. This limitation manifests itself in areas such as collections being limited to 2 billion elements and the inability to memory map files larger than 2 GiB. Java also lacks true multidimensional arrays (contiguously allocated single blocks of memory accessed by a single indirection), which limits performance for scientific and technical computing.

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

PHP preg_replace special characters

do this in two steps:

  1. replace not letter characters with this regex:

    [\/\&%#\$]

  2. replace quotes with this regex:

    [\"\']

and use preg_replace:

$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $yourString);
$stringWithQuotesReplacedWithSpaces = preg_replace("/[\"\']/", " ", $stringWithoutNonLetterCharacters);

ping response "Request timed out." vs "Destination Host unreachable"

As I understand it, "request timeout" means the ICMP packet reached from one host to the other host but the reply could not reach the requesting host. There may be more packet loss or some physical issue. "destination host unreachable" means there is no proper route defined between two hosts.

how to align img inside the div to the right?

<div style="width:300px; text-align:right;">
        <img src="someimgage.gif">
</div>

How do I REALLY reset the Visual Studio window layout?

I close them, but they always come back

When you say "they always come back" do you mean "next time you restart Visual Studio" or "immediately"?

One quirk of Visual Studio (at least VS2005) is that settings aren't saved until you exit. That means that if VS crashes at all while you are using it, any layout changes you made will be lost. The way around this is to always gracefully exit when you have set up everything like you want it to be.

Not sure if this will help your particular situation though.

Difference between .dll and .exe?

EXE:

  1. It's a executable file
  2. When loading an executable, no export is called, but only the module entry point.
  3. When a system launches new executable, a new process is created
  4. The entry thread is called in context of main thread of that process.

DLL:

  1. It's a Dynamic Link Library
  2. There are multiple exported symbols.
  3. The system loads a DLL into the context of an existing process.

For More Details: http://www.c-sharpcorner.com/Interviews/Answer/Answers.aspxQuestionId=1431&MajorCategoryId=1&MinorCategoryId=1 http://wiki.answers.com/Q/What_is_the_difference_between_an_EXE_and_a_DLL

Reference: http://www.dotnetspider.com/forum/34260-What-difference-between-dll-exe.aspx

Table Height 100% inside Div element

Had a similar problem. My solution was to give the inner table a fixed height of 1px and set the height of the td in the inner table to 100%. Against all odds, it works fine, tested in IE, Chrome and FF!

Using Mockito to test abstract classes

You can extend the abstract class with an anonymous class in your test. For example (using Junit 4):

private AbstractClassName classToTest;

@Before
public void preTestSetup()
{
    classToTest = new AbstractClassName() { };
}

// Test the AbstractClassName methods.

Loop through each cell in a range of cells when given a Range object

You could use Range.Rows, Range.Columns or Range.Cells. Each of these collections contain Range objects.

Here's how you could modify Dick's example so as to work with Rows:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCell In rRng.Rows
        Debug.Print rCell.Address, rCell.Value
    Next rCell

End Sub

And Columns:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCol In rRng.Columns
        For Each rCell In rCol.Rows
            Debug.Print rCell.Address, rCell.Value
        Next rCell
    Next rCol

End Sub

Removing html5 required attribute with jQuery

Using Javascript:

document.querySelector('#edit-submitted-first-name').required = false;

Using jQuery:

$('#edit-submitted-first-name').removeAttr('required');

Open source PDF library for C/C++ application?

PDF Hummus. see for http://pdfhummus.com/ - contains all required features for manipulation with PDF files except rendering.

Prevent flex items from overflowing a container

Your flex items have

flex: 0 0 200px; /* <aside> */
flex: 1 0 auto;  /* <article> */ 

That means:

  • The <aside> will start at 200px wide.

    Then it won't grow nor shrink.

  • The <article> will start at the width given by the content.

    Then, if there is available space, it will grow to cover it.

    Otherwise it won't shrink.

To prevent horizontal overflow, you can:

  • Use flex-basis: 0 and then let them grow with a positive flex-grow.
  • Use a positive flex-shrink to let them shrink if there isn't enough space.

To prevent vertical overflow, you can

  • Use min-height instead of height to allow the flex items grow more if necessary
  • Use overflow different than visible on the flex items
  • Use overflow different than visible on the flex container

For example,

_x000D_
_x000D_
main, aside, article {
  margin: 10px;
  border: solid 1px #000;
  border-bottom: 0;
  min-height: 50px; /* min-height instead of height */
}
main {
  display: flex;
}
aside {
  flex: 0 1 200px; /* Positive flex-shrink */
}
article {
  flex: 1 1 auto; /* Positive flex-shrink */
}
_x000D_
<main>
  <aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>
  <article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>
</main>
_x000D_
_x000D_
_x000D_

Declare and initialize a Dictionary in Typescript

I agree with thomaux that the initialization type checking error is a TypeScript bug. However, I still wanted to find a way to declare and initialize a Dictionary in a single statement with correct type checking. This implementation is longer, however it adds additional functionality such as a containsKey(key: string) and remove(key: string) method. I suspect that this could be simplified once generics are available in the 0.9 release.

First we declare the base Dictionary class and Interface. The interface is required for the indexer because classes cannot implement them.

interface IDictionary {
    add(key: string, value: any): void;
    remove(key: string): void;
    containsKey(key: string): bool;
    keys(): string[];
    values(): any[];
}

class Dictionary {

    _keys: string[] = new string[];
    _values: any[] = new any[];

    constructor(init: { key: string; value: any; }[]) {

        for (var x = 0; x < init.length; x++) {
            this[init[x].key] = init[x].value;
            this._keys.push(init[x].key);
            this._values.push(init[x].value);
        }
    }

    add(key: string, value: any) {
        this[key] = value;
        this._keys.push(key);
        this._values.push(value);
    }

    remove(key: string) {
        var index = this._keys.indexOf(key, 0);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);

        delete this[key];
    }

    keys(): string[] {
        return this._keys;
    }

    values(): any[] {
        return this._values;
    }

    containsKey(key: string) {
        if (typeof this[key] === "undefined") {
            return false;
        }

        return true;
    }

    toLookup(): IDictionary {
        return this;
    }
}

Now we declare the Person specific type and Dictionary/Dictionary interface. In the PersonDictionary note how we override values() and toLookup() to return the correct types.

interface IPerson {
    firstName: string;
    lastName: string;
}

interface IPersonDictionary extends IDictionary {
    [index: string]: IPerson;
    values(): IPerson[];
}

class PersonDictionary extends Dictionary {
    constructor(init: { key: string; value: IPerson; }[]) {
        super(init);
    }

    values(): IPerson[]{
        return this._values;
    }

    toLookup(): IPersonDictionary {
        return this;
    }
}

And here is a simple initialization and usage example:

var persons = new PersonDictionary([
    { key: "p1", value: { firstName: "F1", lastName: "L2" } },
    { key: "p2", value: { firstName: "F2", lastName: "L2" } },
    { key: "p3", value: { firstName: "F3", lastName: "L3" } }
]).toLookup();


alert(persons["p1"].firstName + " " + persons["p1"].lastName);
// alert: F1 L2

persons.remove("p2");

if (!persons.containsKey("p2")) {
    alert("Key no longer exists");
    // alert: Key no longer exists
}

alert(persons.keys().join(", "));
// alert: p1, p3

Format telephone and credit card numbers in AngularJS

I created an AngularJS module to handle this issue regarding phonenumbers for myself with a custom directive and accompanying filter.

jsfiddle example: http://jsfiddle.net/aberke/s0xpkgmq/

Filter use example: <p>{{ phonenumberValue | phonenumber }}</p>

Filter code:

.filter('phonenumber', function() {
    /* 
    Format phonenumber as: c (xxx) xxx-xxxx
        or as close as possible if phonenumber length is not 10
        if c is not '1' (country code not USA), does not use country code
    */

    return function (number) {
        /* 
        @param {Number | String} number - Number that will be formatted as telephone number
        Returns formatted number: (###) ###-####
            if number.length < 4: ###
            else if number.length < 7: (###) ###

        Does not handle country codes that are not '1' (USA)
        */
        if (!number) { return ''; }

        number = String(number);

        // Will return formattedNumber. 
        // If phonenumber isn't longer than an area code, just show number
        var formattedNumber = number;

        // if the first character is '1', strip it out and add it back
        var c = (number[0] == '1') ? '1 ' : '';
        number = number[0] == '1' ? number.slice(1) : number;

        // # (###) ###-#### as c (area) front-end
        var area = number.substring(0,3);
        var front = number.substring(3, 6);
        var end = number.substring(6, 10);

        if (front) {
            formattedNumber = (c + "(" + area + ") " + front);  
        }
        if (end) {
            formattedNumber += ("-" + end);
        }
        return formattedNumber;
    };
});

Directive use example:

<phonenumber-directive placeholder="'Input phonenumber here'" model='myModel.phonenumber'></phonenumber-directive>

Directive code:

.directive('phonenumberDirective', ['$filter', function($filter) {
    /*
    Intended use:
        <phonenumber-directive placeholder='prompt' model='someModel.phonenumber'></phonenumber-directive>
    Where:
        someModel.phonenumber: {String} value which to bind only the numeric characters [0-9] entered
            ie, if user enters 617-2223333, value of 6172223333 will be bound to model
        prompt: {String} text to keep in placeholder when no numeric input entered
    */

    function link(scope, element, attributes) {

        // scope.inputValue is the value of input element used in template
        scope.inputValue = scope.phonenumberModel;

        scope.$watch('inputValue', function(value, oldValue) {

            value = String(value);
            var number = value.replace(/[^0-9]+/g, '');
            scope.phonenumberModel = number;
            scope.inputValue = $filter('phonenumber')(number);
        });
    }

    return {
        link: link,
        restrict: 'E',
        scope: {
            phonenumberPlaceholder: '=placeholder',
            phonenumberModel: '=model',
        },
        // templateUrl: '/static/phonenumberModule/template.html',
        template: '<input ng-model="inputValue" type="tel" class="phonenumber" placeholder="{{phonenumberPlaceholder}}" title="Phonenumber (Format: (999) 9999-9999)">',
    };
}])

Full code with module and how to use it: https://gist.github.com/aberke/042eef0f37dba1138f9e

Jquery href click - how can I fire up an event?

You are binding the click event to anchors with an href attribute with value sign_new.

Either bind anchors with class sign_new or bind anchors with href value #sign_up. I would prefer the former.

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

int object is not iterable?

try:

for i in str(inp):

That will iterate over the characters in the string representation. Once you have each character you can use it like a separate number.

how to check if string contains '+' character

You need this instead:

if(s.contains("+"))

contains() method of String class does not take regular expression as a parameter, it takes normal text.


EDIT:

String s = "ddjdjdj+kfkfkf";

if(s.contains("+"))
{
    String parts[] = s.split("\\+");
    System.out.print(parts[0]);
}

OUTPUT:

ddjdjdj

What is the difference between declarations, providers, and import in NgModule?

Adding a quick cheat sheet that may help after the long break with Angular:


DECLARATIONS

Example:

declarations: [AppComponent]

What can we inject here? Components, pipes, directives


IMPORTS

Example:

imports: [BrowserModule, AppRoutingModule]

What can we inject here? other modules


PROVIDERS

Example:

providers: [UserService]

What can we inject here? services


BOOTSTRAP

Example:

bootstrap: [AppComponent]

What can we inject here? the main component that will be generated by this module (top parent node for a component tree)


ENTRY COMPONENTS

Example:

entryComponents: [PopupComponent]

What can we inject here? dynamically generated components (for instance by using ViewContainerRef.createComponent())


EXPORT

Example:

export: [TextDirective, PopupComponent, BrowserModule]

What can we inject here? components, directives, modules or pipes that we would like to have access to them in another module (after importing this module)

Creating Scheduled Tasks

This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

It is nicely designed Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .Configure()
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDaily()
    .RunEveryXMinutes(10)
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))
    .Execute();

Is there a way to call a stored procedure with Dapper?

In the simple case you can do:

var user = cnn.Query<User>("spGetUser", new {Id = 1}, 
        commandType: CommandType.StoredProcedure).First();

If you want something more fancy, you can do:

 var p = new DynamicParameters();
 p.Add("@a", 11);
 p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
 p.Add("@c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

 cnn.Execute("spMagicProc", p, commandType: CommandType.StoredProcedure); 

 int b = p.Get<int>("@b");
 int c = p.Get<int>("@c"); 

Additionally you can use exec in a batch, but that is more clunky.

How to query all the GraphQL type fields without writing a long query?

Unfortunately what you'd like to do is not possible. GraphQL requires you to be explicit about specifying which fields you would like returned from your query.

Capture key press (or keydown) event on DIV element

tabindex HTML attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab key). Read MDN Web Docs for full reference.

Using Jquery

_x000D_
_x000D_
$( "#division" ).keydown(function(evt) {
    evt = evt || window.event;
    console.log("keydown: " + evt.keyCode);
});
_x000D_
#division {
  width: 90px;
  height: 30px;
  background: lightgrey;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="division" tabindex="0"></div>
_x000D_
_x000D_
_x000D_

Using JavaScript

_x000D_
_x000D_
var el = document.getElementById("division");

el.onkeydown = function(evt) {
    evt = evt || window.event;
    console.log("keydown: " + evt.keyCode);
};
_x000D_
#division {
  width: 90px;
  height: 30px;
  background: lightgrey;
}
_x000D_
<div id="division" tabindex="0"></div>
_x000D_
_x000D_
_x000D_

List method to delete last element in list as well as all elements

To delete the last element of the lists, you could use:

def deleteLast(self):
    if self.Ans:
        del self.Ans[-1]
    if self.masses:
        del self.masses[-1]

How do I get git to default to ssh and not https for new repositories

  • GitHub

    git config --global url.ssh://[email protected]/.insteadOf https://github.com/
    
  • BitBucket

    git config --global url.ssh://[email protected]/.insteadOf https://bitbucket.org/
    

That tells git to always use SSH instead of HTTPS when connecting to GitHub/BitBucket, so you'll authenticate by certificate by default, instead of being prompted for a password.

Could not load the Tomcat server configuration

You tried to start Tomcat and got the following error:

Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete

How to solve:

  • Close Eclipse
  • Copy all files from TOMCAT_7_HOME/conf to WORKSPACE_FOLDER/Servers/Tomcat v7.0 Server at localhost-config
  • Start Eclipse
  • Expand the Servers project, click on the Tomcat 7 project and hit F5
  • Start Tomcat from Eclipse

Use table name in MySQL SELECT "AS"

SELECT field1, field2, 'Test' AS field3 FROM Test; // replace with simple quote '

Using PowerShell to remove lines from a text file if it contains a string

Suppose you want to write that in the same file, you can do as follows:

Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)

Total memory used by Python process?

On Windows, you can use WMI (home page, cheeseshop):


def memory():
    import os
    from wmi import WMI
    w = WMI('.')
    result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid())
    return int(result[0].WorkingSet)

On Linux (from python cookbook http://code.activestate.com/recipes/286222/:

import os
_proc_status = '/proc/%d/status' % os.getpid()

_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
          'KB': 1024.0, 'MB': 1024.0*1024.0}

def _VmB(VmKey):
    '''Private.
    '''
    global _proc_status, _scale
     # get pseudo file  /proc/<pid>/status
    try:
        t = open(_proc_status)
        v = t.read()
        t.close()
    except:
        return 0.0  # non-Linux?
     # get VmKey line e.g. 'VmRSS:  9999  kB\n ...'
    i = v.index(VmKey)
    v = v[i:].split(None, 3)  # whitespace
    if len(v) < 3:
        return 0.0  # invalid format?
     # convert Vm value to bytes
    return float(v[1]) * _scale[v[2]]


def memory(since=0.0):
    '''Return memory usage in bytes.
    '''
    return _VmB('VmSize:') - since


def resident(since=0.0):
    '''Return resident memory usage in bytes.
    '''
    return _VmB('VmRSS:') - since


def stacksize(since=0.0):
    '''Return stack size in bytes.
    '''
    return _VmB('VmStk:') - since

How to return the current timestamp with Moment.js?

Try this

console.log(moment().format("MM ddd, YYYY HH:mm:ss a"));

_x000D_
_x000D_
console.log(moment().format("MM ddd, YYYY hh:mm:ss a"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Clear text in EditText when entered

In XML you can write like:

    <EditText
        android:id="@+id/txtsearch"
        android:layout_width="250dp"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:layout_weight="1"
        android:background="@drawable/roundlayoutbutton1"
        android:ems="10"
        android:gravity="center"
        android:inputType="text"
        android:textAllCaps="true"
        android:text="search_xxxx"

        android:textColor="@color/colorPrimaryDark"
        android:visibility="visible" />

and in java class you may have below one :

    EditText searchHost;

OnCreate() you write:

    searchHost=findViewById(R.id.txtsearch);

    searchHost.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(searchHost.getText().toString().equalsIgnoreCase("search_xxxx")){
                searchHost.setText("");
                Toast.makeText(getApplicationContext(),"Enter you text xxx...", Toast.LENGTH_LONG).show();
            }
        }
    });

It works fine for me.

syntax error, unexpected T_VARIABLE

There is no semicolon at the end of that instruction causing the error.

EDIT

Like RiverC pointed out, there is no semicolon at the end of the previous line!

require ("scripts/connect.php") 

EDIT

It seems you have no-semicolons whatsoever.

http://php.net/manual/en/language.basic-syntax.instruction-separation.php

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.

Pass values of checkBox to controller action in asp.net mvc4

For some reason Andrew method of creating the checkbox by hand didn't work for me using Mvc 5. Instead I used this

@Html.CheckBox("checkResp")

to create a checkbox that would play nice with the controller.

Matplotlib/pyplot: How to enforce axis range?

Try putting the call to axis after all plotting commands.

Difference between binary tree and binary search tree

A binary tree is a tree whose children are never more than two. A binary search tree follows the invariant that the left child should have a smaller value than the root node's key, while the right child should have a greater value than the root node's key.

Node / Express: EADDRINUSE, Address already in use - Kill server

I was using debugger and just not stopped the processes running with Ctrl+C. So when I wanted to start debugging I got this error.

java.net.URL read stream to byte[]

byte[] b = IOUtils.toByteArray((new URL( )).openStream()); //idiom

Note however, that stream is not closed in the above example.

if you want a (76-character) chunk (using commons codec)...

byte[] b = Base64.encodeBase64(IOUtils.toByteArray((new URL( )).openStream()), true);

Renew Provisioning Profile

For renew team provisioning profile managed by Xcode :

In the organizer of Xcode :

  • Right click on your device (in the left list)
  • Click on "Add device to provisioning portal"
  • Wait until it's done !

What is the maximum recursion depth in Python, and how to increase it?

As @alex suggested, you could use a generator function to do this sequentially instead of recursively.

Here's the equivalent of the code in your question:

def fib(n):
    def fibseq(n):
        """ Iteratively return the first n Fibonacci numbers, starting from 0. """
        a, b = 0, 1
        for _ in xrange(n):
            yield a
            a, b = b, a + b

    return sum(v for v in fibseq(n))

print format(fib(100000), ',d')  # -> no recursion depth error

Angular2: How to load data before rendering the component?

You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.

There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.

Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.

enter image description here

Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:

import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';

@Injectable()
export class MyResolver implements Resolve<MyData> {
  constructor(private ms: MyService, private router: Router) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
    let id = route.params['id'];

    return this.ms.getId(id).then(data => {
      if (data) {
        return data;
      } else {
        this.router.navigate(['/login']);
        return;
      }
    });
  }
}

and in the module:

import { MyResolver } from './my-resolver.service';

@NgModule({
  imports: [
    RouterModule.forChild(myRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [
    MyResolver
  ]
})
export class MyModule { }

and you can access it in your Component like this:

/////
 ngOnInit() {
    this.route.data
      .subscribe((data: { mydata: myData }) => {
        this.id = data.mydata.id;
      });
  }
/////

And in the Route something like this (usually in the app.routing.ts file):

////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////

Oracle Differences between NVL and Coalesce

COALESCE is more modern function that is a part of ANSI-92 standard.

NVL is Oracle specific, it was introduced in 80's before there were any standards.

In case of two values, they are synonyms.

However, they are implemented differently.

NVL always evaluates both arguments, while COALESCE usually stops evaluation whenever it finds the first non-NULL (there are some exceptions, such as sequence NEXTVAL):

SELECT  SUM(val)
FROM    (
        SELECT  NVL(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val
        FROM    dual
        CONNECT BY
                level <= 10000
        )

This runs for almost 0.5 seconds, since it generates SYS_GUID()'s, despite 1 being not a NULL.

SELECT  SUM(val)
FROM    (
        SELECT  COALESCE(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val
        FROM    dual
        CONNECT BY
                level <= 10000
        )

This understands that 1 is not a NULL and does not evaluate the second argument.

SYS_GUID's are not generated and the query is instant.

How to force 'cp' to overwrite directory instead of creating another one inside?

If you want to ensure bar/ ends up identical to foo/, use rsync instead:

rsync -a --delete foo/ bar/

If just a few things have changed, this will execute much faster than removing and re-copying the whole directory.

  • -a is 'archive mode', which copies faithfully files in foo/ to bar/
  • --delete removes extra files not in foo/ from bar/ as well, ensuring bar/ ends up identical
  • If you want to see what it's doing, add -vh for verbose and human-readable
  • Note: the slash after foo is required, otherwise rsync will copy foo/ to bar/foo/ rather than overwriting bar/ itself.
    • (Slashes after directories in rsync are confusing; if you're interested, here's the scoop. They tell rsync to refer to the contents of the directory, rather than the directory itself. So to overwrite from the contents of foo/ onto the contents of bar/, we use a slash on both. It's confusing because it won't work as expected with a slash on neither, though; rsync sneakily always interprets the destination path as though it has a slash, even though it honors an absence of a slash on the source path. So we need a slash on the source path to make it match the auto-added slash on the destination path, if we want to copy the contents of foo/ into bar/, rather than the directory foo/ itself landing into bar/ as bar/foo.)

rsync is very powerful and useful, if you're curious look around for what else it can do (such as copying over ssh).

Importing a function from a class in another file?

from otherfile import TheClass
theclass = TheClass()
# if you want to return the output of run
return theclass.run()  
# if you want to return run itself to be used later
return theclass.run

Change the end of comm system to:

if __name__ == '__main__':
    a_game = Comm_system()
    a_game.run()

It's those lines being always run that are causing it to be run when imported as well as when executed.

Remove directory from remote repository after adding them to .gitignore

The answer from Blundell should work, but for some bizarre reason it didn't do with me. I had to pipe first the filenames outputted by the first command into a file and then loop through that file and delete that file one by one.

git ls-files -i --exclude-from=.gitignore > to_remove.txt
while read line; do `git rm -r --cached "$line"`; done < to_remove.txt
rm to_remove.txt
git commit -m 'Removed all files that are in the .gitignore' 
git push origin master

Best way to convert list to comma separated string in java

The Separator you are using is a UI component. You would be better using a simple String sep = ", ".

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

Android Animation Alpha

Setting alpha to 1 before starting the animation worked for me:

AlphaAnimation animation1 = new AlphaAnimation(0.2f, 1.0f);
animation1.setDuration(500);
iv.setAlpha(1f);
iv.startAnimation(animation1);

At least on my tests, there's no flickering because of setting alpha before starting the animation. It just works fine.

How to export data from Excel spreadsheet to Sql Server 2008 table

There are several tools which can import Excel to SQL Server.

I am using DbTransfer (http://www.dbtransfer.com/Products/DbTransfer) to do the job. It's primarily focused on transfering data between databases and excel, xml, etc...

I have tried the openrowset method and the SQL Server Import / Export Assitant before. But I found these methods to be unnecessary complicated and error prone in constrast to doing it with one of the available dedicated tools.