Programs & Examples On #System sounds

jQuery-- Populate select from json

fiddle

var $select = $('#down'); 
$select.find('option').remove();  
$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

Function to check if a string is a date

If you have PHP 5.2 Joey's answer won't work. You need to extend PHP's DateTime class:

class ExDateTime extends DateTime{
    public static function createFromFormat($frmt,$time,$timezone=null){
        $v = explode('.', phpversion());
        if(!$timezone) $timezone = new DateTimeZone(date_default_timezone_get());
        if(((int)$v[0]>=5&&(int)$v[1]>=2&&(int)$v[2]>17)){
            return parent::createFromFormat($frmt,$time,$timezone);
        }
        return new DateTime(date($frmt, strtotime($time)), $timezone);
    }
}

and than you can use this class without problems:

ExDateTime::createFromFormat('d.m.Y G:i',$timevar);

UTF-8 byte[] to String

You could use the methods described in this question (especially since you start off with an InputStream): Read/convert an InputStream to a String

In particular, if you don't want to rely on external libraries, you can try this answer, which reads the InputStream via an InputStreamReader into a char[] buffer and appends it into a StringBuilder.

How to write console output to a txt file

In addition to the several programatic approaches discussed, another option is to redirect standard output from the shell. Here are several Unix and DOS examples.

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

you try read link this

Error:Execution failed for task ‘:app:processDevDebugManifest’. Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(25.3.0) then usd VERSION 26.0.0

: https://medium.com/@PongPloyAppDev/error-execution-failed-for-task-app-processdevdebugmanifest-48576be751

enter image description here

Windows Bat file optional argument parsing

If you want to use optional arguments, but not named arguments, then this approach worked for me. I think this is much easier code to follow.

REM Get argument values.  If not specified, use default values.
IF "%1"=="" ( SET "DatabaseServer=localhost" ) ELSE ( SET "DatabaseServer=%1" )
IF "%2"=="" ( SET "DatabaseName=MyDatabase" ) ELSE ( SET "DatabaseName=%2" )

REM Do work
ECHO Database Server = %DatabaseServer%
ECHO Database Name   = %DatabaseName%

ReSharper "Cannot resolve symbol" even when project builds

No soft caches removal solutions worked for me, it looks like there were issues generated between different RS versions installed over the years.

What worked for me was:

  • Uninstal resharper
  • remove all JetBrains folders within AppData\Local and AppData\Roaming
  • Install resharper again

All the settings need to be redone, etc but I couldnt get any better solution even with help of JetBrains team.

Handling the window closing event with WPF / MVVM Light Toolkit

Geez, seems like a lot of code going on here for this. Stas above had the right approach for minimal effort. Here is my adaptation (using MVVMLight but should be recognizable)... Oh and the PassEventArgsToCommand="True" is definitely needed as indicated above.

(credit to Laurent Bugnion http://blog.galasoft.ch/archive/2009/10/18/clean-shutdown-in-silverlight-and-wpf-applications.aspx)

   ... MainWindow Xaml
   ...
   WindowStyle="ThreeDBorderWindow" 
    WindowStartupLocation="Manual">



<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
        <cmd:EventToCommand Command="{Binding WindowClosingCommand}" PassEventArgsToCommand="True" />
    </i:EventTrigger>
</i:Interaction.Triggers> 

In the view model:

///<summary>
///  public RelayCommand<CancelEventArgs> WindowClosingCommand
///</summary>
public RelayCommand<CancelEventArgs> WindowClosingCommand { get; private set; }
 ...
 ...
 ...
        // Window Closing
        WindowClosingCommand = new RelayCommand<CancelEventArgs>((args) =>
                                                                      {
                                                                          ShutdownService.MainWindowClosing(args);
                                                                      },
                                                                      (args) => CanShutdown);

in the ShutdownService

    /// <summary>
    ///   ask the application to shutdown
    /// </summary>
    public static void MainWindowClosing(CancelEventArgs e)
    {
        e.Cancel = true;  /// CANCEL THE CLOSE - let the shutdown service decide what to do with the shutdown request
        RequestShutdown();
    }

RequestShutdown looks something like the following but basicallyRequestShutdown or whatever it is named decides whether to shutdown the application or not (which will merrily close the window anyway):

...
...
...
    /// <summary>
    ///   ask the application to shutdown
    /// </summary>
    public static void RequestShutdown()
    {

        // Unless one of the listeners aborted the shutdown, we proceed.  If they abort the shutdown, they are responsible for restarting it too.

        var shouldAbortShutdown = false;
        Logger.InfoFormat("Application starting shutdown at {0}...", DateTime.Now);
        var msg = new NotificationMessageAction<bool>(
            Notifications.ConfirmShutdown,
            shouldAbort => shouldAbortShutdown |= shouldAbort);

        // recipients should answer either true or false with msg.execute(true) etc.

        Messenger.Default.Send(msg, Notifications.ConfirmShutdown);

        if (!shouldAbortShutdown)
        {
            // This time it is for real
            Messenger.Default.Send(new NotificationMessage(Notifications.NotifyShutdown),
                                   Notifications.NotifyShutdown);
            Logger.InfoFormat("Application has shutdown at {0}", DateTime.Now);
            Application.Current.Shutdown();
        }
        else
            Logger.InfoFormat("Application shutdown aborted at {0}", DateTime.Now);
    }
    }

Are members of a C++ struct initialized to 0 by default?

Move pod members to a base class to shorten your initializer list:

struct foo_pod
{
    int x;
    int y;
    int z;
};

struct foo : foo_pod
{
    std::string name;
    foo(std::string name)
        : foo_pod()
        , name(name)
    {
    }
};

int main()
{
    foo f("bar");
    printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}

Case insensitive std::string.find()

Also make sense to provide Boost version: This will modify original strings.

#include <boost/algorithm/string.hpp>

string str1 = "hello world!!!";
string str2 = "HELLO";
boost::algorithm::to_lower(str1)
boost::algorithm::to_lower(str2)

if (str1.find(str2) != std::string::npos)
{
    // str1 contains str2
}

or using perfect boost xpression library

#include <boost/xpressive/xpressive.hpp>
using namespace boost::xpressive;
....
std::string long_string( "very LonG string" );
std::string word("long");
smatch what;
sregex re = sregex::compile(word, boost::xpressive::icase);
if( regex_match( long_string, what, re ) )
{
    cout << word << " found!" << endl;
}

In this example you should pay attention that your search word don't have any regex special characters.

How to properly add include directories with CMake

I had the same problem.

My project directory was like this:

    --project
    ---Classes
    ----Application
    -----.h and .c files
    ----OtherFolders
    --main.cpp

And what I used to include the files in all those folders:

    file(GLOB source_files
            "*.h"
            "*.cpp"
            "Classes/*/*.cpp"
            "Classes/*/*.h"
    )

    add_executable(Server ${source_files})

And it totally worked.

Hide div element when screen size is smaller than a specific size

@media only screen and (max-width: 1026px) { 
  #fadeshow1 { 
    display: none; 
  } 
}

Any time the screen is less than 1026 pixels wide, anything inside the { } will apply.

Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS

Appending to 2D lists in Python

You haven't created three different empty lists. You've created one empty list, and then created a new list with three references to that same empty list. To fix the problem use this code instead:

listy = [[] for i in range(3)]

Running your example code now gives the result you probably expected:

>>> listy = [[] for i in range(3)]
>>> listy[1] = [1,2]
>>> listy
[[], [1, 2], []]
>>> listy[1].append(3)
>>> listy
[[], [1, 2, 3], []]
>>> listy[2].append(1)
>>> listy
[[], [1, 2, 3], [1]]

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

Check you index.html file. If you use external resources, that not available when you run application then you can get this error.

In my case I forgot to delete link on debugger script (weinre).

<script src="http://192.168.0.102:8080/target/target-script-min.js#anonymous"></script>

So application worked on emulator because http://192.168.0.102:8080/ was on my localhost and available for emulator.

But when I setup application on mobile phone I had same error, because 192.168.0.102 was not available from mobile network.

MySQL my.cnf file - Found option without preceding group

I had this problem when I installed MySQL 8.0.15 with the community installer. The my.ini file that came with the installer did not work correctly after it had been edited. I did a full manual install by downloading that zip folder. I was able to create my own my.ini file containing only the parameters that I was concerned about and it worked.

  1. download zip file from MySQL website
  2. unpack the folder into C:\program files\MySQL\MySQL8.0
  3. within the MySQL8.0 folder that you unpacked the zip folder into, create a text file and save it as my.ini
  4. include the parameters in that my.ini file that you are concerned about. so something like this(just ensure that there is already a folder created for the datadir or else initialization won't work):

    [mysqld]
    basedire=C:\program files\MySQL\MySQL8.0
    datadir=D:\MySQL\Data
    ....continue with whatever parameters you want to include
    
  5. initialize the data directory by running these two commands in the command prompt:

    cd C:\program files\MySQL\MySQL8.0\bin
    mysqld --default-file=C:\program files\MySQL\MySQL8.0\my.ini --initialize
    
  6. install the MySQL server as a service by running these two commands:

    cd C:\program files\MySQL\MySQL8.0\bin
    mysqld --install --default-file=C:\program files\MySQL\MySQL8.0\my.ini
    
  7. finally, start the server for the first time by running these two commands:

    cd C:\program files\MySQL\MySQL8.0\bin
    mysqld --console
    

Meaning of "487 Request Terminated"

The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.

15.1.2 UAS Behavior==> BYE Handling in RFC 3261

The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.

How to debug Spring Boot application with Eclipse?

This question is already answered, but i also got same issue to debug Springboot + gradle + jHipster,

Mostly Spring boot application can debug by right click and debug, but when you use gradle, having some additional environment parameter setup then it is not possible to debug directly.

To resolve this, Eclipse provided one additional features as Remote Java Application

by using this features you can debug your application.

Follow below step:

run your gradle application with ./gradlew bootRun --debug-jvm command

Now go to eclipse --> right click project and Debug configuration --> Remote Java Application.

add you host and port as localhost and port as 5005 (default for gradle debug, you can change it)

Refer for more detail and step.

Best way to format multiple 'or' conditions in an if statement (Java)

Use a collection of some sort - this will make the code more readable and hide away all those constants. A simple way would be with a list:

// Declared with constants
private static List<Integer> myConstants = new ArrayList<Integer>(){{
    add(12);
    add(16);
    add(19);
}};

// Wherever you are checking for presence of the constant
if(myConstants.contains(x)){
    // ETC
}

As Bohemian points out the list of constants can be static so it's accessible in more than one place.

For anyone interested, the list in my example is using double brace initialization. Since I ran into it recently I've found it nice for writing quick & dirty list initializations.

How to count frequency of characters in a string?

You can use a java Map and map a char to an int. You can then iterate over the characters in the string and check if they have been added to the map, if they have, you can then increment its value.

For example:

HashMap<Character, Integer> map = new HashMap<Character, Integer>();
String s = "aasjjikkk";
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    Integer val = map.get(c);
    if (val != null) {
        map.put(c, new Integer(val + 1));
    }
    else {
       map.put(c, 1);
   }
}

At the end you will have a count of all the characters you encountered and you can extract their frequencies from that.

Alternatively, you can use Bozho's solution of using a Multiset and counting the total occurences.

Hashing a file in Python

I would propose simply:

def get_digest(file_path):
    h = hashlib.sha256()

    with open(file_path, 'rb') as file:
        while True:
            # Reading is buffered, so we can read smaller chunks.
            chunk = file.read(h.block_size)
            if not chunk:
                break
            h.update(chunk)

    return h.hexdigest()

All other answers here seem to complicate too much. Python is already buffering when reading (in ideal manner, or you configure that buffering if you have more information about underlying storage) and so it is better to read in chunks the hash function finds ideal which makes it faster or at lest less CPU intensive to compute the hash function. So instead of disabling buffering and trying to emulate it yourself, you use Python buffering and control what you should be controlling: what the consumer of your data finds ideal, hash block size.

Regular Expression to get a string between parentheses in Javascript

var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/;
alert(rex.exec(str));

Will match the first number starting with a $ and followed by ')'. ')' will not be part of the match. The code alerts with the first match.

