Programs & Examples On #Vpn

A virtual private network (VPN) is a network that uses primarily public telecommunication infrastructure, such as the Internet, to provide remote offices or travelling users access to a central organizational network. Questions about configuring or using a VPN should be asked on Super User or Server Fault.

How to solve javax.net.ssl.SSLHandshakeException Error?

First, you need to obtain the public certificate from the server you're trying to connect to. That can be done in a variety of ways, such as contacting the server admin and asking for it, using OpenSSL to download it, or, since this appears to be an HTTP server, connecting to it with any browser, viewing the page's security info, and saving a copy of the certificate. (Google should be able to tell you exactly what to do for your specific browser.)

Now that you have the certificate saved in a file, you need to add it to your JVM's trust store. At $JAVA_HOME/jre/lib/security/ for JREs or $JAVA_HOME/lib/security for JDKs, there's a file named cacerts, which comes with Java and contains the public certificates of the well-known Certifying Authorities. To import the new cert, run keytool as a user who has permission to write to cacerts:

keytool -import -file <the cert file> -alias <some meaningful name> -keystore <path to cacerts file>

It will most likely ask you for a password. The default password as shipped with Java is changeit. Almost nobody changes it. After you complete these relatively simple steps, you'll be communicating securely and with the assurance that you're talking to the right server and only the right server (as long as they don't lose their private key).

Not connecting to SQL Server over VPN

On a default instance, SQL Server listens on TCP/1433 by default. This can be changed. On a named instance, unless configured differently, SQL Server listens on a dynamic TCP port. What that means is should SQL Server discover that the port is in use, it will pick another TCP port. How clients usually find the right port in the case of a named instance is by talking to the SQL Server Listener Service/SQL Browser. That listens on UDP/1434 and cannot be changed. If you have a named instance, you can configure a static port and if you have a need to use Kerberos authentication/delegation, you should.

What you'll need to determine is what port your SQL Server is listening on. Then you'll need to get with your networking/security folks to determine if they allow communication to that port via VPN. If they are, as indicated, check your firewall settings. Some systems have multiple firewalls (my laptop is an example). If so, you'll need to check all the firewalls on your system.

If all of those are correct, verify the server doesn't have an IPSEC policy that restricts access to the SQL Server port via IP address. That also could result in you being blocked.

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

Establish a VPN connection in cmd

Is Powershell an option?

Start Powershell:

powershell

Create the VPN Connection: Add-VpnConnection

Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm] 

Edit VPN connections: Set-VpnConnection

Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]

Lookup VPN Connections: Get-VpnConnection

Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]

Connect: rasdial [connectionName]

rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]

You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial.

The results of Get-VpnConnection can be a little verbose. This can be simplified with a simple Select-Object filter:

Get-VpnConnection | Select-Object -Property Name

More information can be found here:

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

Windows 8.1 gets Error 720 on connect VPN

I had the same problem. Most posted solutions would not work. I ran sfc /scannow and it reported that some errors could not be fixed. To address that problem I ran the command

Dism /Online /Cleanup-Image /RestoreHealth

Ironically, I later found the WAN errors had gone away, the 720 VPN error went away and my VPN worked.

Hard to believe that the WAN errors were corrected by this rather esoteric command, but it's worth a try.

Hash and salt passwords in C#