var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/g;
var matches = str.match(rex);
for (var i = 0; i < matches.length; i++)
{
    alert(matches[i]);
}

This code alerts with all the matches.

References:

search for "?=n" http://www.w3schools.com/jsref/jsref_obj_regexp.asp

search for "x(?=y)" https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Why does .NET foreach loop throw NullRefException when collection is null?

A foreach loop calls the GetEnumerator method.
If the collection is null, this method call results in a NullReferenceException.

It is bad practice to return a null collection; your methods should return an empty collection instead.

What's the fastest algorithm for sorting a linked list?

The question is LeetCode #148, and there are plenty of solutions offered in all major languages. Mine is as follows, but I'm wondering about the time complexity. In order to find the middle element, we traverse the complete list each time. First time n elements are iterated over, second time 2 * n/2 elements are iterated over, so on and so forth. It seems to be O(n^2) time.

def sort(linked_list: LinkedList[int]) -> LinkedList[int]:
    # Return n // 2 element
    def middle(head: LinkedList[int]) -> LinkedList[int]:
        if not head or not head.next:
            return head
        slow = head
        fast = head.next

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

        return slow

    def merge(head1: LinkedList[int], head2: LinkedList[int]) -> LinkedList[int]:
        p1 = head1
        p2 = head2
        prev = head = None

        while p1 and p2:
            smaller = p1 if p1.val < p2.val else p2
            if not head:
                head = smaller
            if prev:
                prev.next = smaller
            prev = smaller

            if smaller == p1:
                p1 = p1.next
            else:
                p2 = p2.next

        if prev:
            prev.next = p1 or p2
        else:
            head = p1 or p2

        return head

    def merge_sort(head: LinkedList[int]) -> LinkedList[int]:
        if head and head.next:
            mid = middle(head)
            mid_next = mid.next
            # Makes it easier to stop
            mid.next = None

            return merge(merge_sort(head), merge_sort(mid_next))
        else:
            return head

    return merge_sort(linked_list)

What is the size of a pointer?

To answer your other question. The size of a pointer and the size of what it points to are not related. A good analogy is to consider them like postal addresses. The size of the address of a house has no relationship to the size of the house.

Android java.exe finished with non-zero exit value 1

This solution work for me

Install Java JDK 8.

Then, go to Tools-> Options ->Tools for Apache Cordova-> Environment Variable Overrides and set the path to your JDK to "C:\Program Files\java\jdk1.8.0_121" to get Java 8 instead of Java 7.

for more info http://www.developersite.org/103-141954-android

iPhone app could not be installed at this time

This can also happen if you disable cellular data for "App Store" (for example, while on vacation) and forget to turn it back on. The solution here is to simply re-enable it in Settings -> Cellular.

When to use EntityManager.find() vs EntityManager.getReference() with JPA

Sssuming you have a parent Post entity and a child PostComment as illustrated in the following diagram:

enter image description here

If you call find when you try to set the @ManyToOne post association:

PostComment comment = new PostComment();
comment.setReview("Just awesome!");
 
Post post = entityManager.find(Post.class, 1L);
comment.setPost(post);
 
entityManager.persist(comment);

Hibernate will execute the following statements:

SELECT p.id AS id1_0_0_,
       p.title AS title2_0_0_
FROM   post p
WHERE p.id = 1
 
INSERT INTO post_comment (post_id, review, id)
VALUES (1, 'Just awesome!', 1)

The SELECT query is useless this time because we don’t need the Post entity to be fetched. We only want to set the underlying post_id Foreign Key column.

Now, if you use getReference instead:

PostComment comment = new PostComment();
comment.setReview("Just awesome!");
 
Post post = entityManager.getReference(Post.class, 1L);
comment.setPost(post);
 
entityManager.persist(comment);

This time, Hibernate will issue just the INSERT statement:

INSERT INTO post_comment (post_id, review, id)
VALUES (1, 'Just awesome!', 1)

Unlike find, the getReference only returns an entity Proxy which only has the identifier set. If you access the Proxy, the associated SQL statement will be triggered as long as the EntityManager is still open.

However, in this case, we don’t need to access the entity Proxy. We only want to propagate the Foreign Key to the underlying table record so loading a Proxy is sufficient for this use case.

When loading a Proxy, you need to be aware that a LazyInitializationException can be thrown if you try to access the Proxy reference after the EntityManager is closed.

What techniques can be used to speed up C++ compilation times?

Dynamic linking (.so) can be much much faster than static linking (.a). Especially when you have a slow network drive. This is since you have all of the code in the .a file which needs to be processed and written out. In addition, a much larger executable file needs to be written out to the disk.

Bundle ID Suffix? What is it?

The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.

It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.

An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:

com.awesomeapps.thebestapp

In this case the suffix is thebestapp.

Simple JavaScript login form validation

  1. The input tag doesn't have onsubmit handler. Instead, you should put your onsubmit handler on actual form tag, like this:

    <form name="loginform" onsubmit="validateForm()" method="post">

    Here are some useful links:

  2. For the form tag you can specify the request method, GET or POST. By default, the method is GET. One of the differences between them is that in case of GET method, the parameters are appended to the URL (just what you have shown), while in case of POST method there are not shown in URL.

    You can read more about the differences here.

UPDATE:

You should return the function call and also you can specify the URL in action attribute of form tag. So here is the updated code:

<form name="loginform" onSubmit="return validateForm();" action="main.html" method="post">
    <label>User name</label>
    <input type="text" name="usr" placeholder="username"> 
    <label>Password</label>
    <input type="password" name="pword" placeholder="password">
    <input type="submit" value="Login"/>
</form>

<script>
    function validateForm() {
        var un = document.loginform.usr.value;
        var pw = document.loginform.pword.value;
        var username = "username"; 
        var password = "password";
        if ((un == username) && (pw == password)) {
            return true;
        }
        else {
            alert ("Login was unsuccessful, please check your username and password");
            return false;
        }
  }
</script>

Quoting backslashes in Python string literals

You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)

>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

Incidentally, there's another string form which might be a bit clearer:

>>> print(r'baz "\"')
baz "\"

Creating and writing lines to a file

' Create The Object
Set FSO = CreateObject("Scripting.FileSystemObject")

' How To Write To A File
Set File = FSO.CreateTextFile("C:\foo\bar.txt",True)
File.Write "Example String"
File.Close

' How To Read From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Do Until File.AtEndOfStream
    Line = File.ReadLine
    WScript.Echo(Line)
Loop
File.Close

' Another Method For Reading From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Set Text = File.ReadAll
WScript.Echo(Text)
File.Close

How do I merge dictionaries together in Python?

I believe that, as stated above, using d2.update(d1) is the best approach and that you can also copy d2 first if you still need it.

Although, I want to point out that dict(d1, **d2) is actually a bad way to merge dictionnaries in general since keyword arguments need to be strings, thus it will fail if you have a dict such as:

{
  1: 'foo',
  2: 'bar'
}

How to create threads in nodejs

There is also at least one library for doing native threading from within Node.js: node-webworker-threads

https://github.com/audreyt/node-webworker-threads

This basically implements the Web Worker browser API for node.js.

How to call a Web Service Method?

write return(secondmethod) inside of the first method

enter image description here

super() in Java

Constructors
In a constructor, you can use it without a dot to call another constructor. super calls a constructor in the superclass; this calls a constructor in this class :

public MyClass(int a) {
  this(a, 5);  // Here, I call another one of this class's constructors.
}

public MyClass(int a, int b) {
  super(a, b);  // Then, I call one of the superclass's constructors.
}

super is useful if the superclass needs to initialize itself. this is useful to allow you to write all the hard initialization code only once in one of the constructors and to call it from all the other, much easier-to-write constructors.

Methods
In any method, you can use it with a dot to call another method. super.method() calls a method in the superclass; this.method() calls a method in this class :

public String toString() {
  int    hp   = this.hitpoints();  // Calls the hitpoints method in this class
                                   //   for this object.
  String name = super.name();      // Calls the name method in the superclass
                                   //   for this object.

  return "[" + name + ": " + hp + " HP]";
}

super is useful in a certain scenario: if your class has the same method as your superclass, Java will assume you want the one in your class; super allows you to ask for the superclass's method instead. this is useful only as a way to make your code more readable.

Clang vs GCC - which produces faster binaries?

Phoronix did some benchmarks about this, but it is about a snapshot version of Clang/LLVM from a few months back. The results being that things were more-or-less a push; neither GCC nor Clang is definitively better in all cases.

Since you'd use the latest Clang, it's maybe a little less relevant. Then again, GCC 4.6 is slated to have some major optimizations for Core 2 and i7, apparently.

I figure Clang's faster compilation speed will be nicer for original developers, and then when you push the code out into the world, Linux distro/BSD/etc. end-users will use GCC for the faster binaries.

JavaScript math, round to two decimal places

If you use a unary plus to convert a string to a number as documented on MDN.

For example:+discount.toFixed(2)

Getting value of HTML text input

See my jsFiddle here: http://jsfiddle.net/fuDBL/

Whenever you change the email field, the link is updated automatically. This requires a small amount of jQuery. So now your form will work as needed, but your link will be updated dynamically so that when someone clicks on it, it contains what they entered in the email field. You should validate the input on the receiving page.

$('input[name="email"]').change(function(){
  $('#regLink').attr('href')+$('input[name="email"]').val();
});

Return value in a Bash function

The problem with other answers is they either use a global, which can be overwritten when several functions are in a call chain, or echo which means your function cannot output diagnostic info (you will forget your function does this and the "result", i.e. return value, will contain more info than your caller expects, leading to weird bug), or eval which is way too heavy and hacky.

The proper way to do this is to put the top level stuff in a function and use a local with bash's dynamic scoping rule. Example:

func1() 
{
    ret_val=hi
}

func2()
{
    ret_val=bye
}

func3()
{
    local ret_val=nothing
    echo $ret_val
    func1
    echo $ret_val
    func2
    echo $ret_val
}

func3

This outputs

nothing
hi
bye

Dynamic scoping means that ret_val points to a different object depending on the caller! This is different from lexical scoping, which is what most programming languages use. This is actually a documented feature, just easy to miss, and not very well explained, here is the documentation for it (emphasis is mine):

Variables local to the function may be declared with the local builtin. These variables are visible only to the function and the commands it invokes.

For someone with a C/C++/Python/Java/C#/javascript background, this is probably the biggest hurdle: functions in bash are not functions, they are commands, and behave as such: they can output to stdout/stderr, they can pipe in/out, they can return an exit code. Basically there is no difference between defining a command in a script and creating an executable that can be called from the command line.

So instead of writing your script like this:

top-level code 
bunch of functions
more top-level code

write it like this:

# define your main, containing all top-level code
main() 
bunch of functions
# call main
main  

where main() declares ret_val as local and all other functions return values via ret_val.

See also the following Unix & Linux question: Scope of Local Variables in Shell Functions.

Another, perhaps even better solution depending on situation, is the one posted by ya.teck which uses local -n.

Avoid Adding duplicate elements to a List C#

If you want to save distinct values into a collection you could try HashSet Class. It will automatically remove the duplicate values and save your coding time. :)

How do I convert number to string and pass it as argument to Execute Process Task?

Expression: "Total Count: " + (DT_WSTR, 5)@[User::Cnt]

What is an Android PendingIntent?

Why PendingIntent is required ? I was thinking like

  1. Why the receiving application itself cannot create the Intent or
  2. Why we cannot use a simple Intent for the same purpose.

E.g.Intent bluetoothIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

If I send bluetoothIntent to another application, which doesn't have permission android.permission.BLUETOOTH_ADMIN, that receiving application cannot enable Bluetooth with startActivity(bluetoothIntent).

The limitation is overcome using PendingIntent. With PendingIntent the receiving application, doesn't need to have android.permission.BLUETOOTH_ADMIN for enabling Bluetooth. Source.

How to remove the last character from a bash grep output

I'd use head --bytes -1, or head -c-1 for short.

COMPANY_NAME=`cat file.txt | grep "company_name" | cut -d '=' -f 2 | head --bytes -1`

head outputs only the beginning of a stream or file. Typically it counts lines, but it can be made to count characters/bytes instead. head --bytes 10 will output the first ten characters, but head --bytes -10 will output everything except the last ten.

NB: you may have issues if the final character is multi-byte, but a semi-colon isn't

I'd recommend this solution over sed or cut because

  • It's exactly what head was designed to do, thus less command-line options and an easier-to-read command
  • It saves you having to think about regular expressions, which are cool/powerful but often overkill
  • It saves your machine having to think about regular expressions, so will be imperceptibly faster

Best way to copy a database (SQL Server 2008)

Easiest way is actually a script.

Run this on production:

USE MASTER;

BACKUP DATABASE [MyDatabase]
TO DISK = 'C:\temp\MyDatabase1.bak' -- some writeable folder. 
WITH COPY_ONLY

This one command makes a complete backup copy of the database onto a single file, without interfering with production availability or backup schedule, etc.

To restore, just run this on your dev or test SQL Server:

USE MASTER;

RESTORE DATABASE [MyDatabase]
FROM DISK = 'C:\temp\MyDatabase1.bak'
WITH
MOVE 'MyDatabase'   TO 'C:\Sql\MyDatabase.mdf', -- or wherever these live on target
MOVE 'MyDatabase_log'   TO 'C:\Sql\MyDatabase_log.ldf',
REPLACE, RECOVERY

Then save these scripts on each server. One-click convenience.

Edit:
if you get an error when restoring that the logical names don't match, you can get them like this:

RESTORE FILELISTONLY
FROM disk = 'C:\temp\MyDatabaseName1.bak'

If you use SQL Server logins (not windows authentication) you can run this after restoring each time (on the dev/test machine):

use MyDatabaseName;
sp_change_users_login 'Auto_Fix', 'userloginname', null, 'userpassword';

CSS table layout: why does table-row not accept a margin?

There is a pretty simple fix for this, the border-spacing and border-collapse CSS attributes work on display: table.

You can use the following to get padding/margins in your cells.

_x000D_
_x000D_
.container {_x000D_
  width: 850px;_x000D_
  padding: 0;_x000D_
  display: table;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 15px;_x000D_
}_x000D_
_x000D_
.row {_x000D_
  display: table-row;_x000D_
}_x000D_
_x000D_
.home_1 {_x000D_
  width: 64px;_x000D_
  height: 64px;_x000D_
  padding-right: 20px;_x000D_
  margin-right: 10px;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_2 {_x000D_
  width: 350px;_x000D_
  height: 64px;_x000D_
  padding: 0px;_x000D_
  vertical-align: middle;_x000D_
  font-size: 150%;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_3 {_x000D_
  width: 64px;_x000D_
  height: 64px;_x000D_
  padding-right: 20px;_x000D_
  margin-right: 10px;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_4 {_x000D_
  width: 350px;_x000D_
  height: 64px;_x000D_
  padding: 0px;_x000D_
  vertical-align: middle;_x000D_
  font-size: 150%;_x000D_
  display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="home_1">Foo</div>_x000D_
    <div class="home_2">Foo</div>_x000D_
    <div class="home_3">Foo</div>_x000D_
    <div class="home_4">Foo</div>_x000D_
  </div>_x000D_
_x000D_
  <div class="row">_x000D_
    <div class="home_1">Foo</div>_x000D_
    <div class="home_2">Foo</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note that you have to have

border-collapse: separate;

Otherwise it will not work.

Where to place $PATH variable assertions in zsh?

tl;dr version: use ~/.zshrc

And read the man page to understand the differences between:

~/.zshrc, ~/.zshenv and ~/.zprofile.


Regarding my comment

In my comment attached to the answer kev gave, I said:

This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh. However, this only occurs if zsh is "invoked as sh or ksh"; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].

The ArchWiki ZSH link says:

At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).



To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from ~/.zshrc, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc is read for interactive shells, which may or may not suit your needs - if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then ~/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There's a bunch of files read on startup (check the linked man pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv not existing - if you need it, make it, and it will be read.

.bashrc and .bash_profile are not read by zsh, unless you explicitly source them from ~/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

git discard all changes and pull from upstream

You can do it in a single command:

git fetch --all && git reset --hard origin/master

Or in a pair of commands:

git fetch --all
git reset --hard origin/master

Note than you will lose ALL your local changes

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

Not sure if I'm too late, but in case someone has still the error after an update of ConstraintLayout and Solver over the SDK Tools, maybe this solution could help: Error:(30, 13) Failed to resolve: com.android.support.constraint:constraint-layout:1.0.0-alpha4

How do I calculate the normal vector of a line segment?

This question has been posted long time ago, but I found an alternative way to answer it. So I decided to share it here.
Firstly, one must know that: if two vectors are perpendicular, their dot product equals zero.
The normal vector (x',y') is perpendicular to the line connecting (x1,y1) and (x2,y2). This line has direction (x2-x1,y2-y1), or (dx,dy).
So,

(x',y').(dx,dy) = 0
x'.dx + y'.dy = 0

The are plenty of pairs (x',y') that satisfy the above equation. But the best pair that ALWAYS satisfies is either (dy,-dx) or (-dy,dx)

Can't install any packages in Node.js using "npm install"

If you happened to run npm install command on Windows, first make sure you open your command prompt with Administration Privileges. That's what solved the issue for me.

scp or sftp copy multiple files with single command

The simplest way is

local$ scp remote:{A/1,A/2,B/3,C/4}.txt ./

So {.. } list can include directories (A,B and C here are directories; "1.txt" and "2.txt" are file names in those directories).

Although it would copy all these four files into one local directory - not sure if that's what you wanted.

In the above case you will end up remote files A/1.txt, A/2.txt, B/3.txt and C/4.txt copied over to a single local directory, with file names ./1.txt, ./2.txt, ./3.txt and ./4.txt

Is there any way to delete local commits in Mercurial?

Enable the "strip" extension and type the following:

hg strip #changeset# --keep

Where #changeset# is the hash for the changeset you want to remove. This will remove the said changeset including changesets that descend from it and will leave your working directory untouched. If you wish to also revert your committed code changes remove the --keep option.

For more information, check the Strip Extension.

If you get "unkown command 'strip'" you may need to enable it. To do so find the .hgrc or Mercurial.ini file and add the following to it:

[extensions]
strip =

Note that (as Juozas mentioned in his comment) having multiple heads is normal workflow in Mercurial. You should not use the strip command to battle that. Instead, you should merge your head with the incoming head, resolve any conflicts, test, and then push.

The strip command is useful when you really want to get rid of changesets that pollute the branch. In fact, if you're in this question's situation and you want to completely remove all "draft" change sets permanently, check out the top answer, which basically suggests doing:

hg strip 'roots(outgoing())'

How to convert from Hex to ASCII in JavaScript?

Another way to do it (if you use Node.js):

var input  = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output);  // Result: 32343630 -> 2460

How do I install cURL on cygwin?

I just ran into this.

If you're not seeing curl in the list (see ibaralf's screenshot), then you may have out-of-date cygwin sources. In one of the screens in cygwin's setup.exe wizard, you have the option to "Install from Internet" or "Install from Local Directory". If you have the "Install from Local Directory" option enabled, then you may not see curl in the list. Switch to "Install from Internet" and select a mirror and then you should see curl.

PostgreSQL Error: Relation already exists

I finally discover the error. The problem is that the primary key constraint name is equal the table name. I don know how postgres represents constraints, but I think the error "Relation already exists" was being triggered during the creation of the primary key constraint because the table was already declared. But because of this error, the table wasnt created at the end.

How to convert text to binary code in JavaScript?

var PADDING = "00000000"

var string = "TEST"
var resultArray = []

for (var i = 0; i < string.length; i++) {
  var compact = string.charCodeAt(i).toString(2)
  var padded  = compact.substring(0, PADDING.length - compact.length) + compact

  resultArray.push(padded)
}

console.log(resultArray.join(" "))

How to get height of entire document with JavaScript?

The "jQuery method" of determining the document size - query everything, take the highest value, and hope for the best - works in most cases, but not in all of them .

If you really need bullet-proof results for the document size, I'd suggest you use my jQuery.documentSize plugin. Unlike the other methods, it actually tests and evaluates browser behaviour when it is loaded and, based on the result, queries the right property from there on out.

The impact of this one-time test on performance is minimal, and the plugin returns the right results in even the weirdest scenarios - not because I say so, but because a massive, auto-generated test suite actually verifies that it does.

Because the plugin is written in vanilla Javascript, you can use it without jQuery, too.

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

The 100% working solution

public static function rmdir_recursive($directory, $delete_parent = null)
  {
    $files = glob($directory . '/{,.}[!.,!..]*',GLOB_MARK|GLOB_BRACE);
    foreach ($files as $file) {
      if (is_dir($file)) {
        self::rmdir_recursive($file, 1);
      } else {
        unlink($file);
      }
    }
    if ($delete_parent) {
      rmdir($directory);
    }
  }

JavaScript property access: dot notation vs. brackets?

Let me add some more use case of the square-bracket notation. If you want to access a property say x-proxy in a object, then - will be interpreted wrongly. Their are some other cases too like space, dot, etc., where dot operation will not help you. Also if u have the key in a variable then only way to access the value of the key in a object is by bracket notation. Hope you get some more context.

Trying Gradle build - "Task 'build' not found in root project"

You didn't do what you're being asked to do.

What is asked:

I have to execute ../gradlew build

What you do

cd ..
gradlew build

That's not the same thing.

The first one will use the gradlew command found in the .. directory (mdeinum...), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore.

The second one will execute the gradlew command found in the current directory (mdeinum...), and look for the build file to execute in the current directory, which is mdeinum....

So the build file executed is not the same.

Javascript: How to remove the last character from a div or a string?

Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html. On keyup

$("#div").html($("#input").val());

How to select multiple files with <input type="file">?

You can do it now with HTML5

In essence you use the multiple attribute on the file input.

<input type='file' multiple>

Passing Javascript variable to <a href >

If you use internationalization (i18n), and after switch to another language, something like ?locale=fror ?fr might be added at the end of the url. But when you go to another page on click event, translation switch wont be stable.

For this kind of cases a DOM click event handler function must be produced to handle all the a.href attributes by storing the switch state as a variable and add it to all a tags’ tail.

SQL LIKE condition to check for integer?

Which one of those is indexable?

This one is definitely btree-indexable:

WHERE title >= '0' AND title < ':'

Note that ':' comes after '9' in ASCII.

How to get PID by process name?

To improve the Padraic's answer: when check_output returns a non-zero code, it raises a CalledProcessError. This happens when the process does not exists or is not running.

What I would do to catch this exception is:

#!/usr/bin/python

from subprocess import check_output, CalledProcessError

def getPIDs(process):
    try:
        pidlist = map(int, check_output(["pidof", process]).split())
    except  CalledProcessError:
        pidlist = []
    print 'list of PIDs = ' + ', '.join(str(e) for e in pidlist)

if __name__ == '__main__':
    getPIDs("chrome")

The output:

$ python pidproc.py
list of PIDS = 31840, 31841, 41942

Problems with entering Git commit message with Vim

Typically, git commit brings up an interactive editor (on Linux, and possibly Cygwin, determined by the contents of your $EDITOR environment variable) for you to edit your commit message in. When you save and exit, the commit completes.

You should make sure that the changes you are trying to commit have been added to the Git index; this determines what is committed. See http://gitref.org/basic/ for details on this.

Convert string to symbol-able in ruby

Rails got ActiveSupport::CoreExtensions::String::Inflections module that provides such methods. They're all worth looking at. For your example:

'Book Author Title'.parameterize.underscore.to_sym # :book_author_title

How do I set the value property in AngularJS' ng-options?

You can use ng-options to achieve select tag binding to value and display members

While using this data source

countries : [
              {
                 "key": 1,
                 "name": "UAE"
             },
              {
                  "key": 2,
                  "name": "India"
              },
              {
                  "key": 3,
                  "name": "OMAN"
              }
         ]

you can use the below to bind your select tag to value and name

<select name="text" ng-model="name" ng-options="c.key as c.name for c in countries"></select>

it works great

Parsing JSON from XmlHttpRequest.responseJSON

I think you have to include jQuery to use responseJSON.

Without jQuery, you could try with responseText and try like eval("("+req.responseText+")");