I read all answers and I think those enough, specially @Michael articles with slow hashing and @CodesInChaos good comments, but I decided to share my code snippet for hashing/validating that may be useful and it does not require [Microsoft.AspNet.Cryptography.KeyDerivation].

    private static bool SlowEquals(byte[] a, byte[] b)
            {
                uint diff = (uint)a.Length ^ (uint)b.Length;
                for (int i = 0; i < a.Length && i < b.Length; i++)
                    diff |= (uint)(a[i] ^ b[i]);
                return diff == 0;
            }

    private static byte[] PBKDF2(string password, byte[] salt, int iterations, int outputBytes)
            {
                Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt);
                pbkdf2.IterationCount = iterations;
                return pbkdf2.GetBytes(outputBytes);
            }

    private static string CreateHash(string value, int salt_bytes, int hash_bytes, int pbkdf2_iterations)
            {
                // Generate a random salt
                RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
                byte[] salt = new byte[salt_bytes];
                csprng.GetBytes(salt);

                // Hash the value and encode the parameters
                byte[] hash = PBKDF2(value, salt, pbkdf2_iterations, hash_bytes);

                //You need to return the salt value too for the validation process
                return Convert.ToBase64String(hash) + ":" + 
                       Convert.ToBase64String(hash);
            }

    private static bool ValidateHash(string pureVal, string saltVal, string hashVal, int pbkdf2_iterations)
            {
                try
                {
                    byte[] salt = Convert.FromBase64String(saltVal);
                    byte[] hash = Convert.FromBase64String(hashVal);

                    byte[] testHash = PBKDF2(pureVal, salt, pbkdf2_iterations, hash.Length);
                    return SlowEquals(hash, testHash);
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

Please pay attention SlowEquals function that is so important, Finally, I hope this help and Please don't hesitate to advise me about better approaches.

console.writeline and System.out.println

Here are the primary differences between using System.out/.err/.in and System.console():

  • System.console() returns null if your application is not run in a terminal (though you can handle this in your application)
  • System.console() provides methods for reading password without echoing characters
  • System.out and System.err use the default platform encoding, while the Console class output methods use the console encoding

This latter behaviour may not be immediately obvious, but code like this can demonstrate the difference:

public class ConsoleDemo {
  public static void main(String[] args) {
    String[] data = { "\u250C\u2500\u2500\u2500\u2500\u2500\u2510", 
        "\u2502Hello\u2502",
        "\u2514\u2500\u2500\u2500\u2500\u2500\u2518" };
    for (String s : data) {
      System.out.println(s);
    }
    for (String s : data) {
      System.console().writer().println(s);
    }
  }
}

On my Windows XP which has a system encoding of windows-1252 and a default console encoding of IBM850, this code will write:

???????
?Hello?
???????
+-----+
¦Hello¦
+-----+

Note that this behaviour depends on the console encoding being set to a different encoding to the system encoding. This is the default behaviour on Windows for a bunch of historical reasons.

Convert float to std::string in C++

As of C++11, the standard C++ library provides the function std::to_string(arg) with various supported types for arg.

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

Add the full link, with:

 "http://"

to the beginning of a line, and most decent email clients will auto-link it either before sending, or at the other end when receiving.

For really long urls that will likely wrap due to all the parameters, wrap the link in a less than/greater than symbol. This tells the email client not to wrap the url.

e.g.

  <http://www.example.com/foo.php?this=a&really=long&url=with&lots=and&lots=and&lots=of&prameters=on_it>

How do I execute code AFTER a form has loaded?

You could also try putting your code in the Activated event of the form, if you want it to occur, just when the form is activated. You would need to put in a boolean "has executed" check though if it is only supposed to run on the first activation.

Why is "except: pass" a bad programming practice?

The main problem here is that it ignores all and any error: Out of memory, CPU is burning, user wants to stop, program wants to exit, Jabberwocky is killing users.

This is way too much. In your head, you're thinking "I want to ignore this network error". If something unexpected goes wrong, then your code silently continues and breaks in completely unpredictable ways that no one can debug.

That's why you should limit yourself to ignoring specifically only some errors and let the rest pass.

How Big can a Python List Get?

In casual code I've created lists with millions of elements. I believe that Python's implementation of lists are only bound by the amount of memory on your system.

In addition, the list methods / functions should continue to work despite the size of the list.

If you care about performance, it might be worthwhile to look into a library such as NumPy.

Creating a new user and password with Ansible

Generating random password for user

first need to define users variable then follow below

tasks:

- name: Generate Passwords
  become: no
  local_action: command pwgen -N 1 8
  with_items: '{{ users }}'
  register: user_passwords

- name: Update User Passwords
  user:
    name: '{{ item.item }}'
    password: "{{ item.stdout | password_hash('sha512')}}"
    update_password: on_create
  with_items: '{{ user_passwords.results }}'

- name: Save Passwords Locally
  become: no
  local_action: copy content={{ item.stdout }} dest=./{{ item.item }}.txt
  with_items: '{{ user_passwords.results }}'

Appending HTML string to the DOM

Is this acceptable?

var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
document.getElementById('test').appendChild(child);

jsFiddle.

But, Neil's answer is a better solution.

Running vbscript from batch file

This is the command for the batch file and it can run the vbscript.

C:\Windows\SysWOW64\cmd.exe /c cscript C:\Windows\SysWOW64\...\necdaily.vbs

Reset push notification settings for app

In addition to the answer of ianolito.

Had the same issue with an app I downloaded a year ago and denying push notification initially. Now wanting push notifications back, these steps worked for me on iOS 7 beta. Not sure which point(s) triggered it exactly.

  • Close and delete the app.
  • Go to your iCloud settings and delete the app from the iCloud. Do this on all other devices where you have iCloud backup for apps enabled. After deactivating and deleting make a fresh backup. The app should not be listed any more under the backups. (This is maybe why the Technical Note from Apple described by ianolito stopped working in iOS 5, since iCloud was introduced in iOS 5 and many have iCloud backup for apps enabled.)
  • Go to your time settings and set the time more than 1 month ahead.
  • Switch the iPhone off (no reset).
  • Wait a minute, switch it on again and download the app again.
  • Start the app and I was presented the dialog again.
  • Enable app backup again, since it is still deactivated. Correct the time.

Thank god I did not have to "Erase All Content And Settings". Maybe it will help someone.

How do I update the element at a certain position in an ArrayList?

 import java.util.ArrayList;
 import java.util.Iterator;


 public class javaClass {

public static void main(String args[]) {


    ArrayList<String> alstr = new ArrayList<>();
    alstr.add("irfan");
    alstr.add("yogesh");
    alstr.add("kapil");
    alstr.add("rajoria");

    for(String str : alstr) {
        System.out.println(str);
    }
    // update value here
    alstr.set(3, "Ramveer");
    System.out.println("with Iterator");
    Iterator<String>  itr = alstr.iterator();

    while (itr.hasNext()) {
        Object obj = itr.next();
        System.out.println(obj);

    }
}}

What is the bower (and npm) version syntax?

In a nutshell, the syntax for Bower version numbers (and NPM's) is called SemVer, which is short for 'Semantic Versioning'. You can find documentation for the detailed syntax of SemVer as used in Bower and NPM on the API for the semver parser within Node/npm. You can learn more about the underlying spec (which does not mention ~ or other syntax details) at semver.org.

There's a super-handy visual semver calculator you can play with, making all of this much easier to grok and test.

SemVer isn't just a syntax! It has some pretty interesting things to say about the right ways to publish API's, which will help to understand what the syntax means. Crucially:

Once you identify your public API, you communicate changes to it with specific increments to your version number. Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version.

So, your specific question about ~ relates to that Major.Minor.Patch schema. (As does the related caret operator ^.) You can use ~ to narrow the range of versions you're willing to accept to either:

  • subsequent patch-level changes to the same minor version ("bug fixes not affecting the API"), or:
  • subsequent minor-level changes to the same major version ("backwards compatible API additions/changes")

For example: to indicate you'll take any subsequent patch-level changes on the 1.2.x tree, starting with 1.2.0, but less than 1.3.0, you could use:

"angular": "~1.2"
  or:
"angular": "~1.2.0"

This also gets you the same results as using the .x syntax:

"angular": "1.2.x"

But, you can use the tilde/~ syntax to be even more specific: if you're only willing to accept patch-level changes starting with 1.2.4, but still less than 1.3.0, you'd use:

"angular": "~1.2.4"

Moving left, towards the major version, if you use...

"angular": "~1"

... it's the same as...

"angular": "1.x"
  or:
"angular": "^1.0.0"

...and matches any minor- or patch-level changes above 1.0.0, and less than 2.0:

Note that last variation above: it's called a 'caret range'. The caret looks an awful lot like a >, so you'd be excused for thinking it means "any version greater than 1.0.0". (I've certainly slipped on that.) Nope!

Caret ranges are basically used to say that you care only about the left-most significant digit - usually the major version - and that you'll permit any minor- or patch-level changes that don't affect that left-most digit. Yet, unlike a tilde range that specifies a major version, caret ranges let you specify a precise minor/patch starting point. So, while ^1.0.0 === ~1, a caret range such as ^1.2.3 lets you say you'll take any changes >=1.2.3 && <2.0.0. You couldn't do that with a tilde range.

That all seems confusing at first, when you look at it up-close. But zoom out for a sec, and think about it this way: the caret simply lets you say that you're most concerned about whatever significant digit is left-most. The tilde lets you say you're most concerned about whichever digit is right-most. The rest is detail.

It's the expressive power of the tilde and the caret that explains why people use them much more than the simpler .x syntax: they simply let you do more. That's why you'll see the tilde used often even where .x would serve. As an example, see npm itself: its own package.json file includes lots of dependencies in ~2.4.0 format, rather than the 2.4.x format it could use. By sticking to ~, the syntax is consistent all the way down a list of 70+ versioned dependencies, regardless of which beginning patch number is acceptable.

Anyway, there's still more to SemVer, but I won't try to detail it all here. Check it out on the node semver package's readme. And be sure to use the semantic versioning calculator while you're practicing and trying to get your head around how SemVer works.


RE: Non-Consecutive Version Numbers: OP's final question seems to be about specifying non-consecutive version numbers/ranges (if I have edited it fairly). Yes, you can do that, using the common double-pipe "or" operator: ||. Like so:

"angular": "1.2 <= 1.2.9 || >2.0.0"

What are database constraints?

Constraints are part of a database schema definition.

A constraint is usually associated with a table and is created with a CREATE CONSTRAINT or CREATE ASSERTION SQL statement.

They define certain properties that data in a database must comply with. They can apply to a column, a whole table, more than one table or an entire schema. A reliable database system ensures that constraints hold at all times (except possibly inside a transaction, for so called deferred constraints).

Common kinds of constraints are:

  • not null - each value in a column must not be NULL
  • unique - value(s) in specified column(s) must be unique for each row in a table
  • primary key - value(s) in specified column(s) must be unique for each row in a table and not be NULL; normally each table in a database should have a primary key - it is used to identify individual records
  • foreign key - value(s) in specified column(s) must reference an existing record in another table (via it's primary key or some other unique constraint)
  • check - an expression is specified, which must evaluate to true for constraint to be satisfied

Copying one structure to another

You can use the following solution to accomplish your goal:

struct student 
{
    char name[20];
    char country[20];
};
void main()
{
    struct student S={"Wolverine","America"};
    struct student X;
    X=S;
    printf("%s%s",X.name,X.country);
}

Convert International String to \u Codes in java

You could use escapeJavaStyleString from org.apache.commons.lang.StringEscapeUtils.

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

Install xunit.runner.visualstudio package for the test project

multiple where condition codeigniter

it's late for this answer but i think maybe still can help, i try the both methods above, using two where conditions and the method with the array, none of those work for me i did several test and the condition was never getting executed, so i did a workaround, here is my code:

public function validateLogin($email, $password){
        $password = md5($password);
        $this->db->select("userID,email,password");
        $query = $this->db->get_where("users", array("email" => $email));
        $p = $query->row_array();

        if($query->num_rows() == 1 && $password == $p['password']){  
            return $query->row();
        }

    }

How do I use arrays in C++?

Arrays on the type level

An array type is denoted as T[n] where T is the element type and n is a positive size, the number of elements in the array. The array type is a product type of the element type and the size. If one or both of those ingredients differ, you get a distinct type:

#include <type_traits>

static_assert(!std::is_same<int[8], float[8]>::value, "distinct element type");
static_assert(!std::is_same<int[8],   int[9]>::value, "distinct size");

Note that the size is part of the type, that is, array types of different size are incompatible types that have absolutely nothing to do with each other. sizeof(T[n]) is equivalent to n * sizeof(T).

Array-to-pointer decay

The only "connection" between T[n] and T[m] is that both types can implicitly be converted to T*, and the result of this conversion is a pointer to the first element of the array. That is, anywhere a T* is required, you can provide a T[n], and the compiler will silently provide that pointer:

                  +---+---+---+---+---+---+---+---+
the_actual_array: |   |   |   |   |   |   |   |   |   int[8]
                  +---+---+---+---+---+---+---+---+
                    ^
                    |
                    |
                    |
                    |  pointer_to_the_first_element   int*

This conversion is known as "array-to-pointer decay", and it is a major source of confusion. The size of the array is lost in this process, since it is no longer part of the type (T*). Pro: Forgetting the size of an array on the type level allows a pointer to point to the first element of an array of any size. Con: Given a pointer to the first (or any other) element of an array, there is no way to detect how large that array is or where exactly the pointer points to relative to the bounds of the array. Pointers are extremely stupid.

Arrays are not pointers

The compiler will silently generate a pointer to the first element of an array whenever it is deemed useful, that is, whenever an operation would fail on an array but succeed on a pointer. This conversion from array to pointer is trivial, since the resulting pointer value is simply the address of the array. Note that the pointer is not stored as part of the array itself (or anywhere else in memory). An array is not a pointer.

static_assert(!std::is_same<int[8], int*>::value, "an array is not a pointer");

One important context in which an array does not decay into a pointer to its first element is when the & operator is applied to it. In that case, the & operator yields a pointer to the entire array, not just a pointer to its first element. Although in that case the values (the addresses) are the same, a pointer to the first element of an array and a pointer to the entire array are completely distinct types:

static_assert(!std::is_same<int*, int(*)[8]>::value, "distinct element type");

The following ASCII art explains this distinction:

      +-----------------------------------+
      | +---+---+---+---+---+---+---+---+ |
+---> | |   |   |   |   |   |   |   |   | | int[8]
|     | +---+---+---+---+---+---+---+---+ |
|     +---^-------------------------------+
|         |
|         |
|         |
|         |  pointer_to_the_first_element   int*
|
|  pointer_to_the_entire_array              int(*)[8]

Note how the pointer to the first element only points to a single integer (depicted as a small box), whereas the pointer to the entire array points to an array of 8 integers (depicted as a large box).

The same situation arises in classes and is maybe more obvious. A pointer to an object and a pointer to its first data member have the same value (the same address), yet they are completely distinct types.

If you are unfamiliar with the C declarator syntax, the parenthesis in the type int(*)[8] are essential:

  • int(*)[8] is a pointer to an array of 8 integers.
  • int*[8] is an array of 8 pointers, each element of type int*.

Accessing elements

C++ provides two syntactic variations to access individual elements of an array. Neither of them is superior to the other, and you should familiarize yourself with both.

Pointer arithmetic

Given a pointer p to the first element of an array, the expression p+i yields a pointer to the i-th element of the array. By dereferencing that pointer afterwards, one can access individual elements:

std::cout << *(x+3) << ", " << *(x+7) << std::endl;

If x denotes an array, then array-to-pointer decay will kick in, because adding an array and an integer is meaningless (there is no plus operation on arrays), but adding a pointer and an integer makes sense:

   +---+---+---+---+---+---+---+---+
x: |   |   |   |   |   |   |   |   |   int[8]
   +---+---+---+---+---+---+---+---+
     ^           ^               ^
     |           |               |
     |           |               |
     |           |               |
x+0  |      x+3  |          x+7  |     int*

(Note that the implicitly generated pointer has no name, so I wrote x+0 in order to identify it.)

If, on the other hand, x denotes a pointer to the first (or any other) element of an array, then array-to-pointer decay is not necessary, because the pointer on which i is going to be added already exists:

   +---+---+---+---+---+---+---+---+
   |   |   |   |   |   |   |   |   |   int[8]
   +---+---+---+---+---+---+---+---+
     ^           ^               ^
     |           |               |
     |           |               |
   +-|-+         |               |
x: | | |    x+3  |          x+7  |     int*
   +---+

Note that in the depicted case, x is a pointer variable (discernible by the small box next to x), but it could just as well be the result of a function returning a pointer (or any other expression of type T*).

Indexing operator

Since the syntax *(x+i) is a bit clumsy, C++ provides the alternative syntax x[i]:

std::cout << x[3] << ", " << x[7] << std::endl;

Due to the fact that addition is commutative, the following code does exactly the same:

std::cout << 3[x] << ", " << 7[x] << std::endl;

The definition of the indexing operator leads to the following interesting equivalence:

&x[i]  ==  &*(x+i)  ==  x+i

However, &x[0] is generally not equivalent to x. The former is a pointer, the latter an array. Only when the context triggers array-to-pointer decay can x and &x[0] be used interchangeably. For example:

T* p = &array[0];  // rewritten as &*(array+0), decay happens due to the addition
T* q = array;      // decay happens due to the assignment

On the first line, the compiler detects an assignment from a pointer to a pointer, which trivially succeeds. On the second line, it detects an assignment from an array to a pointer. Since this is meaningless (but pointer to pointer assignment makes sense), array-to-pointer decay kicks in as usual.

Ranges

An array of type T[n] has n elements, indexed from 0 to n-1; there is no element n. And yet, to support half-open ranges (where the beginning is inclusive and the end is exclusive), C++ allows the computation of a pointer to the (non-existent) n-th element, but it is illegal to dereference that pointer:

   +---+---+---+---+---+---+---+---+....
x: |   |   |   |   |   |   |   |   |   .   int[8]
   +---+---+---+---+---+---+---+---+....
     ^                               ^
     |                               |
     |                               |
     |                               |
x+0  |                          x+8  |     int*

For example, if you want to sort an array, both of the following would work equally well:

std::sort(x + 0, x + n);
std::sort(&x[0], &x[0] + n);

Note that it is illegal to provide &x[n] as the second argument since this is equivalent to &*(x+n), and the sub-expression *(x+n) technically invokes undefined behavior in C++ (but not in C99).

Also note that you could simply provide x as the first argument. That is a little too terse for my taste, and it also makes template argument deduction a bit harder for the compiler, because in that case the first argument is an array but the second argument is a pointer. (Again, array-to-pointer decay kicks in.)

Controlling fps with requestAnimationFrame?

These are all good ideas in theory, until you go deep. The problem is you can't throttle an RAF without de-synchronizing it, defeating it's very purpose for existing. So you let it run at full-speed, and update your data in a separate loop, or even a separate thread!

Yes, I said it. You can do multi-threaded JavaScript in the browser!

There are two methods I know that work extremely well without jank, using far less juice and creating less heat. Accurate human-scale timing and machine efficiency are the net result.

Apologies if this is a little wordy, but here goes...


Method 1: Update data via setInterval, and graphics via RAF.

Use a separate setInterval for updating translation and rotation values, physics, collisions, etc. Keep those values in an object for each animated element. Assign the transform string to a variable in the object each setInterval 'frame'. Keep these objects in an array. Set your interval to your desired fps in ms: ms=(1000/fps). This keeps a steady clock that allows the same fps on any device, regardless of RAF speed. Do not assign the transforms to the elements here!

In a requestAnimationFrame loop, iterate through your array with an old-school for loop-- do not use the newer forms here, they are slow!

for(var i=0; i<sprite.length-1; i++){  rafUpdate(sprite[i]);  }

In your rafUpdate function, get the transform string from your js object in the array, and its elements id. You should already have your 'sprite' elements attached to a variable or easily accessible through other means so you don't lose time 'get'-ing them in the RAF. Keeping them in an object named after their html id's works pretty good. Set that part up before it even goes into your SI or RAF.

Use the RAF to update your transforms only, use only 3D transforms (even for 2d), and set css "will-change: transform;" on elements that will change. This keeps your transforms synced to the native refresh rate as much as possible, kicks in the GPU, and tells the browser where to concentrate most.

So you should have something like this pseudocode...

// refs to elements to be transformed, kept in an array
var element = [
   mario: document.getElementById('mario'),
   luigi: document.getElementById('luigi')
   //...etc.
]

var sprite = [  // read/write this with SI.  read-only from RAF
   mario: { id: mario  ....physics data, id, and updated transform string (from SI) here  },
   luigi: {  id: luigi  .....same  }
   //...and so forth
] // also kept in an array (for efficient iteration)

//update one sprite js object
//data manipulation, CPU tasks for each sprite object
//(physics, collisions, and transform-string updates here.)
//pass the object (by reference).
var SIupdate = function(object){
  // get pos/rot and update with movement
  object.pos.x += object.mov.pos.x;  // example, motion along x axis
  // and so on for y and z movement
  // and xyz rotational motion, scripted scaling etc

  // build transform string ie
  object.transform =
   'translate3d('+
     object.pos.x+','+
     object.pos.y+','+
     object.pos.z+
   ') '+

   // assign rotations, order depends on purpose and set-up. 
   'rotationZ('+object.rot.z+') '+
   'rotationY('+object.rot.y+') '+
   'rotationX('+object.rot.x+') '+

   'scale3d('.... if desired
  ;  //...etc.  include 
}


var fps = 30; //desired controlled frame-rate


// CPU TASKS - SI psuedo-frame data manipulation
setInterval(function(){
  // update each objects data
  for(var i=0; i<sprite.length-1; i++){  SIupdate(sprite[i]);  }
},1000/fps); //  note ms = 1000/fps


// GPU TASKS - RAF callback, real frame graphics updates only
var rAf = function(){
  // update each objects graphics
  for(var i=0; i<sprite.length-1; i++){  rAF.update(sprite[i])  }
  window.requestAnimationFrame(rAF); // loop
}

// assign new transform to sprite's element, only if it's transform has changed.
rAF.update = function(object){     
  if(object.old_transform !== object.transform){
    element[object.id].style.transform = transform;
    object.old_transform = object.transform;
  }
} 

window.requestAnimationFrame(rAF); // begin RAF

This keeps your updates to the data objects and transform strings synced to desired 'frame' rate in the SI, and the actual transform assignments in the RAF synced to GPU refresh rate. So the actual graphics updates are only in the RAF, but the changes to the data, and building the transform string are in the SI, thus no jankies but 'time' flows at desired frame-rate.


Flow:

[setup js sprite objects and html element object references]

[setup RAF and SI single-object update functions]

[start SI at percieved/ideal frame-rate]
  [iterate through js objects, update data transform string for each]
  [loop back to SI]

[start RAF loop]
  [iterate through js objects, read object's transform string and assign it to it's html element]
  [loop back to RAF]

Method 2. Put the SI in a web-worker. This one is FAAAST and smooth!

Same as method 1, but put the SI in web-worker. It'll run on a totally separate thread then, leaving the page to deal only with the RAF and UI. Pass the sprite array back and forth as a 'transferable object'. This is buko fast. It does not take time to clone or serialize, but it's not like passing by reference in that the reference from the other side is destroyed, so you will need to have both sides pass to the other side, and only update them when present, sort of like passing a note back and forth with your girlfriend in high-school.

Only one can read and write at a time. This is fine so long as they check if it's not undefined to avoid an error. The RAF is FAST and will kick it back immediately, then go through a bunch of GPU frames just checking if it's been sent back yet. The SI in the web-worker will have the sprite array most of the time, and will update positional, movement and physics data, as well as creating the new transform string, then pass it back to the RAF in the page.

This is the fastest way I know to animate elements via script. The two functions will be running as two separate programs, on two separate threads, taking advantage of multi-core CPU's in a way that a single js script does not. Multi-threaded javascript animation.

And it will do so smoothly without jank, but at the actual specified frame-rate, with very little divergence.


Result:

Either of these two methods will ensure your script will run at the same speed on any PC, phone, tablet, etc (within the capabilities of the device and the browser, of course).

Getting the closest string match

If you're doing this in the context of a search engine or frontend against a database, you might consider using a tool like Apache Solr, with the ComplexPhraseQueryParser plugin. This combination allows you to search against an index of strings with the results sorted by relevance, as determined by Levenshtein distance.

We've been using it against a large collection of artists and song titles when the incoming query may have one or more typos, and it's worked pretty well (and remarkably fast considering the collections are in the millions of strings).

Additionally, with Solr, you can search against the index on demand via JSON, so you won't have to reinvent the solution between the different languages you're looking at.

"Warning: iPhone apps should include an armv6 architecture" even with build config set

Wow, I update/submit apps about every 6 months. Every time I do this I have to learn the "new" way to do it...

Same problems as described above when running iOS 5.1, and Xcode 4.3.2

Thanks for the posts! I spent a while updating all of the project settings to armv6, armv7, but no joy. When I set "build active architecture only" to No I got a build error about putting both objects in the same directory.

Fortunately, I noticed you guys were modifying the target build settings instead. This is what finally worked (armv6, armv7, and setting "build active architecture only" to No under the Target build Settings). As a disclaimer, I had already set all of the architectures to armv6, armv7 in the project settings too.

Anyway, thanks for the help, Brent

conflicting types error when compiling c program using gcc

To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.

A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

My problem were different indices, the following code solved my problem.

df1.reset_index(drop=True, inplace=True)
df2.reset_index(drop=True, inplace=True)
df = pd.concat([df1, df2], axis=1)

permission denied - php unlink

You'll first require to close the file using fclose($handle); it's not deleting because the file is in use. So first close the file and then try.

$date + 1 year?

Try: $futureDate=date('Y-m-d',strtotime('+1 year',$startDate));

"column not allowed here" error in INSERT statement

While inserting the data, we have to used character string delimiter (' '). And, you missed it (' ') while inserting values which is the reason of your error message. The correction of code is given below:

INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');

How to save a list to a file and read it as a list type?

Although the accepted answer works, you should really be using python's json module:

import json

score=[1,2,3,4,5]

with open("file.json", 'w') as f:
    # indent=2 is not needed but makes the file human-readable
    json.dump(score, f, indent=2) 

with open("file.json", 'r') as f:
    score = json.load(f)

print(score)

Advantages:

  1. json is a widely adopted and standardized data format, so non-python programs can easily read and understand the json files
  2. json files are human-readable
  3. Any nested or non-nested list/dictionary structure can be saved to a json file (as long as all the contents are serializable).

Disadvantages:

  1. The data is stored in plain-text (ie it's uncompressed), which makes it a slow and bloated option for large amounts of data (ie probably a bad option for storing large numpy arrays, that's what hdf5 is for).
  2. The contents of a list/dictionary need to be serializable before you can save it as a json, so while you can save things like strings, ints, and floats, you'll need to write custom serialization and deserialization code to save objects, classes, and functions

When to use json vs pickle:

  • If you want to store something you know you're only ever going to use in the context of a python program, use pickle
  • If you need to save data that isn't serializable by default (ie objects), save yourself the trouble and use pickle.
  • If you need a platform agnostic solution, use json
  • If you need to be able to inspect and edit the data directly, use json

Common use cases:

  • Configuration files (for example, node.js uses a package.json file to track project details, dependencies, scripts, etc ...)
  • Most REST APIs use json to transmit and receive data
  • Data that requires a nested list/dictionary structure, or requires variable length lists/dicts
  • Can be an alternative to csv, xml or yaml files

How to make a Generic Type Cast function

While probably not as clean looking as the IConvertible approach, you could always use the straightforward checking typeof(T) to return a T:

public static T ReturnType<T>(string stringValue)
{
    if (typeof(T) == typeof(int))
        return (T)(object)1;
    else if (typeof(T) == typeof(FooBar))
        return (T)(object)new FooBar(stringValue);
    else
        return default(T);
}

public class FooBar
{
    public FooBar(string something)
    {}
}

How can a windows service programmatically restart itself?

The problem with shelling out to a batch file or EXE is that a service may or may not have the permissions required to run the external app.

The cleanest way to do this that I have found is to use the OnStop() method, which is the entry point for the Service Control Manager. Then all your cleanup code will run, and you won't have any hanging sockets or other processes, assuming your stop code is doing its job.

To do this you need to set a flag before you terminate that tells the OnStop method to exit with an error code; then the SCM knows that the service needs to be restarted. Without this flag you won't be able to stop the service manually from the SCM. This also assumes you have set up the service to restart on an error.

Here's my stop code:

...

bool ABORT;

protected override void OnStop()
{
    Logger.log("Stopping service");
    WorkThreadRun = false;
    WorkThread.Join();
    Logger.stop();
    // if there was a problem, set an exit error code
    // so the service manager will restart this
    if(ABORT)Environment.Exit(1);
}

If the service runs into a problem and needs to restart, I launch a thread that stops the service from the SCM. This allows the service to clean up after itself:

...

if(NeedToRestart)
{
    ABORT = true;
    new Thread(RestartThread).Start();
}

void RestartThread()
{
    ServiceController sc = new ServiceController(ServiceName);
    try
    {
        sc.Stop();
    }
    catch (Exception) { }
}

Submit a form in a popup, and then close the popup

I have executed the code in my machine its working for IE and FF also.

function closeSelf(){
    // do something

    if(condition satisfied){
       alert("conditions satisfied, submiting the form.");
       document.forms['certform'].submit();
       window.close();
    }else{
       alert("conditions not satisfied, returning to form");    
    }
}


<form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
       <div>Certificate 1: <input type="file" name="cert1"/></div>
       <div>Certificate 2: <input type="file" name="cert2"/></div>
       <div>Certificate 3: <input type="file" name="cert3"/></div>

       // change the submit button to normal button
       <div><input type="button" value="Upload"  onclick="closeSelf();"/></div>
</form>

How can I count the rows with data in an Excel sheet?

Try this scenario:

Array = A1:C7. A1-A3 have values, B2-B6 have value and C1, C3 and C6 have values.

To get a count of the number of rows add a column D (you can hide it after formulas are set up) and in D1 put formula =If(Sum(A1:C1)>0,1,0). Copy the formula from D1 through D7 (for others searching who are not excel literate, the numbers in the sum formula will change to the row you are on and this is fine).

Now in C8 make a sum formula that adds up the D column and the answer should be 6. For visually pleasing purposes hide column D.

How to change DatePicker dialog color for Android 5.0

Give this a try.

The code

new DatePickerDialog(MainActivity.this, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        //DO SOMETHING
    }
}, 2015, 02, 26).show();

The Style In your styles.xml file

EDIT - Changed theme to Theme.AppCompat.Light.Dialog as suggested

<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">@color/blue_500</item>
</style>

asp.net mvc3 return raw html to view

In controller you can use MvcHtmlString

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string rawHtml = "<HTML></HTML>";
        ViewBag.EncodedHtml = MvcHtmlString.Create(rawHtml);
        return View();
    }
}

In your View you can simply use that dynamic property which you set in your Controller like below

<div>
        @ViewBag.EncodedHtml
</div>

How to disable compiler optimizations in gcc?

You can disable optimizations if you pass -O0 with the gcc command-line.

E.g. to turn a .C file into a .S file call:

gcc -O0 -S test.c

A formula to copy the values from a formula to another column

What about trying with VLOOKUP? The syntax is:

=VLOOKUP(cell you want to copy, range you want to copy, 1, FALSE).

It should do the trick.

Why do we have to override the equals() method in Java?

To answer your question, firstly I would strongly recommend looking at the Documentation.

Without overriding the equals() method, it will act like "==". When you use the "==" operator on objects, it simply checks to see if those pointers refer to the same object. Not if their members contain the same value.

We override to keep our code clean, and abstract the comparison logic from the If statement, into the object. This is considered good practice and takes advantage of Java's heavily Object Oriented Approach.

How to initialize struct?

You use an implicit operator that converts the string value to a struct value:

public struct MyStruct {
  public string s;
  public int length;

  public static implicit operator MyStruct(string value) {
    return new MyStruct() { s = value, length = value.Length };
  }

}

Example:

MyStruct myStruct = "Lol";
Console.WriteLine(myStruct.s);
Console.WriteLine(myStruct.length);

Output:

Lol
3

Delete multiple rows by selecting checkboxes using PHP

Something that sometimes crops up you may/maynot be aware of

Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE

As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?

If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?

Reference an Element in a List of Tuples

You also can use itemgetter operator:

from operator import itemgetter
my_tuples = [('c','r'), (2, 3), ('e'), (True, False),('text','sample')]
map(itemgetter(0), my_tuples)

Handling file renames in git

Let's think about your files from git perspective.

Keep in mind git doesn't track any metadata about your files

Your repository has (among others)

$ cd repo
$ ls
...
iphone.css
...

and it is under git control:

$ git ls-files --error-unmatch iphone.css &>/dev/null && echo file is tracked
file is tracked

Test this with:

$ touch newfile
$ git ls-files --error-unmatch newfile &>/dev/null && echo file is tracked
(no output, it is not tracked)
$ rm newfile

When you do

$ mv iphone.css mobile.css

From git perspective,

  • there is no iphone.css (it is deleted -git warns about that-).
  • there is a new file mobile.css.
  • Those files are totally unrelated.

So, git advises about files it already knows (iphone.css) and new files it detects (mobile.css) but only when files are in index or HEAD git starts to check their contents.

At this moment, neither "iphone.css deletion" nor mobile.css are on index.

Add iphone.css deletion to index

$ git rm iphone.css

git tells you exactly what has happened: (iphone.css is deleted. Nothing more happened)

then add new file mobile.css

$ git add mobile.css

This time both deletion and new file are on index. Now git detects context are the same and expose it as a rename. In fact if files are 50% similar it will detect that as a rename, that let you change mobile.css a bit while keeping the operation as a rename.

See this is reproducible on git diff. Now that your files are on index you must use --cached. Edit mobile.css a bit, add that to index and see the difference between:

$ git diff --cached 

and

$ git diff --cached -M

-M is the "detect renames" option for git diff. -M stands for -M50% (50% or more similarity will make git express it as a rename) but you can reduce this to -M20% (20%) if you edit mobile.css a lot.

Can't update data-attribute value

Use that instead, if you wish to change the attribute data-num of node element, not of data object:

DEMO

$('#changeData').click(function (e) { 
    e.preventDefault();
    var num = +$('#foo').attr("data-num");
    console.log(num);
    num = num + 1;
    console.log(num);
    $('#foo').attr('data-num', num);
});

PS: but you should use the data() object in virtually all cases, but not all...

Ruby on Rails form_for select field with class

This work for me

<%= f.select :status, [["Single", "single"], ["Married", "married"], ["Engaged", "engaged"], ["In a Relationship", "relationship"]], {}, {class: "form-control"} %>

Adding value labels on a matplotlib bar chart

Building off the above (great!) answer, we can also make a horizontal bar plot with just a few adjustments:

# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]

freq_series = pd.Series(frequencies)

y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0, 
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount ($)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300) # expand xlim to make labels easier to read