UPDATE:Please read the comment regarding eval, you can test with eval, but don't use it in working extension.

OR

use json_parse : it does not use eval

Javascript String to int conversion

Use parseInt():

var number = (parseInt(id.substring(indexPos)) + 1);` // creates the number that will go in the title

Random number from a range in a Bash Script

You can do this

cat /dev/urandom|od -N2 -An -i|awk -v f=2000 -v r=65000 '{printf "%i\n", f + r * $1 / 65536}'

If you need more details see Shell Script Random Number Generator.

How can I ignore a property when serializing using the DataContractSerializer?

What you are saying is in conflict with what it says in the MSDN library at this location:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx

I don't see any mention of the SP1 feature you mention.

How to add an image to an svg container using D3.js

I do not know why, but the image should not be duplicated, tripled, etc ... should remove the previous one and load it again but with another rotation data. This is my code:

data.csv enter image description here

d3.csv("data/data.csv").then(function(data){
//console.log(data);
// Clean data
formattedData = data.map(function(id){
id.rot_1 = +id.rot_1;
        id.trans_1 = +id.trans_1;
        return id;
});
// First run of the visualization
update(formattedData[0]);})

$("#play-button")
.on("click", function(){
    var button = $(this);
    if (button.text() == "Play"){
        button.text("Pause");
        interval = setInterval(step, 1000);            
    }
    else {
        button.text("Play");
        clearInterval(interval);
    }})

function step(){
// At the end of our data, loop back
time = (time < 76) ? time+1 : 0
update(formattedData[time]); }

function update(data) {
// Standard transition time for the visualization
var t = d3.transition()
    .duration(1000);

//console.log(d3.selectAll(data));    
//console.log(data)

// original
var imgs1 = g.append("image") // en vez de g es svg
.attr("xlink:href", "img/picturetest.png");

// EXIT old elements not present in new data.
imgs1.exit()
    .attr("class", "exit")
    .selectAll("svg:image")
    .remove();

//console.log(data)

// ENTER new elements present in new data.
imgs1.enter()
    .append("svg:image") // svg:image
    //.attr("xlink:href", "img/picturetest.png")
    .attr("class", "enter")
    .merge(imgs1)
    .transition(t)
        .attr("x", 0) // 150
        .attr("y", 0) // 80
        .attr("width", 200)
        .attr("height", 200)
        .attr("transform", "rotate("+data.rot_1+") translate("+data.trans_1+")" ); }`

Extract string between two strings in java

Your pattern is fine. But you shouldn't be split()ting it away, you should find() it. Following code gives the output you are looking for:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

How to set the height of an input (text) field in CSS?

You use this style code

.heighttext{
 float:right;
 height:30px;
 width:70px;
 }

Python requests - print entire http request (raw)?

Note: this answer is outdated. Newer versions of requests support getting the request content directly, as AntonioHerraizS's answer documents.

It's not possible to get the true raw content of the request out of requests, since it only deals with higher level objects, such as headers and method type. requests uses urllib3 to send requests, but urllib3 also doesn't deal with raw data - it uses httplib. Here's a representative stack trace of a request:

-> r= requests.get("http://google.com")
  /usr/local/lib/python2.7/dist-packages/requests/api.py(55)get()
-> return request('get', url, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/api.py(44)request()
-> return session.request(method=method, url=url, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/sessions.py(382)request()
-> resp = self.send(prep, **send_kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/sessions.py(485)send()
-> r = adapter.send(request, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/adapters.py(324)send()
-> timeout=timeout
  /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py(478)urlopen()
-> body=body, headers=headers)
  /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py(285)_make_request()
-> conn.request(method, url, **httplib_request_kw)
  /usr/lib/python2.7/httplib.py(958)request()
-> self._send_request(method, url, body, headers)

Inside the httplib machinery, we can see HTTPConnection._send_request indirectly uses HTTPConnection._send_output, which finally creates the raw request and body (if it exists), and uses HTTPConnection.send to send them separately. send finally reaches the socket.

Since there's no hooks for doing what you want, as a last resort you can monkey patch httplib to get the content. It's a fragile solution, and you may need to adapt it if httplib is changed. If you intend to distribute software using this solution, you may want to consider packaging httplib instead of using the system's, which is easy, since it's a pure python module.

Alas, without further ado, the solution:

import requests
import httplib

def patch_send():
    old_send= httplib.HTTPConnection.send
    def new_send( self, data ):
        print data
        return old_send(self, data) #return is not necessary, but never hurts, in case the library is changed
    httplib.HTTPConnection.send= new_send

patch_send()
requests.get("http://www.python.org")

which yields the output:

GET / HTTP/1.1
Host: www.python.org
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/2.1.0 CPython/2.7.3 Linux/3.2.0-23-generic-pae

How to get images in Bootstrap's card to be the same height/width?

Try this in your css:

.card-img-top {
    width: 100%;
    height: 15vw;
    object-fit: cover;
}

Adjust the height vw as you see fit. The object-fit: cover enables zoom instead of image stretching.

How to validate domain credentials?

C# in .NET 3.5 using System.DirectoryServices.AccountManagement.

 bool valid = false;
 using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
 {
     valid = context.ValidateCredentials( username, password );
 }

This will validate against the current domain. Check out the parameterized PrincipalContext constructor for other options.

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Use case/esac to test:

case "$var" in
  "") echo "zero length";;
esac

Calling jQuery method from onClick attribute in HTML

I don't think there's any reason to add this function to JQuery's namespace. Why not just define the method by itself:

function showMessage(msg) {
   alert(msg);
};

<input type="button" value="ahaha" onclick="showMessage('msg');" />

UPDATE: With a small change to how your method is defined I can get it to work:

<html>
<head>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
 <script language="javascript">
    // define the function within the global scope
    $.fn.MessageBox = function(msg) {
        alert(msg);
    };

    // or, if you want to encapsulate variables within the plugin
    (function($) {
        $.fn.MessageBoxScoped = function(msg) {
            alert(msg);
        };
    })(jQuery); //<-- make sure you pass jQuery into the $ parameter
 </script>
</head>
<body>
 <div class="Title">Welcome!</div>
 <input type="button" value="ahaha" id="test" onClick="$(this).MessageBox('msg');" />
</body>
</html>

node.js hash string?

Here you can benchmark all supported hashes on your hardware, supported by your version of node.js. Some are cryptographic, and some is just for a checksum. Its calculating "Hello World" 1 million times for each algorithm. It may take around 1-15 seconds for each algorithm (Tested on the Standard Google Computing Engine with Node.js 4.2.2).

for(var i1=0;i1<crypto.getHashes().length;i1++){
  var Algh=crypto.getHashes()[i1];
  console.time(Algh);
  for(var i2=0;i2<1000000;i2++){
    crypto.createHash(Algh).update("Hello World").digest("hex");
  }
  console.timeEnd(Algh);  
}

Result:
DSA: 1992ms
DSA-SHA: 1960ms
DSA-SHA1: 2062ms
DSA-SHA1-old: 2124ms
RSA-MD4: 1893ms
RSA-MD5: 1982ms
RSA-MDC2: 2797ms
RSA-RIPEMD160: 2101ms
RSA-SHA: 1948ms
RSA-SHA1: 1908ms
RSA-SHA1-2: 2042ms
RSA-SHA224: 2176ms
RSA-SHA256: 2158ms
RSA-SHA384: 2290ms
RSA-SHA512: 2357ms
dsaEncryption: 1936ms
dsaWithSHA: 1910ms
dsaWithSHA1: 1926ms
dss1: 1928ms
ecdsa-with-SHA1: 1880ms
md4: 1833ms
md4WithRSAEncryption: 1925ms
md5: 1863ms
md5WithRSAEncryption: 1923ms
mdc2: 2729ms
mdc2WithRSA: 2890ms
ripemd: 2101ms
ripemd160: 2153ms
ripemd160WithRSA: 2210ms
rmd160: 2146ms
sha: 1929ms
sha1: 1880ms
sha1WithRSAEncryption: 1957ms
sha224: 2121ms
sha224WithRSAEncryption: 2290ms
sha256: 2134ms
sha256WithRSAEncryption: 2190ms
sha384: 2181ms
sha384WithRSAEncryption: 2343ms
sha512: 2371ms
sha512WithRSAEncryption: 2434ms
shaWithRSAEncryption: 1966ms
ssl2-md5: 1853ms
ssl3-md5: 1868ms
ssl3-sha1: 1971ms
whirlpool: 2578ms

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

C# List<string> to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

How do I make HttpURLConnection use a proxy?

This is fairly easy to answer from the internet. Set system properties http.proxyHost and http.proxyPort. You can do this with System.setProperty(), or from the command line with the -D syntax.

javax.faces.application.ViewExpiredException: View could not be restored

I was getting this error : javax.faces.application.ViewExpiredException.When I using different requests, I found those having same JsessionId, even after restarting the server. So this is due to the browser cache. Just close the browser and try, it will work.

addClass and removeClass in jQuery - not removing class

I think that the problem is in the nesting of the elements. Once you attach an event to the outer element the clicks on the inner elements are actually firing the same click event for the outer element. So, you actually never go to the second state. What you can do is to check the clicked element. And if it is the close button then to avoid the class changing. Here is my solution:

var element = $(".clickable");
var closeButton = element.find(".close_button");
var onElementClick = function(e) {
    if(e.target !== closeButton[0]) {
        element.removeClass("spot").addClass("grown");
        element.off("click");
        closeButton.on("click", onCloseClick);
    }
}
var onCloseClick = function() {
    element.removeClass("grown").addClass("spot");
    closeButton.off("click");
    element.on("click", onElementClick);
}
element.on("click", onElementClick);

In addition I'm adding and removing event handlers.

JSFiddle -> http://jsfiddle.net/zmw9E/1/

Proper way to assert type of variable in Python

The isinstance built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:

def my_print(text, begin, end):
    "Print 'text' in UPPER between 'begin' and 'end' in lower"
    try:
      print begin.lower() + text.upper() + end.lower()
    except (AttributeError, TypeError):
      raise AssertionError('Input variables should be strings')

This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)

How to get the date from the DatePicker widget in Android?

If you are using Kotlin, you can define an extension function for DatePicker:

fun DatePicker.getDate(): Date {
    val calendar = Calendar.getInstance()
    calendar.set(year, month, dayOfMonth)
    return calendar.time
}

Then, it's just: datePicker.getDate(). As if it had always existed.

How to read a list of files from a folder using PHP?

If you have problems with accessing to the path, maybe you need to put this:

$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/cv/"; 

// Open the folder
 $dir_handle = @opendir($root . $path) or die("Unable to open $path");

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

First up, you seem to be mixing table variables and tables.

Either way, You can't pass in the table's name like that. You would have to use dynamic TSQL to do that.

If you just want to declare a table variable:

CREATE PROC sp_createATable 
  @name        VARCHAR(10), 
  @properties  VARCHAR(500) 
AS 
  declare @tablename TABLE
  ( 
    id  CHAR(10)  PRIMARY KEY 
  ); 

The fact that you want to create a stored procedure to dynamically create tables might suggest your design is wrong.

Group by with union mysql select query

select sum(qty), name
from (
    select count(m.owner_id) as qty, o.name
    from transport t,owner o,motorbike m
    where t.type='motobike' and o.owner_id=m.owner_id
        and t.type_id=m.motorbike_id
    group by m.owner_id

    union all

    select count(c.owner_id) as qty, o.name,
    from transport t,owner o,car c
    where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
    group by c.owner_id
) t
group by name

How to create a Jar file in Netbeans

I also tried to make an executable jar file that I could run with the following command:

java -jar <jarfile>

After some searching I found the following link:

Packaging and Deploying Desktop Java Applications

I set the project's main class:

  1. Right-click the project's node and choose Properties
  2. Select the Run panel and enter the main class in the Main Class field
  3. Click OK to close the Project Properties dialog box
  4. Clean and build project

Then in the fodler dist the newly created jar should be executable with the command I mentioned above.

Is Java "pass-by-reference" or "pass-by-value"?

Java is only passed by value. there is no pass by reference, for example, you can see the following example.

package com.asok.cop.example.task;
public class Example {
    int data = 50;

    void change(int data) {
        data = data + 100;// changes will be in the local variable 
        System.out.println("after add " + data);
        }

    public static void main(String args[]) {
        Example op = new Example();
        System.out.println("before change " + op.data);
        op.change(500);
        System.out.println("after change " + op.data);
    }
}

Output:

before change 50
after add 600
after change 50

as Michael says in the comments:

objects are still passed by value even though operations on them behave like pass-by-reference. Consider void changePerson(Person person){ person = new Person(); } the callers reference to the person object will remain unchanged. Objects themselves are passed by value but their members can be affected by changes. To be true pass-by-reference, we would have to be able to reassign the argument to a new object and have the change be reflected in the caller.

How to make a <svg> element expand or contract to its parent container?

For your iphone You could use in your head balise :

"width=device-width"

Is there a "do ... until" in Python?

No there isn't. Instead use a while loop such as:

while 1:
 ...statements...
  if cond:
    break

What is the C# equivalent of NaN or IsNumeric?

public static bool IsNumeric(string anyString)
{
    if (anyString == null)
    {
        anyString = "";
    }

    if (anyString.Length > 0)
    {
        double dummyOut = new double();
        System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US", true);
        return Double.TryParse(anyString, System.Globalization.NumberStyles.Any, cultureInfo.NumberFormat, out dummyOut);
    }
    else
    {
        return false;
    }
}

Git Cherry-pick vs Merge Workflow

Rebase and Cherry-pick is the only way you can keep clean commit history. Avoid using merge and avoid creating merge conflict. If you are using gerrit set one project to Merge if necessary and one project to cherry-pick mode and try yourself.

How do I create a circle or square with just CSS - with a hollow center?

To my knowledge there is no cross-browser compatible way to make a circle with CSS & HTML only.

For the square I guess you could make a div with a border and a z-index higher than what you are putting it over. I don't understand why you would need to do this, when you could just put a border on the image or "something" itself.

If anyone else knows how to make a circle that is cross browser compatible with CSS & HTML only, I would love to hear about it!

@Caspar Kleijne border-radius does not work in IE8 or below, not sure about 9.

Installing Python 3 on RHEL

Here are the steps i followed to install Python3:

yum install wget
wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz  
sudo tar xvf Python-3.*   
cd Python-3.* 
sudo ./configure --prefix=/opt/python3    
sudo make   
sudo make install   
sudo ln -s /opt/python3/bin/python3 /usr/bin/python3

$ /usr/bin/python3    
Python 3.6.0

Promise Error: Objects are not valid as a React child

You can't do this: {this.state.arrayFromJson} As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map to do that.

I am pasting a link from where you can learn how to render elements from an array with React.

http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/

Hope it helps!

Creating multiple objects with different names in a loop to store in an array list

You can use this code...

public class Main {

    public static void main(String args[]) {
        String[] names = {"First", "Second", "Third"};//You Can Add More Names
        double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
        List<Customer> customers = new ArrayList<Customer>();
        int i = 0;
        while (i < names.length) {
            customers.add(new Customer(names[i], amount[i]));
            i++;
        }
    }
}

What is the Java equivalent of PHP var_dump?

Just to addup on the Field solution (the setAccessible) so that you can access private variable of an object:

public static void dd(Object obj) throws IllegalArgumentException, IllegalAccessException {
    Field[] fields = obj.getClass().getDeclaredFields();
    for (int i=0; i<fields.length; i++)
    {
        fields[i].setAccessible(true);
        System.out.println(fields[i].getName() + " - " + fields[i].get(obj));
    } 

}

How to split data into training/testing sets using sample function

Beware of sample for splitting if you look for reproducible results. If your data changes even slightly, the split will vary even if you use set.seed. For example, imagine the sorted list of IDs in you data is all the numbers between 1 and 10. If you just dropped one observation, say 4, sampling by location would yield a different results because now 5 to 10 all moved places.

An alternative method is to use a hash function to map IDs into some pseudo random numbers and then sample on the mod of these numbers. This sample is more stable because assignment is now determined by the hash of each observation, and not by its relative position.

For example:

require(openssl)  # for md5
require(data.table)  # for the demo data

set.seed(1)  # this won't help `sample`

population <- as.character(1e5:(1e6-1))  # some made up ID names

N <- 1e4  # sample size

sample1 <- data.table(id = sort(sample(population, N)))  # randomly sample N ids
sample2 <- sample1[-sample(N, 1)]  # randomly drop one observation from sample1

# samples are all but identical
sample1
sample2
nrow(merge(sample1, sample2))

[1] 9999

# row splitting yields very different test sets, even though we've set the seed
test <- sample(N-1, N/2, replace = F)

test1 <- sample1[test, .(id)]
test2 <- sample2[test, .(id)]
nrow(test1)

[1] 5000

nrow(merge(test1, test2))

[1] 2653

# to fix that, we can use some hash function to sample on the last digit

md5_bit_mod <- function(x, m = 2L) {
  # Inputs: 
  #  x: a character vector of ids
  #  m: the modulo divisor (modify for split proportions other than 50:50)
  # Output: remainders from dividing the first digit of the md5 hash of x by m
  as.integer(as.hexmode(substr(openssl::md5(x), 1, 1)) %% m)
}

# hash splitting preserves the similarity, because the assignment of test/train 
# is determined by the hash of each obs., and not by its relative location in the data
# which may change 
test1a <- sample1[md5_bit_mod(id) == 0L, .(id)]
test2a <- sample2[md5_bit_mod(id) == 0L, .(id)]
nrow(merge(test1a, test2a))

[1] 5057

nrow(test1a)

[1] 5057

sample size is not exactly 5000 because assignment is probabilistic, but it shouldn't be a problem in large samples thanks to the law of large numbers.

See also: http://blog.richardweiss.org/2016/12/25/hash-splits.html and https://crypto.stackexchange.com/questions/20742/statistical-properties-of-hash-functions-when-calculating-modulo

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

Total width of element (including padding and border) in jQuery

$(document).ready(function(){     
$("div.width").append($("div.width").width()+" px");
$("div.innerWidth").append($("div.innerWidth").innerWidth()+" px");   
$("div.outerWidth").append($("div.outerWidth").outerWidth()+" px");         
});


<div class="width">Width of this div container without including padding is: </div>  
<div class="innerWidth">width of this div container including padding is: </div> 
<div class="outerWidth">width of this div container including padding and margin is:     </div>

How to prevent line-break in a column of a table cell (not a single cell)?

Put non-breaking spaces in your text instead of normal spaces. On Ubuntu I do this with (Compose Key)-space-space.

How can I pass parameters to a partial view in mvc 4

One of The Shortest method i found for single value while i was searching for myself, is just passing single string and setting string as model in view like this.

In your Partial calling side

@Html.Partial("ParitalAction", "String data to pass to partial")

And then binding the model with Partial View like this

@model string

and the using its value in Partial View like this

@Model

You can also play with other datatypes like array, int or more complex data types like IDictionary or something else.

Hope it helps,

Fragments within Fragments

I have an application that I am developing that is laid out similar with Tabs in the Action Bar that launches fragments, some of these Fragments have multiple embedded Fragments within them.

I was getting the same error when I tried to run the application. It seems like if you instantiate the Fragments within the xml layout after a tab was unselected and then reselected I would get the inflator error.

I solved this replacing all the fragments in xml with Linearlayouts and then useing a Fragment manager/ fragment transaction to instantiate the fragments everything seems to working correctly at least on a test level right now.

I hope this helps you out.

ImportError: no module named win32api

I had both pywin32 and pipywin32 installed like suggested in previous answer, but I still did not have a folder ${PYTHON_HOME}\Lib\site-packages\win32. This always lead to errors when trying import win32api.

The simple solution was to uninstall both packages and reinstall pywin32:

pip uninstall pipywin32
pip uninstall pywin32
pip install pywin32

Then restart Python (and Jupyter). Now, the win32 folder is there and the import works fine. Problem solved.

How to read the last row with SQL Server

SELECT * from Employees where [Employee ID] = ALL (SELECT MAX([Employee ID]) from Employees)

Error: unable to verify the first certificate in nodejs

Another dirty hack, which will make all your requests insecure:

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0

is there any way to force copy? copy without overwrite prompt, using windows?

MOVE /-Y Source Destination

Note:/-y will make the announcement of yes/no for overwrite

Angular/RxJs When should I unsubscribe from `Subscription`

Following the answer by @seangwright, I've written an abstract class that handles "infinite" observables' subscriptions in components:

import { OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import { PartialObserver } from 'rxjs/Observer';

export abstract class InfiniteSubscriberComponent implements OnDestroy {
  private onDestroySource: Subject<any> = new Subject();

  constructor() {}

  subscribe(observable: Observable<any>): Subscription;

  subscribe(
    observable: Observable<any>,
    observer: PartialObserver<any>
  ): Subscription;

  subscribe(
    observable: Observable<any>,
    next?: (value: any) => void,
    error?: (error: any) => void,
    complete?: () => void
  ): Subscription;

  subscribe(observable: Observable<any>, ...subscribeArgs): Subscription {
    return observable
      .takeUntil(this.onDestroySource)
      .subscribe(...subscribeArgs);
  }

  ngOnDestroy() {
    this.onDestroySource.next();
    this.onDestroySource.complete();
  }
}

To use it, just extend it in your angular component and call the subscribe() method as follows:

this.subscribe(someObservable, data => doSomething());

It also accepts the error and complete callbacks as usual, an observer object, or not callbacks at all. Remember to call super.ngOnDestroy() if you are also implementing that method in the child component.

Find here an additional reference by Ben Lesh: RxJS: Don’t Unsubscribe.

How to check if a file exists from inside a batch file

Try something like the following example, quoted from the output of IF /? on Windows XP:

IF EXIST filename. (
    del filename.
) ELSE (
    echo filename. missing.
)

You can also check for a missing file with IF NOT EXIST.

The IF command is quite powerful. The output of IF /? will reward careful reading. For that matter, try the /? option on many of the other built-in commands for lots of hidden gems.  

Converting string to number in javascript/jQuery

You should just use "+" before $(this). That's going to convert the string to number, so:

var votevalue = +$(this).data('votevalue');

Oh and I recommend to use closest() method just in case :)

var votevalue = +$(this).closest('.btn-group').data('votevalue');

How to securely save username/password (local)?

I wanted to encrypt and decrypt the string as a readable string.

Here is a very simple quick example in C# Visual Studio 2019 WinForms based on the answer from @Pradip.

Right click project > properties > settings > Create a username and password setting.

enter image description here

Now you can leverage those settings you just created. Here I save the username and password but only encrypt the password in it's respectable value field in the user.config file.

Example of the encrypted string in the user.config file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <secure_password_store.Properties.Settings>
            <setting name="username" serializeAs="String">
                <value>admin</value>
            </setting>
            <setting name="password" serializeAs="String">
                <value>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAQpgaPYIUq064U3o6xXkQOQAAAAACAAAAAAAQZgAAAAEAACAAAABlQQ8OcONYBr9qUhH7NeKF8bZB6uCJa5uKhk97NdH93AAAAAAOgAAAAAIAACAAAAC7yQicDYV5DiNp0fHXVEDZ7IhOXOrsRUbcY0ziYYTlKSAAAACVDQ+ICHWooDDaUywJeUOV9sRg5c8q6/vizdq8WtPVbkAAAADciZskoSw3g6N9EpX/8FOv+FeExZFxsm03i8vYdDHUVmJvX33K03rqiYF2qzpYCaldQnRxFH9wH2ZEHeSRPeiG</value>
            </setting>
        </secure_password_store.Properties.Settings>
    </userSettings>
</configuration>

enter image description here

Full Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Login_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                Properties.Settings.Default.username = textBox1.Text;
                Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
                Properties.Settings.Default.Save();
            }
            else if (checkBox1.Checked == false)
            {
                Properties.Settings.Default.username = "";
                Properties.Settings.Default.password = "";
                Properties.Settings.Default.Save();
            }
            MessageBox.Show("{\"data\": \"some data\"}","Login Message Alert",MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void DecryptString_Click(object sender, EventArgs e)
        {
            SecureString password = DecryptString(Properties.Settings.Default.password);
            string readable = ToInsecureString(password);
            textBox4.AppendText(readable + Environment.NewLine);
        }
        private void Form_Load(object sender, EventArgs e)
        {
            //textBox1.Text = "UserName";
            //textBox2.Text = "Password";
            if (Properties.Settings.Default.username != string.Empty)
            {
                textBox1.Text = Properties.Settings.Default.username;
                checkBox1.Checked = true;
                SecureString password = DecryptString(Properties.Settings.Default.password);
                string readable = ToInsecureString(password);
                textBox2.Text = readable;
            }
            groupBox1.Select();
        }


        static byte[] entropy = Encoding.Unicode.GetBytes("SaLtY bOy 6970 ePiC");

        public static string EncryptString(SecureString input)
        {
            byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(ToInsecureString(input)),entropy,DataProtectionScope.CurrentUser);
            return Convert.ToBase64String(encryptedData);
        }

        public static SecureString DecryptString(string encryptedData)
        {
            try
            {
                byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(encryptedData),entropy,DataProtectionScope.CurrentUser);
                return ToSecureString(Encoding.Unicode.GetString(decryptedData));
            }
            catch
            {
                return new SecureString();
            }
        }

        public static SecureString ToSecureString(string input)
        {
            SecureString secure = new SecureString();
            foreach (char c in input)
            {
                secure.AppendChar(c);
            }
            secure.MakeReadOnly();
            return secure;
        }

        public static string ToInsecureString(SecureString input)
        {
            string returnValue = string.Empty;
            IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
            try
            {
                returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
            }
            return returnValue;
        }

        private void EncryptString_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
            textBox3.AppendText(Properties.Settings.Default.password.ToString() + Environment.NewLine);
        }
    }
}

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