rects = ax.patches

# For each bar: Place a label
for rect in rects:
    # Get X and Y placement of label from rect.
    x_value = rect.get_width()
    y_value = rect.get_y() + rect.get_height() / 2

    # Number of points between bar and label. Change to your liking.
    space = 5
    # Vertical alignment for positive values
    ha = 'left'

    # If value of bar is negative: Place label left of bar
    if x_value < 0:
        # Invert space to place label to the left
        space *= -1
        # Horizontally align label at right
        ha = 'right'

    # Use X value as label and format number with one decimal place
    label = "{:.1f}".format(x_value)

    # Create annotation
    plt.annotate(
        label,                      # Use `label` as label
        (x_value, y_value),         # Place label at end of the bar
        xytext=(space, 0),          # Horizontally shift label by `space`
        textcoords="offset points", # Interpret `xytext` as offset in points
        va='center',                # Vertically center label
        ha=ha)                      # Horizontally align label differently for
                                    # positive and negative values.

plt.savefig("image.png")

horizontal bar plot with annotations

When do I need to do "git pull", before or after "git add, git commit"?

Best way for me is:

  1. create new branch, checkout to it
  2. create or modify files, git add, git commit
  3. back to master branch and do pull from remote (to get latest master changes)
  4. merge newly created branch with master
  5. remove newly created branch
  6. push master to remote

Or you can push newly created branch on remote and merge there (if you do it this way, at the end you need to pull from remote master)

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

ESLint - "window" is not defined. How to allow global variables in package.json

I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:

Make sure ESLint is not run with the --no-inline-config flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):

/* eslint-env browser */

This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.

There are plenty of environments, and you can declare more than one at the same time, for example, in-line:

/* eslint-env browser, node */

If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.

From their docs:

An environment defines global variables that are predefined. The available environments are:

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node and Browser.

[...]

Besides environments, you can make it ignore anything you want. If it warns you about using console.log() but you don't want to be warned about it, just inline:

/* eslint-disable no-console */

You can see the list of all rules, including recommended rules to have for best coding practices.

Can a local variable's memory be accessed outside its scope?

After returning from a function, all identifiers are destroyed instead of kept values in a memory location and we can not locate the values without having an identifier.But that location still contains the value stored by previous function.

So, here function foo() is returning the address of a and a is destroyed after returning its address. And you can access the modified value through that returned address.

Let me take a real world example:

Suppose a man hides money at a location and tells you the location. After some time, the man who had told you the money location dies. But still you have the access of that hidden money.

How to enter ssh password using bash?

Double check if you are not able to use keys.

Otherwise use expect:

#!/usr/bin/expect -f
spawn ssh [email protected]
expect "assword:"
send "mypassword\r"
interact

Group By Multiple Columns

.GroupBy(x => (x.MaterialID, x.ProductID))

Implementation difference between Aggregation and Composition in Java

I would use a nice UML example.

Take a university that has 1 to 20 different departments and each department has 1 to 5 professors. There is a composition link between a University and its' departments. There is an aggregation link between a department and its' professors.

Composition is just a STRONG aggregation, if the university is destroyed then the departments should also be destroyed. But we shouldn't kill the professors even if their respective departments disappear.

In java :

public class University {

     private List<Department> departments;

     public void destroy(){
         //it's composition, when I destroy a university I also destroy the departments. they cant live outside my university instance
         if(departments!=null)
             for(Department d : departments) d.destroy();
         departments.clean();
         departments = null;
     }
}

public class Department {

     private List<Professor> professors;
     private University university;

     Department(University univ){
         this.university = univ;
         //check here univ not null throw whatever depending on your needs
     }

     public void destroy(){
         //It's aggregation here, we just tell the professor they are fired but they can still keep living
         for(Professor p:professors)
             p.fire(this);
         professors.clean();
         professors = null;
     }
}

public class Professor {

     private String name;
     private List<Department> attachedDepartments;

     public void destroy(){

     }

     public void fire(Department d){
         attachedDepartments.remove(d);
     }
}

Something around this.

EDIT: an example as requested

public class Test
{
    public static void main(String[] args)
    {
        University university = new University();
        //the department only exists in the university
        Department dep = university.createDepartment();
        // the professor exists outside the university
        Professor prof = new Professor("Raoul");
        System.out.println(university.toString());
        System.out.println(prof.toString());

        dep.assign(prof);
        System.out.println(university.toString());
        System.out.println(prof.toString());
        dep.destroy();

        System.out.println(university.toString());
        System.out.println(prof.toString());

    }


}

University class

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class University {

    private List<Department> departments = new ArrayList<>();

    public Department createDepartment() {
        final Department dep = new Department(this, "Math");
        departments.add(dep);
        return dep;
    }

    public void destroy() {
        System.out.println("Destroying university");
        //it's composition, when I destroy a university I also destroy the departments. they cant live outside my university instance
        if (departments != null)
            departments.forEach(Department::destroy);
        departments = null;
    }

    @Override
    public String toString() {
        return "University{\n" +
                "departments=\n" + departments.stream().map(Department::toString).collect(Collectors.joining("\n")) +
                "\n}";
    }
}

Department class

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Department {

    private final String name;
    private List<Professor> professors = new ArrayList<>();
    private final University university;

    public Department(University univ, String name) {
        this.university = univ;
        this.name = name;
        //check here univ not null throw whatever depending on your needs
    }

    public void assign(Professor p) {
        //maybe use a Set here
        System.out.println("Department hiring " + p.getName());
        professors.add(p);
        p.join(this);
    }

    public void fire(Professor p) {
        //maybe use a Set here
        System.out.println("Department firing " + p.getName());
        professors.remove(p);
        p.quit(this);
    }

    public void destroy() {
        //It's aggregation here, we just tell the professor they are fired but they can still keep living
        System.out.println("Destroying department");
        professors.forEach(professor -> professor.quit(this));
        professors = null;
    }

    @Override
    public String toString() {
        return professors == null
                ? "Department " + name + " doesn't exists anymore"
                : "Department " + name + "{\n" +
                "professors=" + professors.stream().map(Professor::toString).collect(Collectors.joining("\n")) +
                "\n}";
    }
}

Professor class

import java.util.ArrayList;
import java.util.List;

public class Professor {

    private final String name;
    private final List<Department> attachedDepartments = new ArrayList<>();

    public Professor(String name) {
        this.name = name;
    }

    public void destroy() {

    }

    public void join(Department d) {
        attachedDepartments.add(d);
    }

    public void quit(Department d) {
        attachedDepartments.remove(d);
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Professor " + name + " working for " + attachedDepartments.size() + " department(s)\n";
    }
}

The implementation is debatable as it depends on how you need to handle creation, hiring deletion etc. Unrelevant for the OP

Implement Validation for WPF TextBoxes

I have implemented this validation. But you would be used code behind. It is too much easy and simplest way.

XAML: For name Validtion only enter character from A-Z and a-z.

<TextBox x:Name="first_name_texbox" PreviewTextInput="first_name_texbox_PreviewTextInput" >  </TextBox>

Code Behind.

private void first_name_texbox_PreviewTextInput ( object sender, TextCompositionEventArgs e )
{
    Regex regex = new Regex ( "[^a-zA-Z]+" );
    if ( regex.IsMatch ( first_name_texbox.Text ) )
    {
        MessageBox.Show("Invalid Input !");
    }
}

For Salary and ID validation, replace regex constructor passed value with [0-9]+. It means you can only enter number from 1 to infinite.

You can also define length with [0-9]{1,4}. It means you can only enter less then or equal to 4 digit number. This baracket means {at least,How many number}. By doing this you can define range of numbers in textbox.

May it help to others.

XAML:

Code Behind.

private void salary_texbox_PreviewTextInput ( object sender, TextCompositionEventArgs e )
{
    Regex regex = new Regex ( "[^0-9]+" );
    if ( regex.IsMatch ( salary_texbox.Text ) )
    {
        MessageBox.Show("Invalid Input !");
    }
}

How to get JSON Key and Value?

$.each(result, function(key, value) {
  console.log(key+ ':' + value);
});

Get source jar files attached to Eclipse for Maven-managed dependencies

overthink suggested using the setup in the pom:

<project>
...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-eclipse-plugin</artifactId>
            <configuration>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
                ... other stuff ...
            </configuration>
        </plugin>
    </plgins>
</build>
...

First i thought this still won't attach the javadoc and sources (as i tried unsuccessfully with that -DdownloadSources option before).

But surprise - the .classpath file IS getting its sources and javadoc attached when using the POM variant!

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Make sure you have the latest values in your gradle files. As of this writing:

  • buildToolsVersion "21.1.2"

  • dependencies { classpath 'com.android.tools.build:gradle:1.1.0' }

TextView - setting the text size programmatically doesn't seem to work

In My Case Used this Method:

public static float pxFromDp(float dp, Context mContext) {
    return dp * mContext.getResources().getDisplayMetrics().density;
}

Here Set TextView's TextSize Programatically :

textView.setTextSize(pxFromDp(18, YourActivity.this));

Keep Enjoying:)

If my interface must return Task what is the best way to have a no-operation implementation?

Task.Delay(0) as in the accepted answer was a good approach, as it is a cached copy of a completed Task.

As of 4.6 there's now Task.CompletedTask which is more explicit in its purpose, but not only does Task.Delay(0) still return a single cached instance, it returns the same single cached instance as does Task.CompletedTask.

The cached nature of neither is guaranteed to remain constant, but as implementation-dependent optimisations that are only implementation-dependent as optimisations (that is, they'd still work correctly if the implementation changed to something that was still valid) the use of Task.Delay(0) was better than the accepted answer.

Casting variables in Java

Casting in Java isn't magic, it's you telling the compiler that an Object of type A is actually of more specific type B, and thus gaining access to all the methods on B that you wouldn't have had otherwise. You're not performing any kind of magic or conversion when performing casting, you're essentially telling the compiler "trust me, I know what I'm doing and I can guarantee you that this Object at this line is actually an <Insert cast type here>." For example:

Object o = "str";
String str = (String)o;

The above is fine, not magic and all well. The object being stored in o is actually a string, and therefore we can cast to a string without any problems.

There's two ways this could go wrong. Firstly, if you're casting between two types in completely different inheritance hierarchies then the compiler will know you're being silly and stop you:

String o = "str";
Integer str = (Integer)o; //Compilation fails here

Secondly, if they're in the same hierarchy but still an invalid cast then a ClassCastException will be thrown at runtime:

Number o = new Integer(5);
Double n = (Double)o; //ClassCastException thrown here

This essentially means that you've violated the compiler's trust. You've told it you can guarantee the object is of a particular type, and it's not.

Why do you need casting? Well, to start with you only need it when going from a more general type to a more specific type. For instance, Integer inherits from Number, so if you want to store an Integer as a Number then that's ok (since all Integers are Numbers.) However, if you want to go the other way round you need a cast - not all Numbers are Integers (as well as Integer we have Double, Float, Byte, Long, etc.) And even if there's just one subclass in your project or the JDK, someone could easily create another and distribute that, so you've no guarantee even if you think it's a single, obvious choice!

Regarding use for casting, you still see the need for it in some libraries. Pre Java-5 it was used heavily in collections and various other classes, since all collections worked on adding objects and then casting the result that you got back out the collection. However, with the advent of generics much of the use for casting has gone away - it has been replaced by generics which provide a much safer alternative, without the potential for ClassCastExceptions (in fact if you use generics cleanly and it compiles with no warnings, you have a guarantee that you'll never get a ClassCastException.)

Angular - "has no exported member 'Observable'"

Try this:

npm install rxjs-compat --save

How to append to New Line in Node.js

It looks like you're running this on Windows (given your H://log.txt file path).

Try using \r\n instead of just \n.

Honestly, \n is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).

Create a rounded button / button with border-radius in Flutter

here is another solution

 Container(
                    height: MediaQuery.of(context).size.height * 0.10,
                    width: MediaQuery.of(context).size.width,
                    child: ButtonTheme(
                      minWidth: MediaQuery.of(context).size.width * 0.75,
                      child: RaisedButton(
                        shape: RoundedRectangleBorder(
                            borderRadius: new BorderRadius.circular(25.0),
                            side: BorderSide(color: Colors.blue)),
                        onPressed: () async {
                           // do something 
                        },
                        color: Colors.red[900],
                        textColor: Colors.white,
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text("Button Text,
                              style: TextStyle(fontSize: 24)),
                        ),
                      ),
                    ),
                  ),

DOS: find a string, if found then run another script

It's been awhile since I've done anything with batch files but I think that the following works:

find /c "string" file
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done

This is really a proof of concept; clean up as it suits your needs. The key is that find returns an errorlevel of 1 if string is not in file. We branch to notfound in this case otherwise we handle the found case.

HTML form with side by side input fields

You could use the {display: inline-flex;} this would produce this: inline-flex

Android activity life cycle - what are all these methods for?

Activity has six states

  • Created
  • Started
  • Resumed
  • Paused
  • Stopped
  • Destroyed

Activity lifecycle has seven methods

  • onCreate()
  • onStart()
  • onResume()
  • onPause()
  • onStop()
  • onRestart()
  • onDestroy()

activity life cycle

Situations

  • When open the app

    onCreate() --> onStart() -->  onResume()
    
  • When back button pressed and exit the app

    onPaused() -- > onStop() --> onDestory()
    
  • When home button pressed

    onPaused() --> onStop()
    
  • After pressed home button when again open app from recent task list or clicked on icon

    onRestart() --> onStart() --> onResume()
    
  • When open app another app from notification bar or open settings

    onPaused() --> onStop()
    
  • Back button pressed from another app or settings then used can see our app

    onRestart() --> onStart() --> onResume()
    
  • When any dialog open on screen

    onPause()
    
  • After dismiss the dialog or back button from dialog

    onResume()
    
  • Any phone is ringing and user in the app

    onPause() --> onResume() 
    
  • When user pressed phone's answer button

    onPause()
    
  • After call end

    onResume()
    
  • When phone screen off

    onPaused() --> onStop()
    
  • When screen is turned back on

    onRestart() --> onStart() --> onResume()
    

Git merge develop into feature branch outputs "Already up-to-date" while it's not

Initially my repo said "Already up to date."

MINGW64 (feature/Issue_123) 
$ git merge develop

Output:

Already up to date.

But the code is not up to date & it is showing some differences in some files.

MINGW64 (feature/Issue_123)
$ git diff develop

Output:

diff --git 
a/src/main/database/sql/additional/pkg_etl.sql 
b/src/main/database/sql/additional/pkg_etl.sql
index ba2a257..1c219bb 100644
--- a/src/main/database/sql/additional/pkg_etl.sql
+++ b/src/main/database/sql/additional/pkg_etl.sql

However, merging fixes it.

MINGW64 (feature/Issue_123)
$ git merge origin/develop

Output:

Updating c7c0ac9..09959e3
Fast-forward
3 files changed, 157 insertions(+), 92 deletions(-)

Again I have confirmed this by using diff command.

MINGW64 (feature/Issue_123)
$ git diff develop

No differences in the code now!

How to concatenate two numbers in javascript?

Use "" + 5 + 6 to force it to strings. This works with numerical variables too:

_x000D_
_x000D_
var a = 5;_x000D_
var b = 6;_x000D_
console.log("" + a + b);
_x000D_
_x000D_
_x000D_

Why must wait() always be in synchronized block

@Rollerball is right. The wait() is called, so that the thread can wait for some condition to occur when this wait() call happens, the thread is forced to give up its lock.
To give up something, you need to own it first. Thread needs to own the lock first. Hence the need to call it inside a synchronized method/block.

Yes, I do agree with all the above answers regarding the potential damages/inconsistencies if you did not check the condition within synchronized method/block. However as @shrini1000 has pointed out, just calling wait() within synchronized block will not avert this inconsistency from happening.

Here is a nice read..

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

With my Android 5 tablet, every time I attempt to use adb, to install a signed release apk, I get the [INSTALL_FAILED_ALREADY_EXISTS] error.

I have to uninstall the debug package first. But, I cannot uninstall using the device's Application Manager!

If do uninstall the debug version with the Application Manager, then I have to re-run the debug build variant from Android Studio, then uninstall it using adb uninstall com.example.mypackagename

Finally, I can use adb install myApp.apk to install the signed release apk.

UITableView Separator line

Set the separatorStyle of the tableview to UITableViewCellSeparatorStyleNone. Add your separator image as subview to each cell and set the frame properly.

How to assign bean's property an Enum value in Spring config file?

I know this is a really old question, but in case someone is looking for the newer way to do this, use the spring util namespace:

<util:constant static-field="my.pkg.types.MyEnumType.TYPE1" />

As described in the spring documentation.

Constraint Layout Vertical Align Center

Two buttons one centered one below to the left of it

Showing it graphically.

Centering on parent is done by constraining both sides to the parent. You can the constrain additional objects off of the centered object.

Note. Each arrow represents a "app:layout_constraintXXX_toYYY=" attribute. (6 in the picture)

How do I add BundleConfig.cs to my project?

BundleConfig is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)

To add this file, first you need to add the Microsoft.AspNet.Web.Optimization nuget package to your web project:

Install-Package Microsoft.AspNet.Web.Optimization

Then under the App_Start folder create a new cs file called BundleConfig.cs. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):

using System.Web;
using System.Web.Optimization;

namespace CodeRepository.Web
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

Then modify your Global.asax and add a call to RegisterBundles() in Application_Start():

using System.Web.Optimization;

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

Programmatically Creating UILabel

Does the following work ?

UIFont * customFont = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
NSString * text = [self fromSender];

CGSize labelSize = [text sizeWithFont:customFont constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];

UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, labelSize.width, labelSize.height)];
fromLabel.text = text;
fromLabel.font = customFont;
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.minimumScaleFactor = 10.0f/12.0f;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];

edit : I believe you may encounter a problem using both adjustsFontSizeToFitWidth and minimumScaleFactor. The former states that you also needs to set a minimumFontWidth (otherwhise it may shrink to something quite unreadable according to my test), but this is deprecated and replaced by the later.

edit 2 : Nevermind, outdated documentation. adjustsFontSizeToFitWidth needs minimumScaleFactor, just be sure no to pass it 0 as a minimumScaleFactor (integer division, 10/12 return 0). Small change on the baselineAdjustment value too.

Full-screen iframe with a height of 100%

http://embedresponsively.com/

This is a great resource and has worked very well, the few times I've used it. Creates the following code....

<style>
.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } 
.embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
</style>
<div class='embed-container'>
<iframe src='http://player.vimeo.com/video/66140585' frameborder='0' webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
</div>

Delete empty lines using sed

sed '/^$/d' should be fine, are you expecting to modify the file in place? If so you should use the -i flag.

Maybe those lines are not empty, so if that's the case, look at this question Remove empty lines from txtfiles, remove spaces from start and end of line I believe that's what you're trying to achieve.

How to set a cell to NaN in a pandas dataframe

df.replace('columnvalue',np.NaN,inplace=True)

Regular Expression to match only alphabetic characters

This will match one or more alphabetical characters:

/^[a-z]+$/

You can make it case insensitive using:

/^[a-z]+$/i

or:

/^[a-zA-Z]+$/

How can I get Git to follow symlinks?

This is a pre-commit hook which replaces the symlink blobs in the index, with the content of those symlinks.

Put this in .git/hooks/pre-commit, and make it executable:

#!/bin/sh
# (replace "find ." with "find ./<path>" below, to work with only specific paths)

# (these lines are really all one line, on multiple lines for clarity)
# ...find symlinks which do not dereference to directories...
find . -type l -exec test '!' -d {} ';' -print -exec sh -c \
# ...remove the symlink blob, and add the content diff, to the index/cache
    'git rm --cached "$1"; diff -au /dev/null "$1" | git apply --cached -p1 -' \
# ...and call out to "sh".
    "process_links_to_nondir" {} ';'

# the end

Notes

We use POSIX compliant functionality as much as possible; however, diff -a is not POSIX compliant, possibly among other things.

There may be some mistakes/errors in this code, even though it was tested somewhat.

Change HTML email body font type and size in VBA

I did a little research and was able to write this code:

strbody = "<BODY style=font-size:11pt;font-family:Calibri>Good Morning;<p>We have completed our main aliasing process for today.  All assigned firms are complete.  Please feel free to respond with any questions.<p>Thank you.</BODY>"

apparently by setting the "font-size=11pt" instead of setting the font size <font size=5>, It allows you to select a specific font size like you normally would in a text editor, as opposed to selecting a value from 1-7 like my code was originally.

This link from simpLE MAn gave me some good info.

javax.naming.NoInitialContextException - Java

If working on EJB client library:

You need to mention the argument for getting the initial context.

InitialContext ctx = new InitialContext();

If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:

Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");

InitialContext ctx = new InitialContext(props);

URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.

The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.

How to validate white spaces/empty spaces? [Angular 2]

After lots of trial i found [a-zA-Z\\s]* for Alphanumeric with white space

Example:

New York

New Delhi

What do column flags mean in MySQL Workbench?

This exact question is answered on mySql workbench-faq:

Hover over an acronym to view a description, and see the Section 8.1.11.2, “The Columns Tab” and MySQL CREATE TABLE documentation for additional details.

That means hover over an acronym in the mySql Workbench table editor.

Section 8.1.11.2, “The Columns Tab”

How can I delete a query string parameter in JavaScript?

From what I can see, none of the above can handle normal parameters and array parameters. Here's one that does.

function removeURLParameter(param, url) {
    url = decodeURI(url).split("?");
    path = url.length == 1 ? "" : url[1];
    path = path.replace(new RegExp("&?"+param+"\\[\\d*\\]=[\\w]+", "g"), "");
    path = path.replace(new RegExp("&?"+param+"=[\\w]+", "g"), "");
    path = path.replace(/^&/, "");
    return url[0] + (path.length
        ? "?" + path
        : "");
}

function addURLParameter(param, val, url) {
    if(typeof val === "object") {
        // recursively add in array structure
        if(val.length) {
            return addURLParameter(
                param + "[]",
                val.splice(-1, 1)[0],
                addURLParameter(param, val, url)
            )
        } else {
            return url;
        }
    } else {
        url = decodeURI(url).split("?");
        path = url.length == 1 ? "" : url[1];
        path += path.length
            ? "&"
            : "";
        path += decodeURI(param + "=" + val);
        return url[0] + "?" + path;
    }
}

How to use it:

url = location.href;
    -> http://example.com/?tags[]=single&tags[]=promo&sold=1

url = removeURLParameter("sold", url)
    -> http://example.com/?tags[]=single&tags[]=promo

url = removeURLParameter("tags", url)
    -> http://example.com/

url = addURLParameter("tags", ["single", "promo"], url)
    -> http://example.com/?tags[]=single&tags[]=promo

url = addURLParameter("sold", 1, url)
    -> http://example.com/?tags[]=single&tags[]=promo&sold=1

Of course, to update a parameter, just remove then add. Feel free to make a dummy function for it.

Add image in title bar

you should be searching about how to add favicon.ico . You can try adding favicon.ico directly in your html pages like this

<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="http://www.example.com/favicon.png" />

Or you can update that in your webserver. It is advised to add in your webserver as you don't need to add this in each of your html pages (assuming no includes).

To add in your apache place the favicon.ico in your root website director and add this in httpd.conf

AddType image/x-icon .ico

Where can I read the Console output in Visual Studio 2015

in the "Ouput Window". you can usually do CTRL-ALT-O to make it visible. Or through menus using View->Output.

How do I add slashes to a string in Javascript?

if (!String.prototype.hasOwnProperty('addSlashes')) {
    String.prototype.addSlashes = function() {
        return this.replace(/&/g, '&amp;') /* This MUST be the 1st replacement. */
             .replace(/'/g, '&apos;') /* The 4 other predefined entities, required. */
             .replace(/"/g, '&quot;')
             .replace(/\\/g, '\\\\')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;').replace(/\u0000/g, '\\0');
        }
}

Usage: alert(str.addSlashes());

ref: https://stackoverflow.com/a/9756789/3584667

What is the significance of load factor in HashMap?

I would pick a table size of n * 1.5 or n + (n >> 1), this would give a load factor of .66666~ without division, which is slow on most systems, especially on portable systems where there is no division in the hardware.

How to handle static content in Spring MVC?

The URLRewrite is sort of a "hack" if you want to call it that. What it comes down to is, you're re-inventing the wheel; as there are already existing solutions. Another thing to remember is Http Server = Static content & App server = dynamic content (this is how they were designed). By delegating the appropriate responsibilities to each server you maximize efficiency... but now-a-days this is probably only a concern in a performance critical environments and something like Tomcat would most likely work well in both roles most of the time; but it is still something to keep in mind none the less.

Browser: Identifier X has already been declared

The problem solved when I don't use any declaration like var, let or const

Adding a line break in MySQL INSERT INTO text

  1. You have to replace \n with <br/> before inset into database.

    $data = str_replace("\n", "<br/>", $data);

    In this case in database table you will see <br/> instead of new line.

    e.g.

    First Line
    Second Line

    will look like:

    First Line<br/>Second Line

  2. Another way to view data with new line. First read data from database. And then replace \n with <br/> e.g. :

    echo $data;
    $data = str_replace("\n", "<br/>", $data);
    echo "<br/><br/>" . $data;

    output:

    First Line Second Line

    First Line
    Second Line


    You will find details about function str_replace() here: http://php.net/manual/en/function.str-replace.php

<embed> vs. <object>

Embed is not a standard tag, though object is. Here's an article that looks like it will help you, since it seems the situation is not so simple. An example for PDF is included.

map vs. hash_map in C++

hash_map was a common extension provided by many library implementations. That is exactly why it was renamed to unordered_map when it was added to the C++ standard as part of TR1. map is generally implemented with a balanced binary tree like a red-black tree (implementations vary of course). hash_map and unordered_map are generally implemented with hash tables. Thus the order is not maintained. unordered_map insert/delete/query will be O(1) (constant time) where map will be O(log n) where n is the number of items in the data structure. So unordered_map is faster, and if you don't care about the order of the items should be preferred over map. Sometimes you want to maintain order (ordered by the key) and for that map would be the choice.

Passing arguments forward to another javascript function

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

ECMAScript ES6 added a new operator that lets you do this in a more practical way: ...Spread Operator.

Example without using the apply method:

_x000D_
_x000D_
function a(...args){_x000D_
  b(...args);_x000D_
  b(6, ...args, 8) // You can even add more elements_x000D_
}_x000D_
function b(){_x000D_
  console.log(arguments)_x000D_
}_x000D_
_x000D_
a(1, 2, 3)
_x000D_
_x000D_
_x000D_

Note This snippet returns a syntax error if your browser still uses ES5.

Editor's note: Since the snippet uses console.log(), you must open your browser's JS console to see the result - there will be no in-page result.

It will display this result:

Image of Spread operator arguments example

In short, the spread operator can be used for different purposes if you're using arrays, so it can also be used for function arguments, you can see a similar example explained in the official docs: Rest parameters

How can I set response header on express.js assets

There is at least one middleware on npm for handling CORS in Express: cors. [see @mscdex answer]

This is how to set custom response headers, from the ExpressJS DOC

res.set(field, [value])

Set header field to value

res.set('Content-Type', 'text/plain');

or pass an object to set multiple fields at once.

res.set({
  'Content-Type': 'text/plain',
  'Content-Length': '123',
  'ETag': '12345'
})

Aliased as

res.header(field, [value])

java.net.BindException: Address already in use: JVM_Bind <null>:80

The error:

java.net.BindException: Address already in use: JVM_Bind :80

means that another application is listening on port 80.

You can check which process is using this port by lsof command, e.g. sudo lsof -i:80. Then stop or kill it.

If won't help finding application running on the same port, the common mistake is the Tomcat misconfiguration.

For example by default Tomcat listens on port 8005 for SHUTDOWN command and if you set another Connector to listen on the same port, you'll get port conflict.

So please double check in server.xml whether these ports are different:

<Server port="8005" shutdown="SHUTDOWN">
    <Connector port="8983" protocol="HTTP/1.1"

Left Join With Where Clause

The where clause is filtering away rows where the left join doesn't succeed. Move it to the join:

SELECT  `settings`.*, `character_settings`.`value`
FROM    `settings`
LEFT JOIN 
       `character_settings` 
ON     `character_settings`.`setting_id` = `settings`.`id`
        AND `character_settings`.`character_id` = '1'  

ClientScript.RegisterClientScriptBlock?

Hai sridhar, I found an answer for your prob

ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);

change false to true

or try this

ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);