How to delete a specific file from folder using asp.net

This is how I delete files

if ((System.IO.File.Exists(fileName)))
                {
                    System.IO.File.Delete(fileName);
}

Also make sure that the file name you are passing in your delete, is the accurate path

EDIT

You could use the following event instead as well or just use the code in this snippet and use in your method

void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
  {

    // Get the currently selected row using the SelectedRow property.
    GridViewRow row = CustomersGridView.SelectedRow;

    //Debug this line and see what value is returned if it contains the full path.
    //If it does not contain the full path then add the path to the string.
    string fileName = row.Cells[0].Text 

    if(fileName != null || fileName != string.empty)
    {
       if((System.IO.File.Exists(fileName))
           System.IO.File.Delete(fileName);

     }
  }

Setting up PostgreSQL ODBC on Windows

Installing psqlODBC on 64bit Windows

Though you can install 32 bit ODBC drivers on Win X64 as usual, you can't configure 32-bit DSNs via ordinary control panel or ODBC datasource administrator.

How to configure 32 bit ODBC drivers on Win x64

Configure ODBC DSN from %SystemRoot%\syswow64\odbcad32.exe

  1. Start > Run
  2. Enter: %SystemRoot%\syswow64\odbcad32.exe
  3. Hit return.
  4. Open up ODBC and select under the System DSN tab.
  5. Select PostgreSQL Unicode

You may have to play with it and try different scenarios, think outside-the-box, remember this is open source.

"The Controls collection cannot be modified because the control contains code blocks"

I just ran into this problem as well but found another solution.

I found that wrapping the code blocks with a asp:PlaceHolder-tag solves the problem.

<asp:PlaceHolder runat="server">
  <meta name="ROBOTS" content="<%= this.ViewData["RobotsMeta"] %>" />
</asp:PlaceHolder>

(The CMS I'm using is inserting into the head-section from some code behind which restricted me from adding custom control blocks with various information like meta-tags etc so this is the only way it works for me.)

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

As this isn't mentioned in the accepted answer.

  • This is not the case for this exact question, but might help others that search for that problem
  • This is something you can do in your client-code to prevent CORS errors in some cases.

You can make use of Simple Requests.
In order to perform a 'Simple Requests' the request needs to meet several conditions. E.g. only allowing POST, GET and HEAD method, as well as only allowing some given Headers (you can find all conditions here).

If your client code does not explicit set affected Headers (e.g. "Accept") with a fix value in the request it might occur that some clients do set these Headers automatically with some "non-standard" values causing the server to not accept it as Simple Request - which will give you a CORS error.

Reading int values from SqlDataReader

TxtFarmerSize.Text = (int)reader[3];

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I would like to add an example of prototypical inheritance with javascript to @Scott Driscoll answer. We'll be using classical inheritance pattern with Object.create() which is a part of EcmaScript 5 specification.

First we create "Parent" object function

function Parent(){

}

Then add a prototype to "Parent" object function

 Parent.prototype = {
 primitive : 1,
 object : {
    one : 1
   }
}

Create "Child" object function

function Child(){

}

Assign child prototype (Make child prototype inherit from parent prototype)

Child.prototype = Object.create(Parent.prototype);

Assign proper "Child" prototype constructor

Child.prototype.constructor = Child;

Add method "changeProps" to a child prototype, which will rewrite "primitive" property value in Child object and change "object.one" value both in Child and Parent objects

Child.prototype.changeProps = function(){
    this.primitive = 2;
    this.object.one = 2;
};

Initiate Parent (dad) and Child (son) objects.

var dad = new Parent();
var son = new Child();

Call Child (son) changeProps method

son.changeProps();

Check the results.

Parent primitive property did not change

console.log(dad.primitive); /* 1 */

Child primitive property changed (rewritten)

console.log(son.primitive); /* 2 */

Parent and Child object.one properties changed

console.log(dad.object.one); /* 2 */
console.log(son.object.one); /* 2 */

Working example here http://jsbin.com/xexurukiso/1/edit/

More info on Object.create here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create

How do I convert uint to int in C#?

Given:

 uint n = 3;

int i = checked((int)n); //throws OverflowException if n > Int32.MaxValue
int i = unchecked((int)n); //converts the bits only 
                           //i will be negative if n > Int32.MaxValue

int i = (int)n; //same behavior as unchecked

or

int i = Convert.ToInt32(n); //same behavior as checked

--EDIT

Included info as mentioned by Kenan E. K.

The simplest way to resize an UIImage?

The simplest way is to set the frame of your UIImageView and set the contentMode to one of the resizing options.

Or you can use this utility method, if you actually need to resize an image:

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

Example usage:

#import "MYUtil.h"
…
UIImage *myIcon = [MYUtil imageWithImage:myUIImageInstance scaledToSize:CGSizeMake(20, 20)];

Embed website into my site

You can embed websites into another website using the <embed> tag, like so:

<embed src="http://www.example.com" style="width:500px; height: 300px;">

You can change the height, width, and URL to suit your needs.

The <embed> tag is the most up-to-date way to embed websites, as it was introduced with HTML5.

How to get the selected radio button value using js

check this

<input class="gender" type="radio" name="sex" value="male">Male
<br>
<input class="gender" type="radio" name="sex" value="female">Female


<script type="text/javascript">
$(document).ready(function () {
$(".gender").change(function () {

    var val = $('.gender:checked').val();
    alert(val);
});
});

</script>

Example

VBA Check if variable is empty

I had a similar issue with an integer that could be legitimately assigned 0 in Access VBA. None of the above solutions worked for me.

At first I just used a boolean var and IF statement:

Dim i as integer, bol as boolean
   If bol = false then
      i = ValueIWantToAssign
      bol = True
   End If

In my case, my integer variable assignment was within a for loop and another IF statement, so I ended up using "Exit For" instead as it was more concise.

Like so:

Dim i as integer
ForLoopStart
   If ConditionIsMet Then
      i = ValueIWantToAssign
   Exit For
   End If
ForLoopEnd

How to get the unix timestamp in C#

This solution helped in my situation:

   public class DateHelper {
     public static double DateTimeToUnixTimestamp(DateTime dateTime)
              {
                    return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -
                             new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
              }
    }

using helper in code:

double ret = DateHelper.DateTimeToUnixTimestamp(DateTime.Now)

How to check syslog in Bash on Linux?

If you like Vim, it has built-in syntax highlighting for the syslog file, e.g. it will highlight error messages in red.

vi +'syntax on' /var/log/syslog

.htaccess 301 redirect of single page

It will redirect your store page to your contact page

    <IfModule mod_rewrite.c>
    RewriteEngine On 
    RewriteBase /
    Redirect 301 /storepage /contactpage
    </IfModule>

How do I convert date/time from 24-hour format to 12-hour AM/PM?

Use smaller h

// 24 hrs 
H:i 
// output 14:20

// 12 hrs 
h:i 
// output 2:20

Convert char array to single int?

There are mulitple ways of converting a string to an int.

Solution 1: Using Legacy C functionality

int main()
{
    //char hello[5];     
    //hello = "12345";   --->This wont compile

    char hello[] = "12345";

    Printf("My number is: %d", atoi(hello)); 

    return 0;
}

Solution 2: Using lexical_cast(Most Appropriate & simplest)

int x = boost::lexical_cast<int>("12345"); 

Solution 3: Using C++ Streams

std::string hello("123"); 
std::stringstream str(hello); 
int x;  
str >> x;  
if (!str) 
{      
   // The conversion failed.      
} 

Update query PHP MySQL

Here i updated two variables and present date and time

$id = "1";
$title = "phpmyadmin";

 $sql=  mysql_query("UPDATE table_name SET id ='".$id."', title = '".$title."',now() WHERE id = '".$id."' ");

now() function update current date and time.

note: For update query we have define the particular id otherwise it update whole table defaulty

How do you performance test JavaScript code?

I usually just test javascript performance, how long script runs. jQuery Lover gave a good article link for testing javascript code performance, but the article only shows how to test how long your javascript code runs. I would also recommend reading article called "5 tips on improving your jQuery code while working with huge data sets".

SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'

An expression of non-boolean type specified in a context where a condition is expected

I also got this error when I forgot to add ON condition when specifying my join clause.

Determine device (iPhone, iPod Touch) with iOS

I know an answer has been ticked already, but for future reference, you could always use the device screen size to figure out which device it is like so:

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {

    CGSize result = [[UIScreen mainScreen] bounds].size;

    if (result.height == 480) {
        // 3.5 inch display - iPhone 4S and below
        NSLog(@"Device is an iPhone 4S or below");
    }

    else if (result.height == 568) {
        // 4 inch display - iPhone 5
        NSLog(@"Device is an iPhone 5/S/C");
    }

    else if (result.height == 667) {
        // 4.7 inch display - iPhone 6
        NSLog(@"Device is an iPhone 6");
    }

    else if (result.height == 736) {
        // 5.5 inch display - iPhone 6 Plus
        NSLog(@"Device is an iPhone 6 Plus");
    }
} 

else if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
       // iPad 9.7 or 7.9 inch display.
       NSLog(@"Device is an iPad.");
}

How to modify existing, unpushed commit messages?

To amend the previous commit, make the changes you want and stage those changes, and then run

git commit --amend

This will open a file in your text editor representing your new commit message. It starts out populated with the text from your old commit message. Change the commit message as you want, then save the file and quit your editor to finish.

To amend the previous commit and keep the same log message, run

git commit --amend -C HEAD

To fix the previous commit by removing it entirely, run

git reset --hard HEAD^

If you want to edit more than one commit message, run

git rebase -i HEAD~commit_count

(Replace commit_count with number of commits that you want to edit.) This command launches your editor. Mark the first commit (the one that you want to change) as “edit” instead of “pick”, then save and exit your editor. Make the change you want to commit and then run

git commit --amend
git rebase --continue

Note: You can also "Make the change you want" from the editor opened by git commit --amend

How to add multiple values to a dictionary key in python?

Make the value a list, e.g.

a["abc"] = [1, 2, "bob"]

UPDATE:

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

key = "somekey"
a.setdefault(key, [])
a[key].append(1)

Results:

>>> a
{'somekey': [1]}

Next, try:

key = "somekey"
a.setdefault(key, [])
a[key].append(2)

Results:

>>> a
{'somekey': [1, 2]}

The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

a.setdefault("somekey",[]).append("bob")

Results:

>>> a
{'somekey': [1, 2, 'bob']}

You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.

Is there a way to specify how many characters of a string to print out using printf()?

The basic way is:

printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");

The other, often more useful, way is:

printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");

Here, you specify the length as an int argument to printf(), which treats the '*' in the format as a request to get the length from an argument.

You can also use the notation:

printf ("Here are the first 8 chars: %*.*s\n",
        8, 8, "A string that is more than 8 chars");

This is also analogous to the "%8.8s" notation, but again allows you to specify the minimum and maximum lengths at runtime - more realistically in a scenario like:

printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);