How to convert a Datetime string to a current culture datetime string

public static DateTime ConvertDateTime(string Date)
    {
        DateTime date=new DateTime();                        
        try
        {
            string CurrentPattern = Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;                
            string[] Split = new string[] {"-","/",@"\","."};
            string[] Patternvalue = CurrentPattern.Split(Split,StringSplitOptions.None);
            string[] DateSplit = Date.Split(Split,StringSplitOptions.None);
            string NewDate = "";
            if (Patternvalue[0].ToLower().Contains("d") == true && Patternvalue[1].ToLower().Contains("m")==true && Patternvalue[2].ToLower().Contains("y")==true)
            {
                NewDate = DateSplit[1] + "/" + DateSplit[0] + "/" + DateSplit[2];
            }
            else if (Patternvalue[0].ToLower().Contains("m") == true && Patternvalue[1].ToLower().Contains("d")==true && Patternvalue[2].ToLower().Contains("y")==true)
            {
                NewDate = DateSplit[0] + "/" + DateSplit[1] + "/" + DateSplit[2];
            }
            else if (Patternvalue[0].ToLower().Contains("y") == true && Patternvalue[1].ToLower().Contains("m")==true && Patternvalue[2].ToLower().Contains("d")==true)
            {
                NewDate = DateSplit[2] + "/" + DateSplit[0] + "/" + DateSplit[1];
            }
            else if (Patternvalue[0].ToLower().Contains("y") == true && Patternvalue[1].ToLower().Contains("d")==true && Patternvalue[2].ToLower().Contains("m")==true)
            {
                NewDate = DateSplit[2] + "/" + DateSplit[1] + "/" + DateSplit[0];
            }
            date = DateTime.Parse(NewDate, Thread.CurrentThread.CurrentCulture);
        }
        catch (Exception ex)
        {

        }
        finally
        {

        }

        return date;

    }

How to fix git error: RPC failed; curl 56 GnuTLS

Try to disable your IPV6 for that and disable after. I think this is your problem.

How do you rename a MongoDB database?

There is no mechanism to re-name databases. The currently accepted answer at time of writing is factually correct and offers some interesting background detail as to the excuse upstream, but offers no suggestions for replicating the behavior. Other answers point at copyDatabase, which is no longer an option as the functionality has been removed in 4.0. I've updated SERVER-701 with my notes and incredulity.

Equivalent behavior involves mongodump and mongorestore in a bit of a dance:

  1. Export your data, making note of the "namespaces" in use. For example, on one of my datasets, I have a collection with the namespace byzmcbehoomrfjcs9vlj.Analytics — that prefix (actually the database name) will be needed in the next step.

  2. Import your data, supplying --nsFrom and --nsTo arguments. (Documentation.) Continuing with my above hypothetical (and extremely unreadable) example, to restore to a more sensical name, I invoke:

mongorestore --archive=backup.agz --gzip --drop \
    --nsFrom 'byzmcbehoomrfjcs9vlj.*' --nsTo 'rita.*'

Some may also point at the --db argument to mongorestore, however this, too, is deprecated and triggers a warning against use on non-BSON folder backups with a completely erroneous suggestion to "use --nsInclude instead". The above namespace translation is equivalent to use of the --db option, and is the correct namespace manipulation setup to use as we are not attempting to filter what is being restored.

How to make a gap between two DIV within the same column

You can make use of the first-child selector

<div class="sidebar">
    <div class="box">
        <p> 
            Text is here
         </p>
     </div>
    <div class="box">
        <p> 
            Text is here
         </p>
     </div>
</div>

and in CSS

.box {
    padding: 10px;
    text-align: justify;
    margin-top: 20px;
}
.box:first-child {
    margin-top: none;
}

Example: http://jsbin.com/ozarot/edit#javascript,html,live

Default value for field in Django model

Set editable to False and default to your default value.

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

b = models.CharField(max_length=7, default='0000000', editable=False)

Also, your id field is unnecessary. Django will add it automatically.

How to increase the clickable area of a <a> tag button?

For me the padding solution wasn't good, as I was using border on the button, and would've been hard to put modify the markup to create an overlay for the touch area.

So what I did, is I just used the :before pseudo tag, and created an overlay, which was perfect in my case, as the click event propagated the same way.

button.my-button:before {
    content: '';
    position: absolute;
    width: 26px;
    height: 26px;
    top: -6px;
    left: -5px;
}

Convert Python dictionary to JSON array

If you are fine with non-printable symbols in your json, then add ensure_ascii=False to dumps call.

>>> json.dumps(your_data, ensure_ascii=False)

If ensure_ascii is false, then the return value will be a unicode instance subject to normal Python str to unicode coercion rules instead of being escaped to an ASCII str.

How Do I Take a Screen Shot of a UIView?

I think you may want renderInContext, not drawInContext. drawInContext is more a method you would override...

Note that it may not work in all views, specifically a year or so ago when I tried to use this with the live camera view it did not work.

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

Assuming that the mouse cursor should return to the document after window resize, we can create a callback-like behavior with onmouseover event. Don't forget that this solution may not work for touch-enabled screens as expected.

var resizeTimer;
var resized = false;
$(window).resize(function() {
   clearTimeout(resizeTimer);
   resizeTimer = setTimeout(function() {
       if(!resized) {
           resized = true;
           $(document).mouseover(function() {
               resized = false;
               // do something here
               $(this).unbind("mouseover");
           })
       }
    }, 500);
});

Make scrollbars only visible when a Div is hovered over?

.div::-webkit-scrollbar-thumb {
    background: transparent;
}

.div:hover::-webkit-scrollbar-thumb {
    background: red;
}

Double precision floating values in Python?

Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..

import random
from decimal import Decimal

GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)

Scala list concatenation, ::: vs ++

Always use :::. There are two reasons: efficiency and type safety.

Efficiency

x ::: y ::: z is faster than x ++ y ++ z, because ::: is right associative. x ::: y ::: z is parsed as x ::: (y ::: z), which is algorithmically faster than (x ::: y) ::: z (the latter requires O(|x|) more steps).

Type safety

With ::: you can only concatenate two Lists. With ++ you can append any collection to List, which is terrible:

scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)

++ is also easy to mix up with +:

scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

Not sure if this is the cause of the problem, but I got this issue only after installing JVM Monitor.

Uninstalling JVM Monitor solved the issue for me.

How do you synchronise projects to GitHub with Android Studio?

For existing project end existing repository with files:

git init
git remote add origin <.git>
git checkout -b master
git branch --set-upstream-to=origin/master master
git pull --allow-unrelated-histories

Format LocalDateTime with Timezone in Java8

LocalDateTime is a date-time without a time-zone. You specified the time zone offset format symbol in the format, however, LocalDateTime doesn't have such information. That's why the error occured.

If you want time-zone information, you should use ZonedDateTime.

DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
ZonedDateTime.now().format(FORMATTER);
=> "20140829 14:12:22.122000 +09"

Backup/Restore a dockerized PostgreSQL database

I had this issue while trying to use a db_dump to restore a db. I normally use dbeaver to restore- however received a psql dump, so had to figure out a method to restore using the docker container.

The methodology recommended by Forth and edited by Soviut worked for me:

cat your_dump.sql | docker exec -i your-db-container psql -U postgres -d dbname

(since this was a single db dump and not multiple db's i included the name)

However, in order to get this to work, I had to also go into the virtualenv that the docker container and project were in. This eluded me for a bit before figuring it out- as I was receiving the following docker error.

read unix @->/var/run/docker.sock: read: connection reset by peer

This can be caused by the file /var/lib/docker/network/files/local-kv.db .I don't know the accuracy of this statement: but I believe I was seeing this as I do not user docker locally, so therefore did not have this file, which it was looking for, using Forth's answer.

I then navigated to correct directory (with the project) activated the virtualenv and then ran the accepted answer. Boom, worked like a top. Hope this helps someone else out there!

How to get 0-padded binary representation of an integer in java?

Starting with Java 11, you can use the repeat(...) method:

"0".repeat(Integer.numberOfLeadingZeros(i) - 16) + Integer.toBinaryString(i)

Or, if you need 32-bit representation of any integer:

"0".repeat(Integer.numberOfLeadingZeros(i != 0 ? i : 1)) + Integer.toBinaryString(i)

How to change the font color in the textbox in C#?

RichTextBox will allow you to use html to specify the color. Another alternative is using a listbox and using the DrawItem event to draw how you would like. AFAIK, textbox itself can't be used in the way you're hoping.

How to work with string fields in a C struct?

While Richard's is what you want if you do want to go with a typedef, I'd suggest that it's probably not a particularly good idea in this instance, as you lose sight of it being a pointer, while not gaining anything.

If you were treating it a a counted string, or something with additional functionality, that might be different, but I'd really recommend that in this instance, you just get familiar with the 'standard' C string implementation being a 'char *'...

How to get thread id from a thread pool?

If your class inherits from Thread, you can use methods getName and setName to name each thread. Otherwise you could just add a name field to MyTask, and initialize it in your constructor.

How to automatically allow blocked content in IE?

Steps to configure IE to always allow blocked content:

  1. From Internet Explorer, select the Tools menu, then the Options...
  2. In the Internet Options dialog, select the Advanced tab...
  3. Scroll down until you see the Security options. Enable the checkbox "Allow active content to run in files on My Computer".

enter image description here

  1. Close the dialog, and quit Internet Explorer. The changes will take effect the next time you start IE.

The Blocked Content is a security feature of Windows XP Service Pack 2. If you do not have SP2 installed, then you will never see this message.

From: How To Allow Blocked Content on Internet Explorer

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

Convert java.time.LocalDate into java.util.Date type

You can use java.sql.Date.valueOf() method as:

Date date = java.sql.Date.valueOf(localDate);

No need to add time and time zone info here because they are taken implicitly.
See LocalDate to java.util.Date and vice versa simpliest conversion?

How do I install SciPy on 64 bit Windows?

Short answer: Windows 64 bit support is still work in progress at this time. The superpack will certainly not work on a 64-bits Python (but it should work fine on a 32 bits Python, even on Windows 64 bit).

The main issue with Windows 64 bit is that building with mingw-w64 is not stable at this point: it may be our's (NumPy developers) fault, Python's fault or mingw-w64. Most likely a combination of all those :). So you have to use proprietary compilers: anything other than the Microsoft compiler crashes NumPy randomly; for the Fortran compiler, ifort is the one to use. As of today, both NumPy and SciPy source code can be compiled with Visual Studio 2008 and ifort (all tests passing), but building it is still quite a pain, and not well supported by the NumPy build infrastructure.

m2eclipse error

In my case the problem was solved by Window -> Preferences -> Maven -> User Settings -> Update Settings. I don't know the problem cause at the first place.

JavaScript load a page on button click

Simple code to redirect page

<!-- html button designing and calling the event in javascript -->
<input id="btntest" type="button" value="Check" 
       onclick="window.location.href = 'http://www.google.com'" />

How to send email to multiple address using System.Net.Mail

My code to solve this problem:

private void sendMail()
{   
    //This list can be a parameter of metothd
    List<MailAddress> lst = new List<MailAddress>();

    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));


    try
    {


        MailMessage objeto_mail = new MailMessage();
        SmtpClient client = new SmtpClient();
        client.Port = 25;
        client.Host = "10.15.130.28"; //or SMTP name
        client.Timeout = 10000;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
        objeto_mail.From = new MailAddress("[email protected]");

        //add each email adress
        foreach (MailAddress m in lst)
        {
            objeto_mail.To.Add(m);
        }


        objeto_mail.Subject = "Sending mail test";
        objeto_mail.Body = "Functional test for automatic mail :-)";
        client.Send(objeto_mail);


    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

In order to avoid having to fully specify the git push command you could alternatively modify your git config file:

[remote "gerrit"]
    url = https://your.gerrit.repo:44444/repo
    fetch = +refs/heads/master:refs/remotes/origin/master
    push = refs/heads/master:refs/for/master

Now you can simply:

git fetch gerrit
git push gerrit

This is according to Gerrit

How to get array keys in Javascript?

For your input data:

let widthRange = new Array()
widthRange[46] = { min:0,  max:52 }
widthRange[61] = { min:52, max:70 }
widthRange[62] = { min:52, max:70 }
widthRange[63] = { min:52, max:70 }
widthRange[66] = { min:52, max:70 }
widthRange[90] = { min:70, max:94 }

Declarative approach:

const relevantKeys = [46,66,90]
const relevantValues = Object.keys(widthRange)
    .filter(index => relevantKeys.includes(parseInt(index)))
    .map(relevantIndex => widthRange[relevantIndex])

Object.keys to get the keys, using parseInt to cast them as numbers. filter to get only ones you want. map to build an array from the original object of just the indices you're after, since Object.keys loses the object values.

Debug:

console.log(widthRange)
console.log(relevantKeys)
console.log(relevantValues)

How to install Cmake C compiler and CXX compiler

Even though I had gcc already installed, I had to run

sudo apt-get install build-essential

to get rid of that error

Convert a list of characters into a string

h = ['a','b','c','d','e','f']
g = ''
for f in h:
    g = g + f

>>> g
'abcdef'

Synchronization vs Lock

Lock and synchronize block both serves the same purpose but it depends on the usage. Consider the below part

void randomFunction(){
.
.
.
synchronize(this){
//do some functionality
}

.
.
.
synchronize(this)
{
// do some functionality
}


} // end of randomFunction

In the above case , if a thread enters the synchronize block, the other block is also locked. If there are multiple such synchronize block on the same object, all the blocks are locked. In such situations , java.util.concurrent.Lock can be used to prevent unwanted locking of blocks

How to populate options of h:selectOneMenu from database?

Based on your question history, you're using JSF 2.x. So, here's a JSF 2.x targeted answer. In JSF 1.x you would be forced to wrap item values/labels in ugly SelectItem instances. This is fortunately not needed anymore in JSF 2.x.


Basic example

To answer your question directly, just use <f:selectItems> whose value points to a List<T> property which you preserve from the DB during bean's (post)construction. Here's a basic kickoff example assuming that T actually represents a String.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{bean.names}" />
</h:selectOneMenu>

with

@ManagedBean
@RequestScoped
public class Bean {

    private String name;
    private List<String> names; 

    @EJB
    private NameService nameService;

    @PostConstruct
    public void init() {
        names = nameService.list();
    }

    // ... (getters, setters, etc)
}

Simple as that. Actually, the T's toString() will be used to represent both the dropdown item label and value. So, when you're instead of List<String> using a list of complex objects like List<SomeEntity> and you haven't overridden the class' toString() method, then you would see com.example.SomeEntity@hashcode as item values. See next section how to solve it properly.

Also note that the bean for <f:selectItems> value does not necessarily need to be the same bean as the bean for <h:selectOneMenu> value. This is useful whenever the values are actually applicationwide constants which you just have to load only once during application's startup. You could then just make it a property of an application scoped bean.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{data.names}" />
</h:selectOneMenu>

Complex objects as available items

Whenever T concerns a complex object (a javabean), such as User which has a String property of name, then you could use the var attribute to get hold of the iteration variable which you in turn can use in itemValue and/or itemLabel attribtues (if you omit the itemLabel, then the label becomes the same as the value).

Example #1:

<h:selectOneMenu value="#{bean.userName}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.name}" />
</h:selectOneMenu>

with

private String userName;
private List<User> users;

@EJB
private UserService userService;

@PostConstruct
public void init() {
    users = userService.list();
}

// ... (getters, setters, etc)

Or when it has a Long property id which you would rather like to set as item value:

Example #2:

<h:selectOneMenu value="#{bean.userId}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private Long userId;
private List<User> users;

// ... (the same as in previous bean example)

Complex object as selected item

Whenever you would like to set it to a T property in the bean as well and T represents an User, then you would need to bake a custom Converter which converts between User and an unique string representation (which can be the id property). Do note that the itemValue must represent the complex object itself, exactly the type which needs to be set as selection component's value.

<h:selectOneMenu value="#{bean.user}" converter="#{userConverter}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private User user;
private List<User> users;

// ... (the same as in previous bean example)

and

@ManagedBean
@RequestScoped
public class UserConverter implements Converter {

    @EJB
    private UserService userService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        if (submittedValue == null || submittedValue.isEmpty()) {
            return null;
        }

        try {
            return userService.find(Long.valueOf(submittedValue));
        } catch (NumberFormatException e) {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        if (modelValue == null) {
            return "";
        }

        if (modelValue instanceof User) {
            return String.valueOf(((User) modelValue).getId());
        } else {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e);
        }
    }

}

(please note that the Converter is a bit hacky in order to be able to inject an @EJB in a JSF converter; normally one would have annotated it as @FacesConverter(forClass=User.class), but that unfortunately doesn't allow @EJB injections)

Don't forget to make sure that the complex object class has equals() and hashCode() properly implemented, otherwise JSF will during render fail to show preselected item(s), and you'll on submit face Validation Error: Value is not valid.

public class User {

    private Long id;

    @Override
    public boolean equals(Object other) {
        return (other != null && getClass() == other.getClass() && id != null)
            ? id.equals(((User) other).id)
            : (other == this);
    }

    @Override
    public int hashCode() {
        return (id != null) 
            ? (getClass().hashCode() + id.hashCode())
            : super.hashCode();
    }

}

Complex objects with a generic converter

Head to this answer: Implement converters for entities with Java Generics.


Complex objects without a custom converter

The JSF utility library OmniFaces offers a special converter out the box which allows you to use complex objects in <h:selectOneMenu> without the need to create a custom converter. The SelectItemsConverter will simply do the conversion based on readily available items in <f:selectItem(s)>.

<h:selectOneMenu value="#{bean.user}" converter="omnifaces.SelectItemsConverter">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

See also:

DateTime.Compare how to check if a date is less than 30 days old?

Compare returns 1, 0, -1 for greater than, equal to, less than, respectively.

You want:

    if (DateTime.Compare(expiryDate, DateTime.Now.AddDays(30)) <= 0) 
    { 
        bool matchFound = true;
    }

How to enable CORS in ASP.NET Core

Based on Henk's answer I have been able to come up with the specific domain, the method I want to allow and also the header I want to enable CORS for:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
         options.AddPolicy("AllowSpecific", p => p.WithOrigins("http://localhost:1233")
                                                   .WithMethods("GET")
                                                   .WithHeaders("name")));
    services.AddMvc();
}

usage:

[EnableCors("AllowSpecific")]

What's the point of the X-Requested-With header?

A good reason is for security - this can prevent CSRF attacks because this header cannot be added to the AJAX request cross domain without the consent of the server via CORS.

Only the following headers are allowed cross domain:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type

any others cause a "pre-flight" request to be issued in CORS supported browsers.

Without CORS it is not possible to add X-Requested-With to a cross domain XHR request.

If the server is checking that this header is present, it knows that the request didn't initiate from an attacker's domain attempting to make a request on behalf of the user with JavaScript. This also checks that the request wasn't POSTed from a regular HTML form, of which it is harder to verify it is not cross domain without the use of tokens. (However, checking the Origin header could be an option in supported browsers, although you will leave old browsers vulnerable.)

New Flash bypass discovered

You may wish to combine this with a token, because Flash running on Safari on OSX can set this header if there's a redirect step. It appears it also worked on Chrome, but is now remediated. More details here including different versions affected.

OWASP Recommend combining this with an Origin and Referer check:

This defense technique is specifically discussed in section 4.3 of Robust Defenses for Cross-Site Request Forgery. However, bypasses of this defense using Flash were documented as early as 2008 and again as recently as 2015 by Mathias Karlsson to exploit a CSRF flaw in Vimeo. But, we believe that the Flash attack can't spoof the Origin or Referer headers so by checking both of them we believe this combination of checks should prevent Flash bypass CSRF attacks. (NOTE: If anyone can confirm or refute this belief, please let us know so we can update this article)

However, for the reasons already discussed checking Origin can be tricky.

Update

Written a more in depth blog post on CORS, CSRF and X-Requested-With here.

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You may need to handle javax.persistence.RollbackException

How to run a program in Atom Editor?

If you know how to launch your program from the command line then you can run it from the platformio-ide-terminal package's terminal. See platformio-ide-terminal provides an embedded terminal within the Atom text editor. So you can issue commands, including commands to run your Java program, from within it. To install this package you can use APM with the command:

$ apm install platformio-ide-terminal --no-confirm

Alternatively, you can install it from the command palette with:

  • Pressing Ctrl+Shift+P. I am assuming this is the appropriate keyboard shortcut for your platform, as you have dealt ith questions about Ubuntu in the past.
  • Type Install Packages and Themes.
  • Search for the platformio-ide-terminal.
  • Install it.

Set height of <div> = to height of another <div> through .css

If you're open to using javascript then you can get the property on an element like this: document.GetElementByID('rightdiv').style.getPropertyValue('max-height');

And you can set the attribute on an element like this: .setAttribute('style','max-height:'+heightVariable+';');

Note: if you're simply looking to set both element's max-height property in one line, you can do so like this:

#leftdiv,#rightdiv
{
    min-height: 600px;   
}

How to properly set Column Width upon creating Excel file? (Column properties)

See this snippet: (C#)

    private Microsoft.Office.Interop.Excel.Application xla;
    Workbook wb;
    Worksheet ws;
    Range rg;
    ..........

        xla = new Microsoft.Office.Interop.Excel.Application();
        wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
        ws = (Worksheet)xla.ActiveSheet;
        rg = (Range)ws.Cells[1, 2];
        rg.ColumnWidth = 10;
        rg.Value2 = "Frequency";
        rg = (Range)ws.Cells[1, 3];
        rg.ColumnWidth = 15;
        rg.Value2 = "Impudence";
        rg = (Range)ws.Cells[1, 4];
        rg.ColumnWidth = 8;
        rg.Value2 = "Phase";

Data access object (DAO) in Java

I am going to be general and not specific to Java as DAO and ORM are used in all languages.

To understand DAO you first need to understand ORM (Object Relational Mapping). This means that if you have a table called "person" with columns "name" and "age", then you would create object-template for that table:

type Person {
name
age
}

Now with help of DAO instead of writing some specific queries, to fetch all persons, for what ever type of db you are using (which can be error-prone) instead you do:

list persons = DAO.getPersons();
...
person = DAO.getPersonWithName("John");
age = person.age;

You do not write the DAO abstraction yourself, instead it is usually part of some opensource project, depending on what language and framework you are using.

Now to the main question here. "..where it is used..". Well usually if you are writing complex business and domain specific code your life will be very difficult without DAO. Of course you do not need to use ORM and DAO provided, instead you can write your own abstraction and native queries. I have done that in the past and almost always regretted it later.

Convert SQL Server result set into string

Both answers are valid, but don't forget to initializate the value of the variable, by default is NULL and with T-SQL:

NULL + "Any text" => NULL

It's a very common mistake, don't forget it!

Also is good idea to use ISNULL function:

SELECT @result = @result + ISNULL(StudentId + ',', '') FROM Student

Styling an anchor tag to look like a submit button

Using a button tag instead of the input, resetting it and put a span inside, you'll then just have to style both the link and the span in the same way. It involve extra markup, but it worked for me.

the markup:

<button type="submit">
    <span>submit</span>
</button>
<a>cancel</a>

the css:

button[type="submit"] {
    display: inline;
    border: none;
    padding: 0;
    background: none;
}

Difference between window.location.href and top.location.href

window.location.href returns the location of the current page.

top.location.href (which is an alias of window.top.location.href) returns the location of the topmost window in the window hierarchy. If a window has no parent, top is a reference to itself (in other words, window === window.top).

top is useful both when you're dealing with frames and when dealing with windows which have been opened by other pages. For example, if you have a page called test.html with the following script:

var newWin=window.open('about:blank','test','width=100,height=100');
newWin.document.write('<script>alert(top.location.href);</script>');

The resulting alert will have the full path to test.html – not about:blank, which is what window.location.href would return.

To answer your question about redirecting, go with window.location.assign(url);

How to add option to select list in jQuery

It looks like you want this pluging as it follows your existing code, maybe the plug in js file got left out somewhere.

http://www.texotela.co.uk/code/jquery/select/

var myOptions = {
"Value 1" : "Text 1",
"Value 2" : "Text 2",
"Value 3" : "Text 3"
} 
$("#myselect2").addOption(myOptions, false); 
// use true if you want to select the added options » Run

Creating a UICollectionView programmatically

  1. Building off @Warewolf's answer, the next step is to create your own custom cell.

    Go to File -> New -> File -> User Interface -> Empty -> Call this nib "customNib".

  2. In your customNib drag a UICollectionView Cell in. Give it reuse cell identifier @"Cell".

  3. File -> New -> File -> Cocoa Touch Class -> Class named "CustomCollectionViewCell" subclass if UICollectionViewCell.

  4. Go back to the custom nib, click cell and make this custom class "CustomCollectionViewCell".

  5. Go to your viewDidLoad viewcontroller and instead of

    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];

    have

    UINib *nib = [UINib nibWithNibName:@"customNib" bundle:nil]; [_collectionView registerNib:nib forCellWithReuseIdentifier:@"Cell"];

  6. Also, change (to your new cell identifier)

    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

How to import or copy images to the "res" folder in Android Studio?

I'm in Mac OSX as well and in a new project I need to:

  • Right click on res folder in the project and add a new Android resource directory.
  • Select drawable from the drop down and Accept.
  • Copy and paste the image into the drawable folder.

Disclaimer : This does NOT cover different resolutions etc.

Get the Query Executed in Laravel 3/4

You can enable the "Profiler" in Laravel 3 by setting

'profiler' => true,

In your application/config/application.php and application/config/database.php

This enables a bar at the bottom of each page. One of its features is listing the executed queries and how long each one took.

enter image description here

R - Concatenate two dataframes?

you can use the function

bind_rows(a,b)

from the dplyr library

How Do I Upload Eclipse Projects to GitHub?

For eclipse i think EGIT is the best option. This guide http://rogerdudler.github.io/git-guide/index.html will help you understand git quick.

How to deal with "data of class uneval" error from ggplot2?

when you add a new data set to a geom you need to use the data= argument. Or put the arguments in the proper order mapping=..., data=.... Take a look at the arguments for ?geom_line.

Thus:

p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red") 

Or:

p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red") 

Compare a string using sh shell

Of the 4 shells that I've tested, ABC -eq XYZ evaluates to true in the test builtin for zsh and ksh. The expression evaluates to false under /usr/bin/test and the builtins for dash and bash. In ksh and zsh, the strings are converted to numerical values and are equal since they are both 0. IMO, the behavior of the builtins for ksh and zsh is incorrect, but the spec for test is ambiguous on this.

How can I debug git/git-shell related problems?

Git 2.22 (Q2 2019) introduces trace2 with commit ee4512e by Jeff Hostetler:

trace2: create new combined trace facility

Create a new unified tracing facility for git.
The eventual intent is to replace the current trace_printf* and trace_performance* routines with a unified set of git_trace2* routines.

In addition to the usual printf-style API, trace2 provides higer-level event verbs with fixed-fields allowing structured data to be written.
This makes post-processing and analysis easier for external tools.

Trace2 defines 3 output targets.
These are set using the environment variables "GIT_TR2", "GIT_TR2_PERF", and "GIT_TR2_EVENT".
These may be set to "1" or to an absolute pathname (just like the current GIT_TRACE).

Note: regarding environment variable name, always use GIT_TRACExxx, not GIT_TRxxx.
So actually GIT_TRACE2, GIT_TRACE2_PERF or GIT_TRACE2_EVENT.
See the Git 2.22 rename mentioned later below.

What follows is the initial work on this new tracing feature, with the old environment variable names:

  • GIT_TR2 is intended to be a replacement for GIT_TRACE and logs command summary data.

  • GIT_TR2_PERF is intended as a replacement for GIT_TRACE_PERFORMANCE.
    It extends the output with columns for the command process, thread, repo, absolute and relative elapsed times.
    It reports events for child process start/stop, thread start/stop, and per-thread function nesting.

  • GIT_TR2_EVENT is a new structured format. It writes event data as a series of JSON records.

Calls to trace2 functions log to any of the 3 output targets enabled without the need to call different trace_printf* or trace_performance* routines.

See commit a4d3a28 (21 Mar 2019) by Josh Steadmon (steadmon).
(Merged by Junio C Hamano -- gitster -- in commit 1b40314, 08 May 2019)

trace2: write to directory targets

When the value of a trace2 environment variable is an absolute path referring to an existing directory, write output to files (one per process) underneath the given directory.
Files will be named according to the final component of the trace2 SID, followed by a counter to avoid potential collisions.

This makes it more convenient to collect traces for every git invocation by unconditionally setting the relevant trace2 envvar to a constant directory name.


See also commit f672dee (29 Apr 2019), and commit 81567ca, commit 08881b9, commit bad229a, commit 26c6f25, commit bce9db6, commit 800a7f9, commit a7bc01e, commit 39f4317, commit a089724, commit 1703751 (15 Apr 2019) by Jeff Hostetler (jeffhostetler).
(Merged by Junio C Hamano -- gitster -- in commit 5b2d1c0, 13 May 2019)

The new documentation now includes config settings which are only read from the system and global config files (meaning repository local and worktree config files and -c command line arguments are not respected.)

Example:

$ git config --global trace2.normalTarget ~/log.normal
$ git version
git version 2.20.1.155.g426c96fcdb

yields

$ cat ~/log.normal
12:28:42.620009 common-main.c:38                  version 2.20.1.155.g426c96fcdb
12:28:42.620989 common-main.c:39                  start git version
12:28:42.621101 git.c:432                         cmd_name version (version)
12:28:42.621215 git.c:662                         exit elapsed:0.001227 code:0
12:28:42.621250 trace2/tr2_tgt_normal.c:124 atexit elapsed:0.001265 code:0

And for performance measure:

$ git config --global trace2.perfTarget ~/log.perf
$ git version
git version 2.20.1.155.g426c96fcdb

yields

$ cat ~/log.perf
12:28:42.620675 common-main.c:38                  | d0 | main                     | version      |     |           |           |            | 2.20.1.155.g426c96fcdb
12:28:42.621001 common-main.c:39                  | d0 | main                     | start        |     |  0.001173 |           |            | git version
12:28:42.621111 git.c:432                         | d0 | main                     | cmd_name     |     |           |           |            | version (version)
12:28:42.621225 git.c:662                         | d0 | main                     | exit         |     |  0.001227 |           |            | code:0
12:28:42.621259 trace2/tr2_tgt_perf.c:211         | d0 | main                     | atexit       |     |  0.001265 |           |            | code:0

As documented in Git 2.23 (Q3 2019), the environment variable to use is GIT_TRACE2.

See commit 6114a40 (26 Jun 2019) by Carlo Marcelo Arenas Belón (carenas).
See commit 3efa1c6 (12 Jun 2019) by Ævar Arnfjörð Bjarmason (avar).
(Merged by Junio C Hamano -- gitster -- in commit e9eaaa4, 09 Jul 2019)

That follows the work done in Git 2.22: commit 4e0d3aa, commit e4b75d6 (19 May 2019) by SZEDER Gábor (szeder).
(Merged by Junio C Hamano -- gitster -- in commit 463dca6, 30 May 2019)

trace2: rename environment variables to GIT_TRACE2*

For an environment variable that is supposed to be set by users, the GIT_TR2* env vars are just too unclear, inconsistent, and ugly.

Most of the established GIT_* environment variables don't use abbreviations, and in case of the few that do (GIT_DIR, GIT_COMMON_DIR, GIT_DIFF_OPTS) it's quite obvious what the abbreviations (DIR and OPTS) stand for.
But what does TR stand for? Track, traditional, trailer, transaction, transfer, transformation, transition, translation, transplant, transport, traversal, tree, trigger, truncate, trust, or ...?!