The POSIX specification for printf() defines these mechanisms.

LaTeX package for syntax highlighting of code in various languages

LGrind does this. It's a mature LaTeX package that's been around since adam was a cowboy and has support for many programming languages.

Using Sockets to send and receive data

    //Client

    import java.io.*;
    import java.net.*;

    public class Client {
        public static void main(String[] args) {

        String hostname = "localhost";
        int port = 6789;

        // declaration section:
        // clientSocket: our client socket
        // os: output stream
        // is: input stream

            Socket clientSocket = null;  
            DataOutputStream os = null;
            BufferedReader is = null;

        // Initialization section:
        // Try to open a socket on the given port
        // Try to open input and output streams

            try {
                clientSocket = new Socket(hostname, port);
                os = new DataOutputStream(clientSocket.getOutputStream());
                is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: " + hostname);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: " + hostname);
            }

        // If everything has been initialized then we want to write some data
        // to the socket we have opened a connection to on the given port

        if (clientSocket == null || os == null || is == null) {
            System.err.println( "Something is wrong. One variable is null." );
            return;
        }

        try {
            while ( true ) {
            System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String keyboardInput = br.readLine();
            os.writeBytes( keyboardInput + "\n" );

            int n = Integer.parseInt( keyboardInput );
            if ( n == 0 || n == -1 ) {
                break;
            }

            String responseLine = is.readLine();
            System.out.println("Server returns its square as: " + responseLine);
            }

            // clean up:
            // close the output stream
            // close the input stream
            // close the socket

            os.close();
            is.close();
            clientSocket.close();   
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
        }           
    }





//Server




import java.io.*;
import java.net.*;

public class Server1 {
    public static void main(String args[]) {
    int port = 6789;
    Server1 server = new Server1( port );
    server.startServer();
    }

    // declare a server socket and a client socket for the server

    ServerSocket echoServer = null;
    Socket clientSocket = null;
    int port;

    public Server1( int port ) {
    this.port = port;
    }

    public void stopServer() {
    System.out.println( "Server cleaning up." );
    System.exit(0);
    }

    public void startServer() {
    // Try to open a server socket on the given port
    // Note that we can't choose a port less than 1024 if we are not
    // privileged users (root)

        try {
        echoServer = new ServerSocket(port);
        }
        catch (IOException e) {
        System.out.println(e);
        }   

    System.out.println( "Waiting for connections. Only one connection is allowed." );

    // Create a socket object from the ServerSocket to listen and accept connections.
    // Use Server1Connection to process the connection.

    while ( true ) {
        try {
        clientSocket = echoServer.accept();
        Server1Connection oneconnection = new Server1Connection(clientSocket, this);
        oneconnection.run();
        }   
        catch (IOException e) {
        System.out.println(e);
        }
    }
    }
}

class Server1Connection {
    BufferedReader is;
    PrintStream os;
    Socket clientSocket;
    Server1 server;

    public Server1Connection(Socket clientSocket, Server1 server) {
    this.clientSocket = clientSocket;
    this.server = server;
    System.out.println( "Connection established with: " + clientSocket );
    try {
        is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        os = new PrintStream(clientSocket.getOutputStream());
    } catch (IOException e) {
        System.out.println(e);
    }
    }

    public void run() {
        String line;
    try {
        boolean serverStop = false;

            while (true) {
                line = is.readLine();
        System.out.println( "Received " + line );
                int n = Integer.parseInt(line);
        if ( n == -1 ) {
            serverStop = true;
            break;
        }
        if ( n == 0 ) break;
                os.println("" + n*n ); 
            }

        System.out.println( "Connection closed." );
            is.close();
            os.close();
            clientSocket.close();

        if ( serverStop ) server.stopServer();
    } catch (IOException e) {
        System.out.println(e);
    }
    }
}

Reading/writing an INI file

The creators of the .NET framework want you to use XML-based config files, rather than INI files. So no, there is no built-in mechanism for reading them.

There are third party solutions available, though.

define a List like List<int,string>?

List<Tuple<string, DateTime, string>> mylist = new List<Tuple<string, DateTime,string>>();
mylist.Add(new Tuple<string, DateTime, string>(Datei_Info.Dateiname, Datei_Info.Datum, Datei_Info.Größe));
for (int i = 0; i < mylist.Count; i++)
{
     Console.WriteLine(mylist[i]);
}

Should I use px or rem value units in my CSS?

josh3736's answer is a good one, but to provide a counterpoint 3 years later:

I recommend using rem units for fonts, if only because it makes it easier for you, the developer, to change sizes. It's true that users very rarely change the default font size in their browsers, and that modern browser zoom will scale up px units. But what if your boss comes to you and says "don't enlarge the images or icons, but make all the fonts bigger". It's much easier to just change the root font size and let all the other fonts scale relative to that, then to change px sizes in dozens or hundreds of css rules.

I think it still makes sense to use px units for some images, or for certain layout elements that should always be the same size regardless of the scale of the design.

Caniuse.com may have said that only 75% of browsers when josh3736 posted his answer in 2012, but as of March 27 they claim 93.78% support. Only IE8 doesn't support it among the browsers they track.

regular expression for Indian mobile numbers

Here you go :)

^[7-9][0-9]{9}$

Convert month name to month number in SQL Server

How about this?

select DATEPART(MM,'january 01 2011') -- returns 1
select DATEPART(MM,'march 01 2011')  -- returns 3
select DATEPART(MM,'august 01 2011') -- returns 8

How to get current route in Symfony 2?

With Twig : {{ app.request.attributes.get('_route') }}

More elegant way of declaring multiple variables at the same time

This is an elaboration on @Jeff M's and my comments.

When you do this:

a, b = c, d

It works with tuple packing and unpacking. You can separate the packing and unpacking steps:

_ = c, d
a, b = _

The first line creates a tuple called _ which has two elements, the first with the value of c and the second with the value of d. The second line unpacks the _ tuple into the variables a and b. This breaks down your one huge line:

a, b, c, d, e, f, g, h, i, j = True, True, True, True, True, False, True, True, True, True

Into two smaller lines:

_ = True, True, True, True, True, False, True, True, True, True
a, b, c, d, e, f, g, h, i, j = _

It will give you the exact same result as the first line (including the same exception if you add values or variables to one part but forget to update the other). However, in this specific case, yan's answer is perhaps the best.

If you have a list of values, you can still unpack them. You just have to convert it to a tuple first. For example, the following will assign a value between 0 and 9 to each of a through j, respectively:

a, b, c, d, e, f, g, h, i, j = tuple(range(10))

EDIT: Neat trick to assign all of them as true except element 5 (variable f):

a, b, c, d, e, f, g, h, i, j = tuple(x != 5 for x in range(10))

Is <div style="width: ;height: ;background: "> CSS?

Yes, it is called Inline CSS, Here you styling the div using some height, width, and background.

Here the example:

<div style="width:50px;height:50px;background color:red">

You can achieve same using Internal or External CSS

2.Internal CSS:

  <head>
    <style>
    div {
    height:50px;
    width:50px;
    background-color:red;
    foreground-color:white;
    }
    </style>
  </head>
  <body>
    <div></div>
  </body>

3.External CSS:

<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div></div>
</body>

style.css /external css file/

 div {
        height:50px;
        width:50px;
        background-color:red;
    }

How to Generate Unique Public and Private Key via RSA

When you use a code like this:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   // Do something with the key...
   // Encrypt, export, etc.
}

.NET (actually Windows) stores your key in a persistent key container forever. The container is randomly generated by .NET

This means:

  1. Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account.

  2. Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute).

To resolve these issues:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   try
   {
      // Do something with the key...
      // Encrypt, export, etc.
   }
   finally
   {
      rsa.PersistKeyInCsp = false;
   }
}

ALWAYS

How to convert NSNumber to NSString

In Swift you can do like this

let number : NSNumber = 95
let str : String = number.stringValue

Where are my postgres *.conf files?

If you followed the white paper put out by Amazon for installing Postgresql on AWS, which included creating a /data/ directory on a filesystem mounted on a separate EBS volume, then your postgresql.conf file is in /data/

From which I conclude the file is created during initialisation of the data directory, and resides in the root of the data dir. For a default install this appears to be /var/lib/pgsql/data, but not if you moved the data dir

Read a file in Node.js

Run this code, it will fetch data from file and display in console

function fileread(filename)
{            
   var contents= fs.readFileSync(filename);
   return contents;
}        
var fs =require("fs");  // file system        
var data= fileread("abc.txt");
//module.exports.say =say;
//data.say();
console.log(data.toString());

How to switch activity without animation in Android?

You can create a style,

 <style name="noAnimTheme" parent="android:Theme">
   <item name="android:windowAnimationStyle">@null</item>
</style>

and set it as theme for your activity in the manifest:

   <activity android:name=".ui.ArticlesActivity" android:theme="@style/noAnimTheme">
    </activity>

You can also define a style to specify custom entry and exit animations. http://developer.android.com/reference/android/R.attr.html#windowEnterAnimation

CSS 100% height with padding/margin

This is the default behavior of display: block The fastest way that you can fix it in 2020 is to set display: 'flex' of parent element and padding e.g. 20px then all its children will have 100% height relative to its height.

Pure CSS to make font-size responsive based on dynamic amount of characters

Edit: Watch out for attr() Its related to calc() in css. You may be able to achieve it in future.

Unfortunately for now there isn't a css only solution. This is what I suggest you do. To your element give a title attribute. And use text-overflow ellipsis to prevent breakage of the design and let user know more text is there.

<div style="width: 200px; height: 1em; text-overflow: ellipsis;" title="Some sample dynamic amount of text here">
 Some sample dynamic amount of text here
</div>

.

.

.

Alternatively, If you just want to reduce size based on the viewport. CSS3 supports new dimensions that are relative to view port.

body {
   font-size: 3.2vw;
}
  1. 3.2vw = 3.2% of width of viewport
  2. 3.2vh = 3.2% of height of viewport
  3. 3.2vmin = Smaller of 3.2vw or 3.2vh
  4. 3.2vmax = Bigger of 3.2vw or 3.2vh see css-tricks.com/.... and also look at caniuse.com/....

how to convert milliseconds to date format in android?

This is the easiest way using Kotlin

private const val DATE_FORMAT = "dd/MM/yy hh:mm"

fun millisToDate(millis: Long) : String {
    return SimpleDateFormat(DATE_FORMAT, Locale.US).format(Date(millis))
}

Is there a way to make mv create the directory to be moved to if it doesn't exist?

You can use mkdir:

mkdir -p ~/bar/baz/ && \
mv foo.c ~/bar/baz/

A simple script to do it automatically (untested):

#!/bin/sh

# Grab the last argument (argument number $#)    
eval LAST_ARG=\$$#

# Strip the filename (if it exists) from the destination, getting the directory
DIR_NAME=`echo $2 | sed -e 's_/[^/]*$__'`

# Move to the directory, making the directory if necessary
mkdir -p "$DIR_NAME" || exit
mv "$@"

Django -- Template tag in {% if %} block

Sorry for comment in an old post but if you want to use an else if statement this will help you

{% if title == source %}
    Do This
{% elif title == value %}
    Do This
{% else %}
    Do This
{% endif %}

For more info see Django Documentation

How to send PUT, DELETE HTTP request in HttpURLConnection?

I agree with @adietisheim and the rest of people that suggest HttpClient.

I spent time trying to make a simple call to rest service with HttpURLConnection and it hadn't convinced me and after that I tried with HttpClient and it was really more easy, understandable and nice.

An example of code to make a put http call is as follows:

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpPut putRequest = new HttpPut(URI);

StringEntity input = new StringEntity(XML);
input.setContentType(CONTENT_TYPE);

putRequest.setEntity(input);
HttpResponse response = httpClient.execute(putRequest);

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

Adding to @Greg Hewgill answer: if you want to be able to match both date-time and only date, you can make the "time" part of the regex optional:

(\d{4})-(\d{2})-(\d{2})( (\d{2}):(\d{2}):(\d{2}))?

this way you will match both 2008-09-01 12:35:42 and 2008-09-01

Recursive Fibonacci

This is my solution to fibonacci problem with recursion.

#include <iostream>
using namespace std;

int fibonacci(int n){
    if(n<=0)
        return 0;
    else if(n==1 || n==2)
        return 1;
    else
        return (fibonacci(n-1)+fibonacci(n-2));
}

int main() {
    cout << fibonacci(8);
    return 0;
}

Good PHP ORM Library?

I really like Propel, here you can get an overview, the documentation is pretty good, and you can get it through PEAR or SVN.

You only need a working PHP5 install, and Phing to start generating classes.

javascript: calculate x% of a number

In order to fully avoid floating point issues, the amount whose percent is being calculated and the percent itself need to be converted to integers. Here's how I resolved this:

function calculatePercent(amount, percent) {
    const amountDecimals = getNumberOfDecimals(amount);
    const percentDecimals = getNumberOfDecimals(percent);
    const amountAsInteger = Math.round(amount + `e${amountDecimals}`);
    const percentAsInteger = Math.round(percent + `e${percentDecimals}`);
    const precisionCorrection = `e-${amountDecimals + percentDecimals + 2}`;    // add 2 to scale by an additional 100 since the percentage supplied is 100x the actual multiple (e.g. 35.8% is passed as 35.8, but as a proper multiple is 0.358)

    return Number((amountAsInteger * percentAsInteger) + precisionCorrection);
}

function getNumberOfDecimals(number) {
    const decimals = parseFloat(number).toString().split('.')[1];

    if (decimals) {
        return decimals.length;
    }

    return 0;
}

calculatePercent(20.05, 10); // 2.005

As you can see, I:

  1. Count the number of decimals in both the amount and the percent
  2. Convert both amount and percent to integers using exponential notation
  3. Calculate the exponential notation needed to determine the proper end value
  4. Calculate the end value

The usage of exponential notation was inspired by Jack Moore's blog post. I'm sure my syntax could be shorter, but I wanted to be as explicit as possible in my usage of variable names and explaining each step.

Define make variable at rule execution time

In your example, the TMP variable is set (and the temporary directory created) whenever the rules for out.tar are evaluated. In order to create the directory only when out.tar is actually fired, you need to move the directory creation down into the steps:

out.tar : 
    $(eval TMP := $(shell mktemp -d))
    @echo hi $(TMP)/hi.txt
    tar -C $(TMP) cf $@ .
    rm -rf $(TMP)

The eval function evaluates a string as if it had been typed into the makefile manually. In this case, it sets the TMP variable to the result of the shell function call.

edit (in response to comments):

To create a unique variable, you could do the following:

out.tar : 
    $(eval $@_TMP := $(shell mktemp -d))
    @echo hi $($@_TMP)/hi.txt
    tar -C $($@_TMP) cf $@ .
    rm -rf $($@_TMP)

This would prepend the name of the target (out.tar, in this case) to the variable, producing a variable with the name out.tar_TMP. Hopefully, that is enough to prevent conflicts.

How to get all selected values of a multiple select box?

You may use jquery plugin chosen .

<head>
 <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css"
 <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
 <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
 <script>
        jQuery(document).ready(function(){
            jQuery(".chosen").data("placeholder","Select Frameworks...").chosen();
        });
 </script>
</head>

 <body> 
   <label for="Test" class="col-md-3 control label">Test</label>
      <select class="chosen" style="width:350px" multiple="true">
            <option>Choose...</option>
            <option>Java</option>                           
            <option>C++</option>
            <option>Python</option>
     </select>
 </body>

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

In > Swift 2.2, I've combined few answers here.

Make an outlet from storyboard to link to your staticCell.

@IBOutlet weak var updateStaticCell: UITableViewCell!

override func viewDidLoad() {
    ...
    updateStaticCell.hidden = true
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.row == 0 {
        return 0
    } else {
        return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
    }
}

I want to hide my first cell so I set the height to 0 as described above.

Working with select using AngularJS's ng-options

I'm learning AngularJS and was struggling with selection as well. I know this question is already answered, but I wanted to share some more code nevertheless.

In my test I have two listboxes: car makes and car models. The models list is disabled until some make is selected. If selection in makes listbox is later reset (set to 'Select Make') then the models listbox becomes disabled again AND its selection is reset as well (to 'Select Model'). Makes are retrieved as a resource while models are just hard-coded.

Makes JSON:

[
{"code": "0", "name": "Select Make"},
{"code": "1", "name": "Acura"},
{"code": "2", "name": "Audi"}
]

services.js:

angular.module('makeServices', ['ngResource']).
factory('Make', function($resource){
    return $resource('makes.json', {}, {
        query: {method:'GET', isArray:true}
    });
});

HTML file:

<div ng:controller="MakeModelCtrl">
  <div>Make</div>
  <select id="makeListBox"
      ng-model="make.selected"
      ng-options="make.code as make.name for make in makes"
      ng-change="makeChanged(make.selected)">
  </select>

  <div>Model</div>
  <select id="modelListBox"
     ng-disabled="makeNotSelected"
     ng-model="model.selected"
     ng-options="model.code as model.name for model in models">
  </select>
</div>

controllers.js:

function MakeModelCtrl($scope)
{
    $scope.makeNotSelected = true;
    $scope.make = {selected: "0"};
    $scope.makes = Make.query({}, function (makes) {
         $scope.make = {selected: makes[0].code};
    });

    $scope.makeChanged = function(selectedMakeCode) {
        $scope.makeNotSelected = !selectedMakeCode;
        if ($scope.makeNotSelected)
        {
            $scope.model = {selected: "0"};
        }
    };

    $scope.models = [
      {code:"0", name:"Select Model"},
      {code:"1", name:"Model1"},
      {code:"2", name:"Model2"}
    ];
    $scope.model = {selected: "0"};
}

Disabling enter key for form

Here's a simple way to accomplish this with jQuery that limits it to the appropriate input elements:

//prevent submission of forms when pressing Enter key in a text input
$(document).on('keypress', ':input:not(textarea):not([type=submit])', function (e) {
    if (e.which == 13) e.preventDefault();
});

Thanks to this answer: https://stackoverflow.com/a/1977126/560114.

how to check which version of nltk, scikit learn installed?

In Windows® systems you can simply try

pip3 list | findstr scikit

scikit-learn                  0.22.1

If you are on Anaconda try

conda list scikit

scikit-learn              0.22.1           py37h6288b17_0

And this can be used to find out the version of any package you have installed. For example

pip3 list | findstr numpy

numpy                         1.17.4
numpydoc                      0.9.2

Or if you want to look for more than one package at a time

pip3 list | findstr "scikit numpy"

numpy                         1.17.4
numpydoc                      0.9.2
scikit-learn                  0.22.1

Note the quote characters are required when searching for more than one word.

Take care.

Interfaces vs. abstract classes

Abstract classes and interfaces are semantically different, although their usage can overlap.

An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.

An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.

Is it .yaml or .yml?

.yaml is apparently the official extension, because some applications fail when using .yml. On the other hand I am not familiar with any applications which use YAML code, but fail with a .yaml extension.

I just stumbled across this, as I was used to writing .yml in Ansible and Docker Compose. Out of habit I used .yml when writing Netplan files which failed silently. I finally figured out my mistake. The author of a popular Ansible Galaxy role for Netplan makes the same assumption in his code:

- name: Capturing Existing Configurations
  find:
    paths: /etc/netplan
    patterns: "*.yml,*.yaml"
  register: _netplan_configs

Yet any files with a .yml extension get ignored by Netplan in the same way as files with a .bak extension. As Netplan is very quiet, and gives no feedback whatsoever on success, even with netplan apply --debug, a config such as 01-netcfg.yml will fail silently without any meaningful feedback.

source command not found in sh shell

source is a bash built-in command so to execute source command, you can log in as Root.

sudo -s source ./filename.sh

How to select some rows with specific rownames from a dataframe?

You can also use this:

DF[paste0("stu",c(2,3,5,9)), ]

How to ignore conflicts in rpm installs

The --force option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.

If you tell rpm to install all RPMs from some directory, then it does exactly this. rpm will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.

You can remove the old RPM and rpm will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.

If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i (zypper in can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.

I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify command. It will complain for the new package if the old one has overwritten some files.

Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?

New to unit testing, how to write great tests?

Unit testing is about the output you get from a function/method/application. It does not matter at all how the result is produced, it just matters that it is correct. Therefore, your approach of counting calls to inner methods and such is wrong. What I tend to do is sit down and write what a method should return given certain input values or a certain environment, then write a test which compares the actual value returned with what I came up with.

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

Set CSS property in Javascript?

<body>
  <h1 id="h1">Silence and Smile</h1><br />
  <h3 id="h3">Silence and Smile</h3>

  <script type="text/javascript">
    document.getElementById("h1").style.color = "Red";
    document.getElementById("h1").style.background = "Green";
    document.getElementById("h3").style.fontSize = "larger" ; 
    document.getElementById("h3").style.fontFamily = "Arial";
  </script>
</body>

How to list all properties of a PowerShell object

Try this:

Get-WmiObject -Class "Win32_computersystem" | Format-List *
Get-WmiObject -Class "Win32_computersystem" | Format-List -Property *

For certain objects, PowerShell provides a set of formatting instructions that can affect either the table or list formats. These are usually meant to limit the display of reams of properties down to just the essential properties. However there are times when you really want to see everything. In those cases Format-List * will show all the properties. Note that in the case where you're trying to view a PowerShell error record, you need to use "Format-List * -Force" to truly see all the error information, for example,

$error[0] | Format-List * -force

Note that the wildcard can be used like a traditional wilcard this:

Get-WmiObject -Class "Win32_computersystem" | Format-List M*

What is the purpose of a plus symbol before a variable?

As explained in other answers it converts the variable to a number. Specially useful when d can be either a number or a string that evaluates to a number.

Example (using the addMonths function in the question):

addMonths(34,1,true);
addMonths("34",1,true);

then the +d will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d is a number, a function or a string that can be converted to a number.

Executing multi-line statements in the one-line command-line?

If your system is Posix.2 compliant it should supply the printf utility:

$ printf "print 'zap'\nfor r in range(3): print 'rob'" | python
zap
rob
rob
rob

How to convert nanoseconds to seconds using the TimeUnit enum?

TimeUnit is an enum, so you can't create a new one.

The following will convert 1000000000000ns to seconds.

TimeUnit.NANOSECONDS.toSeconds(1000000000000L);

How to checkout a specific Subversion revision from the command line?

Go to folder and use the command:

svn co {url}

Fatal error: Namespace declaration statement has to be the very first statement in the script in

UTF-8 Byte Order Mark at the beginning of the document
^THIS for me solved the issue. I opened the inolved file with an HEX editor and removed the BOM at the start of the file.

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

In the earlier versions of MySQL ( < 5.7.5 ) the only way to set

'innodb_buffer_pool_size'

variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :

[mysqld]

innodb_buffer_pool_size = 2147483648

You need to restart your mysql server to have it's effect in action.

UPDATE :

As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:

mysql> SET GLOBAL innodb_buffer_pool_size=402653184;

Reference : https://dev.mysql.com/doc/refman/5.7/en/innodb-buffer-pool-resize.html

How to change the font and font size of an HTML input tag?

in your css :

 #txtComputer {
      font-size: 24px;
 }

You can style an input entirely (background, color, etc.) and even use the hover event.

How can I generate UUID in C#

I don't know about methods; however, the type to GUID can be done via:

Guid iid = System.Runtime.InteropServices.Marshal.GenerateGuidForType(typeof(IFoo));

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.generateguidfortype.aspx

Count number of vector values in range with R

Use which:

 set.seed(1)
 x <- sample(10, 50, replace = TRUE)
 length(which(x > 3 & x < 5))
 # [1]  6

How do I delete multiple rows in Entity Framework (without foreach)

EntityFramework 6 has made this a bit easier with .RemoveRange().

Example:

db.People.RemoveRange(db.People.Where(x => x.State == "CA"));
db.SaveChanges();