The trace2 facility, as the '2' suffix in its name suggests, is supposed to eventually supercede Git's original trace facility.
It's reasonable to expect that the corresponding environment variables follow suit, and after the original GIT_TRACE variables they are called GIT_TRACE2; there is no such thing is 'GIT_TR'.

All trace2-specific config variables are, very sensibly, in the 'trace2' section, not in 'tr2'.

OTOH, we don't gain anything at all by omitting the last three characters of "trace" from the names of these environment variables.

So let's rename all GIT_TR2* environment variables to GIT_TRACE2*, before they make their way into a stable release.


Git 2.24 (Q3 2019) improves the Git repository initialization.

See commit 22932d9, commit 5732f2b, commit 58ebccb (06 Aug 2019) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit b4a1eec, 09 Sep 2019)

common-main: delay trace2 initialization

We initialize the trace2 system in the common main() function so that all programs (even ones that aren't builtins) will enable tracing.

But trace2 startup is relatively heavy-weight, as we have to actually read on-disk config to decide whether to trace.
This can cause unexpected interactions with other common-main initialization. For instance, we'll end up in the config code before calling initialize_the_repository(), and the usual invariant that the_repository is never NULL will not hold.

Let's push the trace2 initialization further down in common-main, to just before we execute cmd_main().


Git 2.24 (Q4 2019) makes also sure that output from trace2 subsystem is formatted more prettily now.

See commit 742ed63, commit e344305, commit c2b890a (09 Aug 2019), commit ad43e37, commit 04f10d3, commit da4589c (08 Aug 2019), and commit 371df1b (31 Jul 2019) by Jeff Hostetler (jeffhostetler).
(Merged by Junio C Hamano -- gitster -- in commit 93fc876, 30 Sep 2019)

And, still Git 2.24

See commit 87db61a, commit 83e57b0 (04 Oct 2019), and commit 2254101, commit 3d4548e (03 Oct 2019) by Josh Steadmon (steadmon).
(Merged by Junio C Hamano -- gitster -- in commit d0ce4d9, 15 Oct 2019)

trace2: discard new traces if target directory has too many files

Signed-off-by: Josh Steadmon

trace2 can write files into a target directory.
With heavy usage, this directory can fill up with files, causing difficulty for trace-processing systems.

This patch adds a config option (trace2.maxFiles) to set a maximum number of files that trace2 will write to a target directory.

The following behavior is enabled when the maxFiles is set to a positive integer:

  • When trace2 would write a file to a target directory, first check whether or not the traces should be discarded.
    Traces should be discarded if:
    • there is a sentinel file declaring that there are too many files
    • OR, the number of files exceeds trace2.maxFiles.
      In the latter case, we create a sentinel file named git-trace2-discard to speed up future checks.

The assumption is that a separate trace-processing system is dealing with the generated traces; once it processes and removes the sentinel file, it should be safe to generate new trace files again.

The default value for trace2.maxFiles is zero, which disables the file count check.

The config can also be overridden with a new environment variable: GIT_TRACE2_MAX_FILES.


And Git 2.24 (Q4 2019) teach trace2 about git push stages.

See commit 25e4b80, commit 5fc3118 (02 Oct 2019) by Josh Steadmon (steadmon).
(Merged by Junio C Hamano -- gitster -- in commit 3b9ec27, 15 Oct 2019)

push: add trace2 instrumentation

Signed-off-by: Josh Steadmon

Add trace2 regions in transport.c and builtin/push.c to better track time spent in various phases of pushing:

  • Listing refs
  • Checking submodules
  • Pushing submodules
  • Pushing refs

With Git 2.25 (Q1 2020), some of the Documentation/technical is moved to header *.h files.

See commit 6c51cb5, commit d95a77d, commit bbcfa30, commit f1ecbe0, commit 4c4066d, commit 7db0305, commit f3b9055, commit 971b1f2, commit 13aa9c8, commit c0be43f, commit 19ef3dd, commit 301d595, commit 3a1b341, commit 126c1cc, commit d27eb35, commit 405c6b1, commit d3d7172, commit 3f1480b, commit 266f03e, commit 13c4d7e (17 Nov 2019) by Heba Waly (HebaWaly).
(Merged by Junio C Hamano -- gitster -- in commit 26c816a, 16 Dec 2019)

trace2: move doc to trace2.h

Signed-off-by: Heba Waly

Move the functions documentation from Documentation/technical/api-trace2.txt to trace2.h as it's easier for the developers to find the usage information beside the code instead of looking for it in another doc file.

Only the functions documentation section is removed from Documentation/technical/api-trace2.txt as the file is full of details that seemed more appropriate to be in a separate doc file as it is, with a link to the doc file added in the trace2.h. Also the functions doc is removed to avoid having redundandt info which will be hard to keep syncronized with the documentation in the header file.

(although that reorganization had a side effect on another command, explained and fixed with Git 2.25.2 (March 2020) in commit cc4f2eb (14 Feb 2020) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 1235384, 17 Feb 2020))


With Git 2.27 (Q2 2020): Trace2 enhancement to allow logging of the environment variables.

See commit 3d3adaa (20 Mar 2020) by Josh Steadmon (steadmon).
(Merged by Junio C Hamano -- gitster -- in commit 810dc64, 22 Apr 2020)

trace2: teach Git to log environment variables

Signed-off-by: Josh Steadmon
Acked-by: Jeff Hostetler

Via trace2, Git can already log interesting config parameters (see the trace2_cmd_list_config() function). However, this can grant an incomplete picture because many config parameters also allow overrides via environment variables.

To allow for more complete logs, we add a new trace2_cmd_list_env_vars() function and supporting implementation, modeled after the pre-existing config param logging implementation.


With Git 2.27 (Q2 2020), teach codepaths that show progress meter to also use the start_progress() and the stop_progress() calls as a "region" to be traced.

See commit 98a1364 (12 May 2020) by Emily Shaffer (nasamuffin).
(Merged by Junio C Hamano -- gitster -- in commit d98abce, 14 May 2020)

trace2: log progress time and throughput

Signed-off-by: Emily Shaffer

Rather than teaching only one operation, like 'git fetch', how to write down throughput to traces, we can learn about a wide range of user operations that may seem slow by adding tooling to the progress library itself.

Operations which display progress are likely to be slow-running and the kind of thing we want to monitor for performance anyways.

By showing object counts and data transfer size, we should be able to make some derived measurements to ensure operations are scaling the way we expect.

And:

With Git 2.27 (Q2 2020), last-minute fix for our recent change to allow use of progress API as a traceable region.

See commit 3af029c (15 May 2020) by Derrick Stolee (derrickstolee).
(Merged by Junio C Hamano -- gitster -- in commit 85d6e28, 20 May 2020)

progress: call trace2_region_leave() only after calling _enter()

Signed-off-by: Derrick Stolee

A user of progress API calls start_progress() conditionally and depends on the display_progress() and stop_progress() functions to become no-op when start_progress() hasn't been called.

As we added a call to trace2_region_enter() to start_progress(), the calls to other trace2 API calls from the progress API functions must make sure that these trace2 calls are skipped when start_progress() hasn't been called on the progress struct.

Specifically, do not call trace2_region_leave() from stop_progress() when we haven't called start_progress(), which would have called the matching trace2_region_enter().


That last part is more robust with Git 2.29 (Q4 2020):

See commit ac900fd (10 Aug 2020) by Martin Ågren (none).
(Merged by Junio C Hamano -- gitster -- in commit e6ec620, 17 Aug 2020)

progress: don't dereference before checking for NULL

Signed-off-by: Martin Ågren

In stop_progress(), we're careful to check that p_progress is non-NULL before we dereference it, but by then we have already dereferenced it when calling finish_if_sparse(*p_progress).
And, for what it's worth, we'll go on to blindly dereference it again inside stop_progress_msg().

We could return early if we get a NULL-pointer, but let's go one step further and BUG instead.
The progress API handles NULL just fine, but that's the NULL-ness of *p_progress, e.g., when running with --no-progress.
If p_progress is NULL, chances are that's a mistake.
For symmetry, let's do the same check in stop_progress_msg(), too.


With Git 2.29 (Q4 2020), there is even more trace, this time in a Git development environment.

See commit 4441f42 (09 Sep 2020) by Han-Wen Nienhuys (hanwen).
(Merged by Junio C Hamano -- gitster -- in commit c9a04f0, 22 Sep 2020)

refs: add GIT_TRACE_REFS debugging mechanism

Signed-off-by: Han-Wen Nienhuys

When set in the environment, GIT_TRACE_REFS makes git print operations and results as they flow through the ref storage backend. This helps debug discrepancies between different ref backends.

Example:

$ GIT_TRACE_REFS="1" ./git branch
15:42:09.769631 refs/debug.c:26         ref_store for .git
15:42:09.769681 refs/debug.c:249        read_raw_ref: HEAD: 0000000000000000000000000000000000000000 (=> refs/heads/ref-debug) type 1: 0
15:42:09.769695 refs/debug.c:249        read_raw_ref: refs/heads/ref-debug: 3a238e539bcdfe3f9eb5010fd218640c1b499f7a (=> refs/heads/ref-debug) type 0: 0
15:42:09.770282 refs/debug.c:233        ref_iterator_begin: refs/heads/ (0x1)
15:42:09.770290 refs/debug.c:189        iterator_advance: refs/heads/b4 (0)
15:42:09.770295 refs/debug.c:189        iterator_advance: refs/heads/branch3 (0)

git now includes in its man page:

GIT_TRACE_REFS

Enables trace messages for operations on the ref database. See GIT_TRACE for available trace output options.


With Git 2.30 (Q1 2021), like die() and error(), a call to warning() will also trigger a trace2 event.

See commit 0ee10fd (23 Nov 2020) by Jonathan Tan (jhowtan).
(Merged by Junio C Hamano -- gitster -- in commit 2aeafbc, 08 Dec 2020)

set background color: Android

By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:

android:background="#fff"

How to connect Bitbucket to Jenkins properly

I had a similar problems, till I got it working. Below is the full listing of the integration:

  1. Generate public/private keys pair: ssh-keygen -t rsa
  2. Copy the public key (~/.ssh/id_rsa.pub) and paste it in Bitbucket SSH keys, in user’s account management console: enter image description here

  3. Copy the private key (~/.ssh/id_rsa) to new user (or even existing one) with private key credentials, in this case, username will not make a difference, so username can be anything: enter image description here

  4. run this command to test if you can get access to Bitbucket account: ssh -T [email protected]

  5. OPTIONAL: Now, you can use your git to to copy repo to your desk without passwjord git clone [email protected]:username/repo_name.git
  6. Now you can enable Bitbucket hooks for Jenkins push notifications and automatic builds, you will do that in 2 steps:

    1. Add an authentication token inside the job/project you configure, it can be anything: enter image description here

    2. In Bitbucket hooks: choose jenkins hooks, and fill the fields as below: enter image description here

Where:

**End point**: username:usertoken@jenkins_domain_or_ip
**Project name**: is the name of job you created on Jenkins
**Token**: Is the authorization token you added in the above steps in your Jenkins' job/project 

Recommendation: I usually add the usertoken as the authorization Token (in both Jenkins Auth Token job configuration and Bitbucket hooks), making them one variable to ease things on myself.

Calculating the distance between 2 points

the algorithm : ((x1 - x2) ^ 2 + (y1 - y2) ^ 2) < 25

jQuery: Setting select list 'selected' based on text, failing strangely

$("#my-select option:contains(" + myText +")").attr("selected", true);

This returns the first option containing your text description.

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

I faced this issue, but none of the answers here worked for me. I googled and found that FormsModule not shared with Feature Modules

So If your form is in a featured module, then you have to import and add the FromsModule there.

Please ref: https://github.com/angular/angular/issues/11365

Are there any style options for the HTML5 Date picker?

FYI, I needed to update the color of the calendar icon which didn't seem possible with properties like color, fill, etc.

I did eventually figure out that some filter properties will adjust the icon so while i did not end up figuring out how to make it any color, luckily all I needed was to make it so the icon was visible on a dark background so I was able to do the following:

_x000D_
_x000D_
body { background: black; }_x000D_
_x000D_
input[type="date"] { _x000D_
  background: transparent;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
  filter: invert(100%);_x000D_
}
_x000D_
<body>_x000D_
 <input type="date" />_x000D_
</body>
_x000D_
_x000D_
_x000D_

Hopefully this helps some people as for the most part chrome even directly says this is impossible.

What is std::move(), and when should it be used?

1. "What is it?"

While std::move() is technically a function - I would say it isn't really a function. It's sort of a converter between ways the compiler considers an expression's value.

2. "What does it do?"

The first thing to note is that std::move() doesn't actually move anything. It changes an expression from being an lvalue (such as a named variable) to being an xvalue. An xvalue tells the compiler:

You can plunder me, move anything I'm holding and use it elsewhere (since I'm going to be destroyed soon anyway)".

in other words, when you use std::move(x), you're allowing the compiler to cannibalize x. Thus if x has, say, its own buffer in memory - after std::move()ing the compiler can have another object own it instead.

You can also move from a prvalue (such as a temporary you're passing around), but this is rarely useful.

3. "When should it be used?"

Another way to ask this question is "What would I cannibalize an existing object's resources for?" well, if you're writing application code, you would probably not be messing around a lot with temporary objects created by the compiler. So mainly you would do this in places like constructors, operator methods, standard-library-algorithm-like functions etc. where objects get created and destroyed automagically a lot. Of course, that's just a rule of thumb.

A typical use is 'moving' resources from one object to another instead of copying. @Guillaume links to this page which has a straightforward short example: swapping two objects with less copying.

template <class T>
swap(T& a, T& b) {
    T tmp(a);   // we now have two copies of a
    a = b;      // we now have two copies of b (+ discarded a copy of a)
    b = tmp;    // we now have two copies of tmp (+ discarded a copy of b)
}

using move allows you to swap the resources instead of copying them around:

template <class T>
swap(T& a, T& b) {
    T tmp(std::move(a));
    a = std::move(b);   
    b = std::move(tmp);
}

Think of what happens when T is, say, vector<int> of size n. In the first version you read and write 3*n elements, in the second version you basically read and write just the 3 pointers to the vectors' buffers, plus the 3 buffers' sizes. Of course, class T needs to know how to do the moving; your class should have a move-assignment operator and a move-constructor for class T for this to work.

Word count from a txt file program

print("sorted counting values:-")
from collections import Counter

fname = open(filename)

fname = fname.read()

fsplit = fname.split()

user  = Counter(fsplit)

for i,v in sorted(user.items()):

   print((v,i))

Your project path contains non-ASCII characters android studio

The path location must not contain á,à,â, and similars. Chinese characters or any other diferent than the usual alphabetical characters. For example, my path was C:\Users\Vinícius\AndroidStudioProjects\MyApplication .But my user name had the letter í. So I create a folder 'custom2222' and change the path to C:\custom2222\MyApplication

Find and copy files

for i in $(ls); do cp -r "$i" "$i"_dev; done;

Get request URL in JSP which is forwarded by Servlet

To get the current path from within the JSP file you can simply do one of the following:

<%= request.getContextPath() %>
<%= request.getRequestURI() %>
<%= request.getRequestURL() %>

How do you overcome the svn 'out of date' error?

If you're using the github svn bridge, it is likely because something changed on github's side of things. The solution is simple, you just have to run svn switch, which lets it properly find itself, then update and everything will work. Just run the following from the root of your checkout

svn info | grep Relative 
svn switch path_from_previous_command
svn update

or

svn switch `svn info | grep Relative | sed 's_.*: __'`
svn update

The basis for this solution comes from Lee Preimesberger's blog

Swap two variables without using a temporary variable

int a = 4, b = 6;
a ^= b ^= a ^= b;

Works for all types including strings and floats.

C++ How do I convert a std::chrono::time_point to long and back

I would also note there are two ways to get the number of ms in the time point. I'm not sure which one is better, I've benchmarked them and they both have the same performance, so I guess it's a matter of preference. Perhaps Howard could chime in:

auto now = system_clock::now();

//Cast the time point to ms, then get its duration, then get the duration's count.
auto ms = time_point_cast<milliseconds>(now).time_since_epoch().count();

//Get the time point's duration, then cast to ms, then get its count.
auto ms = duration_cast<milliseconds>(tpBid.time_since_epoch()).count();

The first one reads more clearly in my mind going from left to right.

How can I pair socks from a pile efficiently?

My proposed solution assumes that all socks are identical in details, except by color. If there are more details to defer between socks, these details can be used to define different types of socks instead of colors in my example ..

Given that we have a pile of socks, a sock can come in three colors: Blue, red, or green.

Then we can create a parallel worker for each color; it has its own list to fill corresponding colors.

At time i:

Blue  read  Pile[i]    : If Blue  then Blue.Count++  ; B=TRUE  ; sync

Red   read  Pile[i+1]  : If Red   then Red.Count++   ; R=TRUE  ; sync

Green read  Pile [i+2] : If Green then Green.Count++ ; G=TRUE  ; sync

With synchronization process:

Sync i:

i++

If R is TRUE:
    i++
    If G is TRUE:
        i++

This requires an initialization:

Init:

If Pile[0] != Blue:
    If      Pile[0] = Red   : Red.Count++
    Else if Pile[0] = Green : Green.Count++

If Pile[1] != Red:
    If Pile[0] = Green : Green.Count++

Where

Best Case: B, R, G, B, R, G, .., B, R, G

Worst Case: B, B, B, .., B

Time(Worst-Case) = C * n ~ O(n)

Time(Best-Case) = C * (n/k) ~ O(n/k)

n: number of sock pairs
k: number of colors
C: sync overhead

Unique on a dataframe with only selected columns

Minor update in @Joran's code.
Using the code below, you can avoid the ambiguity and only get the unique of two columns:

dat <- data.frame(id=c(1,1,3), id2=c(1,1,4) ,somevalue=c("x","y","z"))    
dat[row.names(unique(dat[,c("id", "id2")])), c("id", "id2")]

Angles between two n-dimensional vectors in Python

import math

def dotproduct(v1, v2):
  return sum((a*b) for a, b in zip(v1, v2))

def length(v):
  return math.sqrt(dotproduct(v, v))

def angle(v1, v2):
  return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2)))

Note: this will fail when the vectors have either the same or the opposite direction. The correct implementation is here: https://stackoverflow.com/a/13849249/71522

How to define hash tables in Bash?

Bash 3 solution:

In reading some of the answers I put together a quick little function I would like to contribute back that might help others.

# Define a hash like this
MYHASH=("firstName:Milan"
        "lastName:Adamovsky")

# Function to get value by key
getHashKey()
 {
  declare -a hash=("${!1}")
  local key
  local lookup=$2

  for key in "${hash[@]}" ; do
   KEY=${key%%:*}
   VALUE=${key#*:}
   if [[ $KEY == $lookup ]]
   then
    echo $VALUE
   fi
  done
 }

# Function to get a list of all keys
getHashKeys()
 {
  declare -a hash=("${!1}")
  local KEY
  local VALUE
  local key
  local lookup=$2

  for key in "${hash[@]}" ; do
   KEY=${key%%:*}
   VALUE=${key#*:}
   keys+="${KEY} "
  done

  echo $keys
 }

# Here we want to get the value of 'lastName'
echo $(getHashKey MYHASH[@] "lastName")


# Here we want to get all keys
echo $(getHashKeys MYHASH[@])

Build android release apk on Phonegap 3.x CLI

Building PhoneGap Android app for deployment to the Google Play Store

These steps would work for Cordova, PhoneGap or Ionic. The only difference would be, wherever a call to cordova is placed, replace it with phonegap or ionic, for your particular scenario.

Once you are done with the development and are ready to deploy, follow these steps:

  1. Open a command line window (Terminal on macOS and Linux OR Command Prompt on Windows).

  2. Head over to the /path/to/your/project/, which we would refer to as the Project Root.

  3. While at the project root, remove the "Console" plugin from your set of plugins.

    The command is: cordova plugin rm cordova-plugin-console

  4. While still at the project root, use the cordova build command to create an APK for release distribution.

    The command is: cordova build --release android

  5. The above process creates a file called android-release-unsigned.apk in the folder ProjectRoot/platforms/android/build/outputs/apk/

  6. Sign and align the APK using the instructions at https://developer.android.com/studio/publish/app-signing.html#signing-manually

    At the end of this step the APK which you get can be uploaded to the Play Store.

Note: As a newbie or a beginner, the last step may be a bit confusing as it was to me. One may run into a few issues and may have some questions as to what these commands are and where to find them.

Q1. What are jarsigner and keytool?
Ans: The Android App Signing instructions do tell you specifically what jarsigner and keytool are all about BUT it doesn't tell you where to find them if you run into a 'command not found error' on the command line window.

Thus, if you've got the Java Development Kit(JDK) added to your PATH variable, simply running the commands as in the Guide would work. BUT, if you don't have it in your PATH, you can always access them from the bin folder of your JDK installation.

Q2. Where is zipalign?
Ans: There is a high probability to not find the zipalign command and receive the 'command not found error'. You'd probably be googling zipalign and where to find it?

The zipalign utility is present within the Android SDK installation folder. On macOS, the default location is at, user-name/Library/Android/sdk/. If you head over to the folder you would find a bunch of other folders like docs, platform-tools, build-tools, tools, add-ons...

Open the build-tools folder. cd build-tools. In here, there would be a number of folders which are versioned according to the build tool-chain you are using in the Android SDK Manager. ZipAlign is available in each of these folders. I personally go for the folder with the latest version on it. Open Any.

On macOS or Linux you may have to use ./zipalign rather than simply typing in zipalign as the documentation mentions. On Windows, zipalign is good enough.

Rails get index of "each" loop

<% @images.each_with_index do |page, index| %>

<% end %>

In C#, can a class inherit from another class and an interface?

No, not exactly. But it can inherit from a class and implement one or more interfaces.

Clear terminology is important when discussing concepts like this. One of the things that you'll see mark out Jon Skeet's writing, for example, both here and in print, is that he is always precise in the way he decribes things.

How to upgrade docker container after its image changed

I don't like mounting volumes as a link to a host directory, so I came up with a pattern for upgrading docker containers with entirely docker managed containers. Creating a new docker container with --volumes-from <container> will give the new container with the updated images shared ownership of docker managed volumes.

docker pull mysql
docker create --volumes-from my_mysql_container [...] --name my_mysql_container_tmp mysql

By not immediately removing the original my_mysql_container yet, you have the ability to revert back to the known working container if the upgraded container doesn't have the right data, or fails a sanity test.

At this point, I'll usually run whatever backup scripts I have for the container to give myself a safety net in case something goes wrong

docker stop my_mysql_container
docker start my_mysql_container_tmp

Now you have the opportunity to make sure the data you expect to be in the new container is there and run a sanity check.

docker rm my_mysql_container
docker rename my_mysql_container_tmp my_mysql_container

The docker volumes will stick around so long as any container is using them, so you can delete the original container safely. Once the original container is removed, the new container can assume the namesake of the original to make everything as pretty as it was to begin.

There are two major advantages to using this pattern for upgrading docker containers. Firstly, it eliminates the need to mount volumes to host directories by allowing volumes to be directly transferred to an upgraded containers. Secondly, you are never in a position where there isn't a working docker container; so if the upgrade fails, you can easily revert to how it was working before by spinning up the original docker container again.

How to copy multiple files in one layer using a Dockerfile?

It might be worth mentioning that you can also create a .dockerignore file, to exclude the files that you don't want to copy:

https://docs.docker.com/engine/reference/builder/#dockerignore-file

Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.

Android translate animation - permanently move View to new position using AnimationListener

This is what worked for me perfectly:-

// slide the view from its current position to below itself
public void slideUp(final View view, final View llDomestic){

    ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY",0f);
    animation.setDuration(100);
    llDomestic.setVisibility(View.GONE);
    animation.start();

}

// slide the view from below itself to the current position
public void slideDown(View view,View llDomestic){
    llDomestic.setVisibility(View.VISIBLE);
    ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY",   0f);
    animation.setDuration(100);
    animation.start();
}

llDomestic : The view which you want to hide. view: The view which you want to move down or up.

Time part of a DateTime Field in SQL

I know this is an old question, but since the other answers all

  • return strings (rather than datetimes),
  • rely on the internal representation of dates (conversion to float, int, and back) or
  • require SQL Server 2008 or beyond,

I thought I'd add a "pure" option which only requires datetime operations and works with SQL Server 2005+:

SELECT DATEADD(dd, -DATEDIFF(dd, 0, mydatetime), mydatetime)

This calculates the difference (in whole days) between date zero (1900-01-01) and the given date and then subtracts that number of days from the given date, thereby setting its date component to zero.

Elegant way to check for missing packages and install them?

Thought I'd contribute the one I use:

testin <- function(package){if (!package %in% installed.packages())    
install.packages(package)}
testin("packagename")

How to get the python.exe location programmatically?

sys.executable is not reliable if working in an embedded python environment. My suggestions is to deduce it from

import os
os.__file__

How to use OpenSSL to encrypt/decrypt files?

DO NOT USE OPENSSL DEFAULT KEY DERIVATION.

Currently the accepted answer makes use of it and it's no longer recommended and secure.

It is very feasible for an attacker to simply brute force the key.

https://www.ietf.org/rfc/rfc2898.txt

PBKDF1 applies a hash function, which shall be MD2 [6], MD5 [19] or SHA-1 [18], to derive keys. The length of the derived key is bounded by the length of the hash function output, which is 16 octets for MD2 and MD5 and 20 octets for SHA-1. PBKDF1 is compatible with the key derivation process in PKCS #5 v1.5. PBKDF1 is recommended only for compatibility with existing applications since the keys it produces may not be large enough for some applications.

PBKDF2 applies a pseudorandom function (see Appendix B.1 for an example) to derive keys. The length of the derived key is essentially unbounded. (However, the maximum effective search space for the derived key may be limited by the structure of the underlying pseudorandom function. See Appendix B.1 for further discussion.) PBKDF2 is recommended for new applications.

Do this:

openssl enc -aes-256-cbc -pbkdf2 -iter 20000 -in hello -out hello.enc -k meow

openssl enc -d -aes-256-cbc -pbkdf2 -iter 20000 -in hello.enc -out hello.out

Note: Iterations in decryption have to be the same as iterations in encryption.

Iterations have to be a minimum of 10000. Here is a good answer on the number of iterations: https://security.stackexchange.com/a/3993

Also... we've got enough people here recommending GPG. Read the damn question.

What does "javascript:void(0)" mean?

There is a huge difference in the behaviour of # vs javascript:void(0);.

# scrolls you to the top of the page but javascript:void(0); does not.

This is very important if you are coding dynamic pages because the user does not want to go back to the top when they click a link on the page.

proper hibernate annotation for byte[]

I have finally got this working. It expands on the solution from A. Garcia, however, since the problem lies in the hibernate type MaterializedBlob type just mapping Blob > bytea is not sufficient, we need a replacement for MaterializedBlobType which works with hibernates broken blob support. This implementation only works with bytea, but maybe the guy from the JIRA issue who wanted OID could contribute an OID implementation.

Sadly replacing these types at runtime is a pain, since they should be part of the Dialect. If only this JIRA enhanement gets into 3.6 it would be possible.

public class PostgresqlMateralizedBlobType extends AbstractSingleColumnStandardBasicType<byte[]> {
 public static final PostgresqlMateralizedBlobType INSTANCE = new PostgresqlMateralizedBlobType();

 public PostgresqlMateralizedBlobType() {
  super( PostgresqlBlobTypeDescriptor.INSTANCE, PrimitiveByteArrayTypeDescriptor.INSTANCE );
 }

  public String getName() {
   return "materialized_blob";
  }
}

Much of this could probably be static (does getBinder() really need a new instance?), but I don't really understand the hibernate internal so this is mostly copy + paste + modify.

public class PostgresqlBlobTypeDescriptor extends BlobTypeDescriptor implements SqlTypeDescriptor {
  public static final BlobTypeDescriptor INSTANCE = new PostgresqlBlobTypeDescriptor();

  public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
   return new PostgresqlBlobBinder<X>(javaTypeDescriptor, this);
  }
  public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
   return new BasicExtractor<X>( javaTypeDescriptor, this ) {
    protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException { 
      return (X)rs.getBytes(name);
    }
   };
  }
}

public class PostgresqlBlobBinder<J> implements ValueBinder<J> {
 private final JavaTypeDescriptor<J> javaDescriptor;
 private final SqlTypeDescriptor sqlDescriptor;

 public PostgresqlBlobBinder(JavaTypeDescriptor<J> javaDescriptor, SqlTypeDescriptor sqlDescriptor) { 
  this.javaDescriptor = javaDescriptor; this.sqlDescriptor = sqlDescriptor;
 }  
 ...
 public final void bind(PreparedStatement st, J value, int index, WrapperOptions options) 
 throws SQLException {
  st.setBytes(index, (byte[])value);
 }
}

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)

From: http://technet.microsoft.com/en-us/library/ee681792.aspx:

"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

Enabling HTTPS on express.js

In express.js (since version 3) you should use that syntax:

var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

// your express configuration here

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

httpServer.listen(8080);
httpsServer.listen(8443);

In that way you provide express middleware to the native http/https server

If you want your app running on ports below 1024, you will need to use sudo command (not recommended) or use a reverse proxy (e.g. nginx, haproxy).

How to sort a List<Object> alphabetically using Object name field

public class ObjectComparator implements Comparator<Object> {

    public int compare(Object obj1, Object obj2) {
        return obj1.getName().compareTo(obj2.getName());
    }

}

Please replace Object with your class which contains name field

Usage:

ObjectComparator comparator = new ObjectComparator();
Collections.sort(list, comparator);

How to update Identity Column in SQL Server?

I have solved this problem firstly using DBCC and then using insert. For example if your table is

Firstly set new current ID Value on the table as NEW_RESEED_VALUE

MyTable { IDCol, colA, colB }

    DBCC CHECKIDENT('MyTable', RESEED, NEW_RESEED_VALUE)

then you can use

    insert into MyTable (colA, ColB) select colA, colB from MyTable

This would duplicate all your records but using new IDCol value starting as NEW_RESEED_VALUE. You can then remove higher ID Value duplicate rows once your have removed/moved their foreign key references, if any.

How to save password when using Subversion from the console

All methods mention here are not working for me. I built Subversion from source, and I found out, I must run configure with --enable-plaintext-password-storage to support this feature.

Install psycopg2 on Ubuntu

This works for me in Ubuntu 12.04 and 15.10

if pip not installed:

sudo apt-get install python-pip

and then:

sudo apt-get update
sudo apt-get install libpq-dev python-dev
sudo pip install psycopg2

How to convert current date to epoch timestamp?

if you want UTC try some of the gm functions:

import time
import calendar

date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
utc_epoch = calendar.timegm(time.strptime(date_time, pattern))
print utc_epoch

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

I change my APIs as * cglib --- to ---> cglib-nodep-2.2.jar * cglib-asm --- to ---> cglib-asm.jar (i.e. latest one )

jQuery: Change button text on click

its work short code

$('.SeeMore2').click(function(){ var $this = $(this).toggleClass('SeeMore2'); if($(this).hasClass('SeeMore2')) { $(this).text('See More');
} else { $(this).text('See Less'); } });

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

Cause you need to add jQuery library to your file:

jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.

<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>

Jquery $.ajax fails in IE on cross domain calls

I have the same problem in IE, I solved it by replacing:

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

To

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

So basically upgrade your jquery version.

Unable to show a Git tree in terminal

Keeping your commands short will make them easier to remember:

git log --graph --oneline

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

This happens when you pull and all files were executable in the remote repository. Making them executable again will set everything back to normal again.

chmod +x <yourfile> //For one file
chmod +x folder/* // For files in a folder

You might need to do:

chmod -x <file> // Removes execute bit

instead, for files that was not set as executable and that was changed because of the above operation. There is a better way to do this but this is just a very quick and dirty fix.

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

If it gets into the selinux arena you've got a much more complicated issue. It's not a good idea to remove the selinux protection but to embrace it and use the tools that were designed to manage it.

If you are serving content out of /var/www/abc, you can verify the selinux permissions with a Z appended to the normal ls -l command. i.e. ls -laZ will give the selinux context.

To add a directory to be served by selinux you can use the semanage command like this. This will change the label on /var/www/abc to httpd_sys_content_t

semanage fcontext -a -t httpd_sys_content_t /var/www/abc

this will update the label for /var/www/abc

restorecon /var/www/abc 

This answer was taken from unixmen and modified to fit this question. I had been searching for this answer for a while and finally found it so felt like I needed to share somewhere. Hope it helps someone.

How do you make an element "flash" in jQuery

Would a pulse effect(offline) JQuery plugin be appropriate for what you are looking for ?

You can add a duration for limiting the pulse effect in time.


As mentioned by J-P in the comments, there is now his updated pulse plugin.
See his GitHub repo. And here is a demo.