Programs & Examples On #Eventual consistency

Eventual consistency is a consistency model used in distributed computing that informally guarantees that, if no new updates are made to a given data item, eventually all accesses to that item will return the last updated value.

How can a windows service programmatically restart itself?

The better approach may be to utilize the NT Service as a wrapper for your application. When the NT Service is started, your application can start in an "idle" mode waiting for the command to start (or be configured to start automatically).

Think of a car, when it's started it begins in an idle state, waiting for your command to go forward or reverse. This also allows for other benefits, such as better remote administration as you can choose how to expose your application.

Which characters are valid/invalid in a JSON key name?

It is worth mentioning that while starting the keys with numbers is valid, it could cause some unintended issues.

Example:

var testObject = {
    "1tile": "test value"
};
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround

Return a value of '1' a referenced cell is empty

You can use:

=IF(ISBLANK(A1),1,0)

but you should be careful what you mean by empty cell. I've been caught out by this before. If you want to know if a cell is truly blank, isblank, as above, will work. Unfortunately, you sometimes also need to know if it just contains no useful data.

The expression:

=IF(ISBLANK(A1),TRUE,(TRIM(A1)=""))

will return true for cells that are either truly blank, or contain nothing but white space.

Here's the results when column A contains varying amounts of spaces, column B contains the length (so you know how many spaces) and column C contains the result of the above expression:

<-A-> <-B-> <-C->
        0   TRUE
        1   TRUE
        2   TRUE
        3   TRUE
        4   TRUE
        5   TRUE
  a     1   FALSE
<-A-> <-B-> <-C->

To return 1 if the cell is blank or white space and 0 otherwise:

=IF(ISBLANK(A1),1,if(TRIM(A1)="",1,0))

will do the trick.

This trick comes in handy when the cell that you're checking is actually the result of an Excel function. Many Excel functions (such as trim) will return an empty string rather than a blank cell.

You can see this in action with a new sheet. Leave cell A1 as-is and set A2 to =trim(a1).

Then set B1 to =isblank(a1) and B2 to isblank(a2). You'll see that the former is true while the latter is false.

How to get the current directory in a C program?

Although the question is tagged Unix, people also get to visit it when their target platform is Windows, and the answer for Windows is the GetCurrentDirectory() function:

DWORD WINAPI GetCurrentDirectory(
  _In_  DWORD  nBufferLength,
  _Out_ LPTSTR lpBuffer
);

These answers apply to both C and C++ code.

Link suggested by user4581301 in a comment to another question, and verified as the current top choice with a Google search 'site:microsoft.com getcurrentdirectory'.

How to use css style in php

css :hover kinda is like js onmouseover

row1 {
    // your css
}
row1:hover {
    color: red;
}
row1:hover #a, .b, .c:nth-child[3] {
    border: 1px solid red;
}

not too sure how it works but css applies styles to echo'ed ids

How to read XML response from a URL in java?

If you want to print XML directly onto the screen you can use TransformerFactory

URL url = new URL(urlString);
URLConnection conn = url.openConnection();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());

TransformerFactory transformerFactory= TransformerFactory.newInstance();
Transformer xform = transformerFactory.newTransformer();

// that’s the default xform; use a stylesheet to get a real one
xform.transform(new DOMSource(doc), new StreamResult(System.out));

Adjust icon size of Floating action button (fab)

Try to use app:maxImageSize="56dp" instead of the above answers after you update your support library to v28.0.0

Can I give a default value to parameters or optional parameters in C# functions?

It is only possible as from C# 4.0

However, when you use a version of C#, prior to 4.0, you can work around this by using overloaded methods:

public void Func( int i, int j )
{
    Console.WriteLine (String.Format ("i = {0}, j = {1}", i, j));
}

public void Func( int i )
{
    Func (i, 4);
}

public void Func ()
{
    Func (5);
}

(Or, you can upgrade to C# 4.0 offcourse).

How to give a delay in loop execution using Qt

C++11 has some portable timer stuff. Check out sleep_for.

How do I create a new user in a SQL Azure database?

I followed the answers here but when I tried to connect with my new user, I got an error message stating "The server principal 'newuser' is not able to access the database 'master' under the current security context".

I had to also create a new user in the master table to successfully log in with SSMS.

USE [master]
GO
CREATE LOGIN [newuser] WITH PASSWORD=N'blahpw'
GO
CREATE USER [newuser] FOR LOGIN [newuser] WITH DEFAULT_SCHEMA=[dbo]
GO

USE [MyDatabase]
CREATE USER newuser FOR LOGIN newuser WITH DEFAULT_SCHEMA = dbo
GO
EXEC sp_addrolemember N'db_owner', N'newuser'
GO

Multiprocessing a for loop?

You can use multiprocessing.Pool:

from multiprocessing import Pool
class Engine(object):
    def __init__(self, parameters):
        self.parameters = parameters
    def __call__(self, filename):
        sci = fits.open(filename + '.fits')
        manipulated = manipulate_image(sci, self.parameters)
        return manipulated

try:
    pool = Pool(8) # on 8 processors
    engine = Engine(my_parameters)
    data_outputs = pool.map(engine, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen
    pool.close()
    pool.join()

Commenting code in Notepad++

In your n++ editor, you can go to Setting > Shortcut mapper and find all shortcut information as well as you can edit them :)

How to convert a string to utf-8 in Python

In Python 3.6, they do not have a built-in unicode() method. Strings are already stored as unicode by default and no conversion is required. Example:

my_str = "\u221a25"
print(my_str)
>>> v25

Iterate over elements of List and Map using JSTL <c:forEach> tag

try this

<c:forEach items="${list}" var="map">
    <tr>
        <c:forEach items="${map}" var="entry">

            <td>${entry.value}</td>

        </c:forEach>
    </tr>
</c:forEach>

Get the last inserted row ID (with SQL statement)

You can use:

SELECT IDENT_CURRENT('tablename')

to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)

SELECT IDENT_CURRENT('MyTable')

SELECT IDENT_CURRENT('YourTable')

This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

How to make ConstraintLayout work with percentage values?

With the ConstraintLayout v1.1.2, the dimension should be set to 0dp and then set the layout_constraintWidth_percent or layout_constraintHeight_percent attributes to a value between 0 and 1 like :

<!-- 50% width centered Button -->
<Button
    android:id="@+id/button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintWidth_percent=".5" />

(You don't need to set app:layout_constraintWidth_default="percent" or app:layout_constraintHeight_default="percent" with ConstraintLayout 1.1.2 and following versions)

What is the difference between concurrent programming and parallel programming?

Concurrency and Parallelism Source

In a multithreaded process on a single processor, the processor can switch execution resources between threads, resulting in concurrent execution.

In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run on a separate processor at the same time, resulting in parallel execution.

When the process has fewer or as many threads as there are processors, the threads support system in conjunction with the operating environment ensure that each thread runs on a different processor.

For example, in a matrix multiplication that has the same number of threads and processors, each thread (and each processor) computes a row of the result.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException in simple words is -> you have 10 students in your class (int array size 10) and you want to view the value of the 11th student (a student who does not exist)

if you make this int i[3] then i takes values i[0] i[1] i[2]

for your problem try this code structure

double[] array = new double[50];

    for (int i = 0; i < 24; i++) {

    }

    for (int j = 25; j < 50; j++) {

    }

How to load specific image from assets with Swift

You cannot load images directly with @2x or @3x, system selects appropriate image automatically, just specify the name using UIImage:

UIImage(named: "green-square-Retina")

Array of arrays (Python/NumPy)

a=np.array([[1,2,3],[4,5,6]])

a.tolist()

tolist method mentioned above will return the nested Python list

How do I set a JLabel's background color?

Use

label.setOpaque(true);

Otherwise the background is not painted, since the default of opaque is false for JLabel.

From the JavaDocs:

If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.

For more information, read the Java Tutorial How to Use Labels.

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

add new element in laravel collection object

It looks like you have everything correct according to Laravel docs, but you have a typo

$item->push($product);

Should be

$items->push($product);

I also want to think the actual method you're looking for is put

$items->put('products', $product);

How to add values in a variable in Unix shell scripting?

What is count1 set to? If it is not set, it looks like the empty string - and that would lead to an invalid expression. Which shell are you using?

In Bash 3.x on MacOS X 10.7.1:

$ count7=0
$ count7=$(($count7 + $count1))
-sh: 0 + : syntax error: operand expected (error token is " ")
$ count1=2
$ count7=$(($count7 + $count1))
$ echo $count7
2
$

You could also use ${count1:-0} to add 0 if $count1 is unset.

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

How do I link to part of a page? (hash?)

You have two options:

You can either put an anchor in your document as follows:

<a name="ref"></a>

Or else you give an id to a any HTML element:

<h1 id="ref">Heading</h1>

Then simply append the hash #ref to the URL of your link to jump to the desired reference. Example:

<a href="document.html#ref">Jump to ref in document.html</a>

Android checkbox style

Note: Using Android Support Library v22.1.0 and targeting API level 11 and up? Scroll down to the last update.


My application style is set to Theme.Holo which is dark and I would like the check boxes on my list view to be of style Theme.Holo.Light. I am not trying to create a custom style. The code below doesn't seem to work, nothing happens at all.

At first it may not be apparent why the system exhibits this behaviour, but when you actually look into the mechanics you can easily deduce it. Let me take you through it step by step.

First, let's take a look what the Widget.Holo.Light.CompoundButton.CheckBox style defines. To make things more clear, I've also added the 'regular' (non-light) style definition.

<style name="Widget.Holo.Light.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

<style name="Widget.Holo.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

As you can see, both are empty declarations that simply wrap Widget.CompoundButton.CheckBox in a different name. So let's look at that parent style.

<style name="Widget.CompoundButton.CheckBox">
    <item name="android:background">@android:drawable/btn_check_label_background</item>
    <item name="android:button">?android:attr/listChoiceIndicatorMultiple</item>
</style>

This style references both a background and button drawable. btn_check_label_background is simply a 9-patch and hence not very interesting with respect to this matter. However, ?android:attr/listChoiceIndicatorMultiple indicates that some attribute based on the current theme (this is important to realise) will determine the actual look of the CheckBox.

As listChoiceIndicatorMultiple is a theme attribute, you will find multiple declarations for it - one for each theme (or none if it gets inherited from a parent theme). This will look as follows (with other attributes omitted for clarity):

<style name="Theme">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check</item>
    ...
</style>

<style name="Theme.Holo">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_dark</item>
    ...
</style>

<style name="Theme.Holo.Light" parent="Theme.Light">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_light</item>
    ...
</style>

So this where the real magic happens: based on the theme's listChoiceIndicatorMultiple attribute, the actual appearance of the CheckBox is determined. The phenomenon you're seeing is now easily explained: since the appearance is theme-based (and not style-based, because that is merely an empty definition) and you're inheriting from Theme.Holo, you will always get the CheckBox appearance matching the theme.

Now, if you want to change your CheckBox's appearance to the Holo.Light version, you will need to take a copy of those resources, add them to your local assets and use a custom style to apply them.

As for your second question:

Also can you set styles to individual widgets if you set a style to the application?

Absolutely, and they will override any activity- or application-set styles.

Is there any way to set a theme(style with images) to the checkbox widget. (...) Is there anyway to use this selector: link?


Update:

Let me start with saying again that you're not supposed to rely on Android's internal resources. There's a reason you can't just access the internal namespace as you please.

However, a way to access system resources after all is by doing an id lookup by name. Consider the following code snippet:

int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
((CheckBox) findViewById(R.id.checkbox)).setButtonDrawable(id);

The first line will actually return the resource id of the btn_check_holo_light drawable resource. Since we established earlier that this is the button selector that determines the look of the CheckBox, we can set it as 'button drawable' on the widget. The result is a CheckBox with the appearance of the Holo.Light version, no matter what theme/style you set on the application, activity or widget in xml. Since this sets only the button drawable, you will need to manually change other styling; e.g. with respect to the text appearance.

Below a screenshot showing the result. The top checkbox uses the method described above (I manually set the text colour to black in xml), while the second uses the default theme-based Holo styling (non-light, that is).

Screenshot showing the result


Update2:

With the introduction of Support Library v22.1.0, things have just gotten a lot easier! A quote from the release notes (my emphasis):

Lollipop added the ability to overwrite the theme at a view by view level by using the android:theme XML attribute - incredibly useful for things such as dark action bars on light activities. Now, AppCompat allows you to use android:theme for Toolbars (deprecating the app:theme used previously) and, even better, brings android:theme support to all views on API 11+ devices.

In other words: you can now apply a theme on a per-view basis, which makes solving the original problem a lot easier: just specify the theme you'd like to apply for the relevant view. I.e. in the context of the original question, compare the results of below:

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo" />

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo.Light" />

The first CheckBox is styled as if used in a dark theme, the second as if in a light theme, regardless of the actual theme set to your activity or application.

Of course you should no longer be using the Holo theme, but instead use Material.

how to redirect to external url from c# controller

Try this:

return Redirect("http://www.website.com");

Is there any quick way to get the last two characters in a string?

String value = "somestring";
String lastTwo = null;
if (value != null && value.length() >= 2) {  
    lastTwo = value.substring(value.length() - 2);
}

Parsing JSON from URL

You could use org.apache.commons.io.IOUtils for downloading and org.json.JSONTokener for parsing:

JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
System.out.println(jo.getString("version"));

How to convert numbers between hexadecimal and decimal

class HexToDecimal
{
    static void Main()
    {
        while (true)
        {
            Console.Write("Enter digit number to convert: ");
            int n = int.Parse(Console.ReadLine()); // set hexadecimal digit number  
            Console.Write("Enter hexadecimal number: ");
            string str = Console.ReadLine();
            str.Reverse();

            char[] ch = str.ToCharArray();
            int[] intarray = new int[n];

            decimal decimalval = 0;

            for (int i = ch.Length - 1; i >= 0; i--)
            {
                if (ch[i] == '0')
                    intarray[i] = 0;
                if (ch[i] == '1')
                    intarray[i] = 1;
                if (ch[i] == '2')
                    intarray[i] = 2;
                if (ch[i] == '3')
                    intarray[i] = 3;
                if (ch[i] == '4')
                    intarray[i] = 4;
                if (ch[i] == '5')
                    intarray[i] = 5;
                if (ch[i] == '6')
                    intarray[i] = 6;
                if (ch[i] == '7')
                    intarray[i] = 7;
                if (ch[i] == '8')
                    intarray[i] = 8;
                if (ch[i] == '9')
                    intarray[i] = 9;
                if (ch[i] == 'A')
                    intarray[i] = 10;
                if (ch[i] == 'B')
                    intarray[i] = 11;
                if (ch[i] == 'C')
                    intarray[i] = 12;
                if (ch[i] == 'D')
                    intarray[i] = 13;
                if (ch[i] == 'E')
                    intarray[i] = 14;
                if (ch[i] == 'F')
                    intarray[i] = 15;

                decimalval += intarray[i] * (decimal)Math.Pow(16, ch.Length - 1 - i);

            }

            Console.WriteLine(decimalval);
        }

    }

}

How to SSH to a VirtualBox guest externally through a host?

You can also initiate a port forward TO your HOST, OR ANY OTHER SERVER, from your Guest. This is especially useful if your Guest is 'locked' or can't otherwise complete the ModifyVM option (e.g. no permission to VBoxManage).

Three minor requirements are 1) you are/can log into the VirtualBox Guest (via 'console' GUI, another Guest, etc), 2) you have an account on the VirtualBox HOST (or other Server), and 3) SSH and TCP forwarding is not blocked.

Presuming you can meet the 3 requirements, these are the steps:

  1. On the Guest, run netstat -rn and find the Gateway address to the default route destination 0.0.0.0. Let's say it's "10.0.2.2". This 'Gateway' address is (one of) the VirtualBox Host virtual IP(s).
  2. On the Guest, run ssh -R 2222:localhost:22 10.0.2.2 where "10.0.2.2" is the VirtualBox server's IP address -OR- any other server IP you wish to port forward to.
  3. On the Host, run ssh 10.0.2.2 -p2222 where 10.0.2.2 is the default gateway/VBHost virtual IP found in step 1. If it is NOT the VirtualBox host you are port forwarding to, then the command is ssh localhost -p2222

Horizontal scroll css?

use max-width instead of width

max-width:530px;

demo:http://jsfiddle.net/FPBWr/161/

Procedure or function !!! has too many arguments specified

This answer is based on the title and not the specific case in the original post.

I had an insert procedure that kept throwing this annoying error, and even though the error says, "procedure....has too many arguments specified," the fact is that the procedure did NOT have enough arguments.

The table had an incremental id column, and since it is incremental, I did not bother to add it as a variable/argument to the proc, but it turned out that it is needed, so I added it as @Id and viola like they say...it works.

Check that an email address is valid on iOS

Heres a good one with NSRegularExpression that's working for me.

[text rangeOfString:@"^.+@.+\\..{2,}$" options:NSRegularExpressionSearch].location != NSNotFound;

You can insert whatever regex you want but I like being able to do it in one line.

Abstract methods in Python

You can use six and abc to construct a class for both python2 and python3 efficiently as follows:

import six
import abc

@six.add_metaclass(abc.ABCMeta)
class MyClass(object):
    """
    documentation
    """

    @abc.abstractmethod
    def initialize(self, para=None):
        """
        documentation
        """
        raise NotImplementedError

This is an awesome document of it.

How to sort an array of ints using a custom comparator?

By transforming your int array into an Integer one and then using public static <T> void Arrays.sort(T[] a, Comparator<? super T> c) (the first step is only needed as I fear autoboxing may bot work on arrays).

How to pass password to scp?

You can use the 'expect' script on unix/terminal

For example create 'test.exp' :

#!/usr/bin/expect
        spawn scp  /usr/bin/file.txt root@<ServerLocation>:/home
        set pass "Your_Password"
        expect {
        password: {send "$pass\r"; exp_continue}
                  }

run the script

expect test.exp 

I hope that helps.

Wrap a text within only two lines inside div

Another simple and quick solution

.giveMeEllipsis {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: N; /* number of lines to show */
   line-height: X;        /* fallback */
   max-height: X*N;       /* fallback */
}

The reference to the original question and answer is here

How to use S_ISREG() and S_ISDIR() POSIX Macros?

[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);

int main(int argc, char *argv[]){

  DIR *dip;
  struct dirent *dit;
  struct stat statbuf;
  char currentPath[FILENAME_MAX];
  int depth = 0; /*Used to correctly space output*/

  /*Open Current Directory*/
  if((dip = opendir(".")) == NULL)
    return errno;

  /*Store Current Working Directory in currentPath*/
  if((getcwd(currentPath, FILENAME_MAX)) == NULL)
    return errno;

  /*Read all items in directory*/
  while((dit = readdir(dip)) != NULL){

    /*Skips . and ..*/
    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    /*Correctly forms the path for stat and then resets it for rest of algorithm*/
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    if(stat(currentPath, &statbuf) == -1){
      perror("stat");
      return errno;
    }
    getcwd(currentPath, FILENAME_MAX);


    /*Checks if current item is of the type file (type 8) and no command line arguments*/
    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*If a command line argument is given, checks for filename match*/
    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
      if(strcmp(dit->d_name, argv[1]) == 0)
         printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*Checks if current item is of the type directory (type 4)*/
    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);

  }
  closedir(dip);
  return 0;
}

/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf, 
        char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  if((dip = opendir(currentPath)) == NULL)
    printf("Error: Failed to open Directory ==> %s\n", currentPath);

  while((dit = readdir(dip)) != NULL){

    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    stat(currentPath, &statbuf);
    getcwd(currentPath, FILENAME_MAX);

    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
      for(i = 0; i < depth; i++)
    printf("    ");
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
    }

    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
      if(strcmp(dit->d_name, argv[1]) == 0){
    for(i = 0; i < depth; i++)
      printf("    ");
    printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
      }
    }

    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);
  }
  /*Changing back here is necessary because of how stat is done*/
    chdir("..");
    closedir(dip);
}

void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf, 
          char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  strcat(currentPath, "/");
  strcat(currentPath, dit->d_name);

  /*If two directories exist at the same level the path
    is built wrong and needs to be corrected*/
  if((chdir(currentPath)) == -1){
    chdir("..");
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);

    for(i = 0; i < depth; i++)
      printf ("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }

  else{
    for(i =0; i < depth; i++)
      printf("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    chdir(currentPath);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }
}

How to use AND in IF Statement

If there are no typos in the question, you got the conditions wrong:

You said this:

IF cells (i,"A") contains the text 'Miami'

...but your code says:

If Cells(i, "A") <> "Miami"

--> <> means that the value of the cell is not equal to "Miami", so you're not checking what you think you are checking.

I guess you want this instead:

If Cells(i, "A") like "*Miami*"

EDIT:

Sorry, but I can't really help you more. As I already said in a comment, I'm no Excel VBA expert.
Normally I would open Excel now and try your code myself, but I don't even have Excel on any of my machines at home (I use OpenOffice).

Just one general thing: can you identify the row that does not work?
Maybe this helps someone else to answer the question.

Does it ever execute (or at least try to execute) the Cells(i, "C").Value = "BA" line?
Or is the If Cells(i, "A") like "*Miami*" stuff already False?
If yes, try checking just one cell and see if that works.

AutoComplete TextBox in WPF

I know this is a very old question but I want to add an answer I have come up with.

First you need a handler for your normal TextChanged event handler for the TextBox:

private bool InProg;
internal void TBTextChanged(object sender, TextChangedEventArgs e)
            {
            var change = e.Changes.FirstOrDefault();
            if ( !InProg )
                {
                InProg = true;
                var culture = new CultureInfo(CultureInfo.CurrentCulture.Name);
                var source = ( (TextBox)sender );
                    if ( ( ( change.AddedLength - change.RemovedLength ) > 0 || source.Text.Length > 0 ) && !DelKeyPressed )
                        {
                         if ( Files.Where(x => x.IndexOf(source.Text, StringComparison.CurrentCultureIgnoreCase) == 0 ).Count() > 0 )
                            {
                            var _appendtxt = Files.FirstOrDefault(ap => ( culture.CompareInfo.IndexOf(ap, source.Text, CompareOptions.IgnoreCase) == 0 ));
                            _appendtxt = _appendtxt.Remove(0, change.Offset + 1);
                            source.Text += _appendtxt;
                            source.SelectionStart = change.Offset + 1;
                            source.SelectionLength = source.Text.Length;
                            }
                        }
                InProg = false;
                }
            }

Then make a simple PreviewKeyDown handler:

    private static bool DelKeyPressed;
    internal static void DelPressed(object sender, KeyEventArgs e)
    { if ( e.Key == Key.Back ) { DelKeyPressed = true; } else { DelKeyPressed = false; } }

In this example "Files" is a list of directory names created on application startup.

Then just attach the handlers:

public class YourClass
  {
  public YourClass()
    {
    YourTextbox.PreviewKeyDown += DelPressed;
    YourTextbox.TextChanged += TBTextChanged;
    }
  }

With this whatever you choose to put in the List will be used for the autocomplete box. This may not be a great option if you expect to have an enormous list for the autocomplete but in my app it only ever sees 20-50 items so it cycles through very quick.

Change text color with Javascript?

You set the style per element and not by its content:

function init() { 
  document.getElementById("about").style.color = 'blue';
}

With innerHTML you get/set the content of an element. So if you would want to modify your title, innerHTML would be the way to go.

In your case, however, you just want to modify a property of the element (change the color of the text inside it), so you address the style property of the element itself.

Use of Greater Than Symbol in XML

You can try to use CDATA to put all your symbols that don't work.

An example of something that will work in XML:

<![CDATA[
function matchwo(a,b) {
    if (a < b && a < 0) {
        return 1;
   } else {
       return 0;
   }
}
]]>

And of course you can use &lt; and &gt;.

How to unblock with mysqladmin flush hosts

mysqladmin is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).

You type that command from a shell prompt.

Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:

FLUSH HOSTS;

http://dev.mysql.com/doc/refman/5.6/en/flush.html

http://dev.mysql.com/doc/refman/5.6/en/mysqladmin.html

oracle - what statements need to be committed?

And a key point - although TRUNCATE TABLE seems like a DELETE with no WHERE clause, TRUNCATE is not DML, it is DDL. DELETE requires a COMMIT, but TRUNCATE does not.

xxxxxx.exe is not a valid Win32 application

For me, this helped: 1. Configuration properties/General/Platform Toolset = Windows XP (V110_xp) 2. C/C++ Preprocessor definitions, add "WIN32" 3. Linker/System/Minimum required version = 5.01

What does `ValueError: cannot reindex from a duplicate axis` mean?

Indices with duplicate values often arise if you create a DataFrame by concatenating other DataFrames. IF you don't care about preserving the values of your index, and you want them to be unique values, when you concatenate the the data, set ignore_index=True.

Alternatively, to overwrite your current index with a new one, instead of using df.reindex(), set:

df.index = new_index

how concatenate two variables in batch script?

You can do it without setlocal, because of the setlocal command the variable won't survive an endlocal because it was created in setlocal. In this way the variable will be defined the right way.

To do that use this code:

set var1=A

set var2=B

set AB=hi

call set newvar=%%%var1%%var2%%%

echo %newvar% 

Note: You MUST use call before you set the variable or it won't work.

Promise Error: Objects are not valid as a React child

You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

render: function() {
  return (
    <span>
      // This will go through all the elements in arrayFromJson and
      // render each one as a <SomeComponent /> with data from the object
      {this.state.arrayFromJson.map(function(object) {
        return (
          <SomeComponent key={object.id} data={object} />
        );
      })}
    </span>
  );
}

How to capitalize the first letter in a String in Ruby

Rails 5+

As of Active Support and Rails 5.0.0.beta4 you can use one of both methods: String#upcase_first or ActiveSupport::Inflector#upcase_first.

"my API is great".upcase_first #=> "My API is great"
"?????".upcase_first           #=> "?????"
"?????".upcase_first           #=> "?????"
"NASA".upcase_first            #=> "NASA"
"MHz".upcase_first             #=> "MHz"
"sputnik".upcase_first         #=> "Sputnik"

Check "Rails 5: New upcase_first Method" for more info.

Difference between two dates in years, months, days in JavaScript

Neither of the codes work for me, so I use this instead for months and days:

function monthDiff(d2, d1) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth() + 1;
    return months <= 0 ? 0 : months;
}

function daysInMonth(date) {
    return new Date(date.getYear(), date.getMonth() + 1, 0).getDate();
}    

function diffDate(date1, date2) {
    if (date2 && date2.getTime() && !isNaN(date2.getTime())) {
        var months = monthDiff(date1, date2);
        var days = 0;

        if (date1.getUTCDate() >= date2.getUTCDate()) {
            days = date1.getUTCDate() - date2.getUTCDate();
        }
        else {
            months--;
            days = date1.getUTCDate() - date2.getUTCDate() + daysInMonth(date2);
        }

        // Use the variables months and days how you need them.
    }
}

SQL - How to find the highest number in a column?

If you're talking MS SQL, here's the most efficient way. This retrieves the current identity seed from a table based on whatever column is the identity.

select IDENT_CURRENT('TableName') as LastIdentity

Using MAX(id) is more generic, but for example I have an table with 400 million rows that takes 2 minutes to get the MAX(id). IDENT_CURRENT is nearly instantaneous...

What is the best way to remove the first element from an array?

To sum up, the quick linkedlist method:

List<String> llist = new LinkedList<String>(Arrays.asList(oldArray));
llist.remove(0);

Difference Between Schema / Database in MySQL

Microsoft SQL Server for instance, Schemas refer to a single user and is another level of a container in the order of indicating the server, database, schema, tables, and objects.

For example, when you are intending to update dbo.table_a and the syntax isn't full qualified such as UPDATE table.a the DBMS can't decide to use the intended table. Essentially by default the DBMS will utilize myuser.table_a

jQuery: Slide left and slide right

If you don't want something bloated like jQuery UI, try my custom animations: https://github.com/yckart/jquery-custom-animations

For you, blindLeftToggle and blindRightToggle is the appropriate choice.

http://jsfiddle.net/ARTsinn/65QsU/

What is the difference between IEnumerator and IEnumerable?

An Enumerator shows you the items in a list or collection. Each instance of an Enumerator is at a certain position (the 1st element, the 7th element, etc) and can give you that element (IEnumerator.Current) or move to the next one (IEnumerator.MoveNext). When you write a foreach loop in C#, the compiler generates code that uses an Enumerator.

An Enumerable is a class that can give you Enumerators. It has a method called GetEnumerator which gives you an Enumerator that looks at its items. When you write a foreach loop in C#, the code that it generates calls GetEnumerator to create the Enumerator used by the loop.

Docker can't connect to docker daemon

If all the other solutions above don't work you can try checking the ownership of /var/run/docker.sock:

ls -l /var/run/docker.sock

If you're not the owner then change ownership with the command:

sudo chown *your-username* /var/run/docker.sock

Then you can go ahead and try executing the Docker commands hassle-free :D

Sharing a variable between multiple different threads

Using static will not help your case.

Using synchronize locks a variable when it is in use by another thread.

You should use volatile keyword to keep the variable updated among all threads.

Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread safe. Thread safe means that a method or class instance can be used by multiple threads at the same time without any problem.

How can I change the value of the elements in a vector?

You can access the values in a vector just as you access any other array.

for (int i = 0; i < v.size(); i++)
{         
  v[i] -= 1;         
} 

concat scope variables into string in angular directive expression

You can just concat the values using +

<a ng-click="$navigate.go('#/path/' + obj.val1 + '/' + obj.val2)">{{obj.val1}}, {{obj.val2}}</a>

Simple example on jsfiddle

I am sure the code you posted is a simplified example, if your path building is more complex I would recommend extracting out a function (or service) that would build your urls so you can effectively write unit test.

How to log as much information as possible for a Java Exception?

What's wrong with the printStacktrace() method provided by Throwable (and thus every exception)? It shows all the info you requested, including the type, message, and stack trace of the root exception and all (nested) causes. In Java 7, it even shows you the information about "supressed" exceptions that might occur in a try-with-resources statement.

Of course you wouldn't want to write to System.err, which the no-argument version of the method does, so instead use one of the available overloads.

In particular, if you just want to get a String:

  Exception e = ...
  StringWriter sw = new StringWriter();
  e.printStackTrace(new PrintWriter(sw));
  String exceptionDetails = sw.toString();

If you happen to use the great Guava library, it provides a utility method doing this: com.google.common.base.Throwables#getStackTraceAsString(Throwable).

Understanding inplace=True

The inplace parameter:

df.dropna(axis='index', how='all', inplace=True)

in Pandas and in general means:

1. Pandas creates a copy of the original data

2. ... does some computation on it

3. ... assigns the results to the original data.

4. ... deletes the copy.

As you can read in the rest of my answer's further below, we still can have good reason to use this parameter i.e. the inplace operations, but we should avoid it if we can, as it generate more issues, as:

1. Your code will be harder to debug (Actually SettingwithCopyWarning stands for warning you to this possible problem)

2. Conflict with method chaining


So there is even case when we should use it yet?

Definitely yes. If we use pandas or any tool for handeling huge dataset, we can easily face the situation, where some big data can consume our entire memory. To avoid this unwanted effect we can use some technics like method chaining:

(
    wine.rename(columns={"color_intensity": "ci"})
    .assign(color_filter=lambda x: np.where((x.hue > 1) & (x.ci > 7), 1, 0))
    .query("alcohol > 14 and color_filter == 1")
    .sort_values("alcohol", ascending=False)
    .reset_index(drop=True)
    .loc[:, ["alcohol", "ci", "hue"]]
)

which make our code more compact (though harder to interpret and debug too) and consumes less memory as the chained methods works with the other method's returned values, thus resulting in only one copy of the input data. We can see clearly, that we will have 2 x original data memory consumption after this operations.

Or we can use inplace parameter (though harder to interpret and debug too) our memory consumption will be 2 x original data, but our memory consumption after this operation remains 1 x original data, which if somebody whenever worked with huge datasets exactly knows can be a big benefit.


Final conclusion:

Avoid using inplace parameter unless you don't work with huge data and be aware of its possible issues in case of still using of it.

Is there Selected Tab Changed Event in the standard WPF Tab Control

If anyone use WPF Modern UI,they cant use OnTabSelected event.but they can use SelectedSourceChanged event.

like this

<mui:ModernTab Layout="Tab" SelectedSourceChanged="ModernTab_SelectedSourceChanged" Background="Blue" AllowDrop="True" Name="tabcontroller" >

C# code is

private void ModernTab_SelectedSourceChanged(object sender, SourceEventArgs e)
    {
          var links = ((ModernTab)sender).Links;

          var link = this.tabcontroller.Links.FirstOrDefault(l => l.Source == e.Source);

          if (link != null) {
              var index = this.tabcontroller.Links.IndexOf(link);
              MessageBox.Show(index.ToString());
          }            
    }

mysql said: Cannot connect: invalid settings. xampp

it may be another mysqld instance running and stoped it with:

sudo service mysql stop

Worked for me.

TypeError: Can't convert 'int' object to str implicitly

You cannot concatenate a string with an int. You would need to convert your int to a string using the str function, or use formatting to format your output.

Change: -

print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")

to: -

print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))

or: -

print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")

or as per the comment, use , to pass different strings to your print function, rather than concatenating using +: -

print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")

Install Node.js on Ubuntu

Now you can simply install with:

sudo apt-get install nodejs
sudo apt-get install npm

Make sure you have the Python and C interpreters/compilers preinstalled. If not, perform:

sudo apt-get install python g++ make

Toolbar overlapping below status bar

For me, the problem was that I copied something from an example and used

<item name="android:windowTranslucentStatus">true</item>

just removing this fixed my problem.

How to change Elasticsearch max memory size

If you use the service wrapper provided in Elasticsearch's Github repository, found at https://github.com/elasticsearch/elasticsearch-servicewrapper, then the conf file at elasticsearch-servicewrapper / service / elasticsearch.conf controls memory settings. At the top of elasticsearch.conf is a parameter:

set.default.ES_HEAP_SIZE=1024

Just reduce this parameter, say to "set.default.ES_HEAP_SIZE=512", to reduce Elasticsearch's allotted memory.

Note that if you use the elasticsearch-wrapper, the ES_HEAP_SIZE provided in elasticsearch.conf OVERRIDES ALL OTHER SETTINGS. This took me a bit to figure out, since from the documentation, it seemed that heap memory could be set from elasticsearch.yml.

If your service wrapper settings are set somewhere else, such as at /etc/default/elasticsearch as in James's example, then set the ES_HEAP_SIZE there.

ldconfig error: is not a symbolic link

You need to include the path of the libraries inside /etc/ld.so.conf, and rerun ldconfig to upate the list

Other possibility is to include in the env variable LD_LIBRARY_PATH the path to your library, and rerun the executable.

check the symbolic links if they point to a valid library ...

You can add the path directly in /etc/ld.so.conf, without include...

run ldconfig -p to see whether your library is well included in the cache.

Cannot open include file with Visual Studio

For me, it helped to link the projects current directory as such:

In the properties -> C++ -> General window, instead of linking the path to the file in "additional include directories". Put "." and uncheck "inheret from parent or project defaults".

Hope this helps.

JPA eager fetch does not join

to join you can do multiple things (using eclipselink)

  • in jpql you can do left join fetch

  • in named query you can specify query hint

  • in TypedQuery you can say something like

    query.setHint("eclipselink.join-fetch", "e.projects.milestones");

  • there is also batch fetch hint

    query.setHint("eclipselink.batch", "e.address");

see

http://java-persistence-performance.blogspot.com/2010/08/batch-fetching-optimizing-object-graph.html

how to run vibrate continuously in iphone?

Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.

Mapping object to dictionary and vice versa

    public Dictionary<string, object> ToDictionary<T>(string key, T value)
    {
        try
        {
            var payload = new Dictionary<string, object>
            {
                { key, value }
            }; 
        } catch (Exception e)
        {
            return null;
        }
    }

    public T FromDictionary<T>(Dictionary<string, object> payload, string key)
    {
        try
        {
            JObject jObject = (JObject) payload[key];
            T t = jObject.ToObject<T>();
            return (t);
        }
        catch(Exception e) {
            return default(T);
        }
    }

How to input matrix (2D list) in Python?

Apart from the accepted answer, you can also initialise your rows in the following manner - matrix[i] = [0]*n

Therefore, the following piece of code will work -

m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []
# initialize the number of rows
for i in range(0,m):
    matrix += [0]
# initialize the matrix
for i in range (0,m):
    matrix[i] = [0]*n
for i in range (0,m):
    for j in range (0,n):
        print ('entry in row: ',i+1,' column: ',j+1)
        matrix[i][j] = int(input())
print (matrix)

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Reload parent window from child window

You can reload parent window location using :

window.opener.location.href = window.opener.location.href;

Salt and hash a password in Python

passlib seems to be useful if you need to use hashes stored by an existing system. If you have control of the format, use a modern hash like bcrypt or scrypt. At this time, bcrypt seems to be much easier to use from python.

passlib supports bcrypt, and it recommends installing py-bcrypt as a backend: http://pythonhosted.org/passlib/lib/passlib.hash.bcrypt.html

You could also use py-bcrypt directly if you don't want to install passlib. The readme has examples of basic use.

see also: How to use scrypt to generate hash for password and salt in Python

Merging multiple PDFs using iTextSharp in c#.net

Using iTextSharp.dll

protected void Page_Load(object sender, EventArgs e)
{
    String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
    MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
    if (System.IO.File.Exists(destinationFile))
        System.IO.File.Delete(destinationFile);

    string[] sSrcFile;
    sSrcFile = new string[2];

    string[] arr = new string[2];
    for (int i = 0; i <= sourceFiles.Length - 1; i++)
    {
        if (sourceFiles[i] != null)
        {
            if (sourceFiles[i].Trim() != "")
                arr[i] = sourceFiles[i].ToString();
        }
    }

    if (arr != null)
    {
        sSrcFile = new string[2];

        for (int ic = 0; ic <= arr.Length - 1; ic++)
        {
            sSrcFile[ic] = arr[ic].ToString();
        }
    }
    try
    {
        int f = 0;

        PdfReader reader = new PdfReader(sSrcFile[f]);
        int n = reader.NumberOfPages;
        Response.Write("There are " + n + " pages in the original file.");
        Document document = new Document(PageSize.A4);

        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));

        document.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;

        int rotation;
        while (f < sSrcFile.Length)
        {
            int i = 0;
            while (i < n)
            {
                i++;

                document.SetPageSize(PageSize.A4);
                document.NewPage();
                page = writer.GetImportedPage(reader, i);

                rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                Response.Write("\n Processed page " + i);
            }

            f++;
            if (f < sSrcFile.Length)
            {
                reader = new PdfReader(sSrcFile[f]);
                n = reader.NumberOfPages;
                Response.Write("There are " + n + " pages in the original file.");
            }
        }
        Response.Write("Success");
        document.Close();
    }
    catch (Exception e)
    {
        Response.Write(e.Message);
    }


}

For loop in Oracle SQL

You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:

-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
  k NUMBER:= 0;
BEGIN
  FOR i IN 1..10 LOOP
    k:= k+1;
    dbms_output.put_line(i||' '||k);
 END LOOP;
END;
/

-- Cursor FOR loop --
set serveroutput on
DECLARE
   CURSOR c1 IS SELECT * FROM scott.emp;
   i NUMBER:= 0;
BEGIN
  FOR e_rec IN c1 LOOP
  i:= i+1;
    dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
  END LOOP;
END;
/

-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
  FROM dual
CONNECT BY LEVEL <= 10
/

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

If you are using Symfony 2.7 or above, and don't want to include any additional bundle for serializing, maybe you can follow this way to seialize doctrine entities to json -

  1. In my (common, parent) controller, I have a function that prepares the serializer

    use Symfony\Component\Serializer\Encoder\JsonEncoder;
    use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
    use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
    use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
    use Symfony\Component\Serializer\Serializer;
    
    // -----------------------------
    
    /**
     * @return Serializer
     */
    protected function _getSerializer()
    {  
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
        $normalizer           = new ObjectNormalizer($classMetadataFactory);
    
        return new Serializer([$normalizer], [new JsonEncoder()]);
    }
    
  2. Then use it to serialize Entities to JSON

    $this->_getSerializer()->normalize($anEntity, 'json');
    $this->_getSerializer()->normalize($arrayOfEntities, 'json');
    

Done!

But you may need some fine tuning. For example -

Why Response.Redirect causes System.Threading.ThreadAbortException?

What I do is catch this exception, together with another possible exceptions. Hope this help someone.

 catch (ThreadAbortException ex1)
 {
    writeToLog(ex1.Message);
 }
 catch(Exception ex)
 {
     writeToLog(ex.Message);
 }

Java Initialize an int array in a constructor

private int[] data = new int[3];

This already initializes your array elements to 0. You don't need to repeat that again in the constructor.

In your constructor it should be:

data = new int[]{0, 0, 0};

What are these attributes: `aria-labelledby` and `aria-hidden`

Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control

Aria does not change anything visually. (Aria is scared of designers too).

aria-hidden:

aria-hidden attribute is used to hide content for visually impaired users who navigate through application using screen readers (JAWS, NVDA,...).

aria-hidden attribute is used with values true, false.

How To Use:

<i class = "fa fa-books" aria-hidden = "true"></i>

using aria-hidden = "true" on the <i> hides content to screen reader users with no visual change in the application.

aria-label

aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users

How To Use:

<input type = "edit" aria-label = "search" placeholder = "search">

There is no visual change in application. But screen readers can understand the purpose of control

aria-labelledby

Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually

Approach 1:

<span id = "sd"> Search </span>

<input type = "text" aria-labelledby = "sd">

aria-labelledby can also be used to combine two labels for screen reader users

Approach 2:

<span id = "de"> Billing Address </span>

<span id = "sd"> First Name </span>

<input type = "text" aria-labelledby = "de sd">

Unable to get spring boot to automatically create database schema

I ran into a similar problem. I'm using spring boot 2.x and I missed to add Postgres dependency at spring initializer. I added the dependency manually

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>

and here is what I was getting- INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect instead of

**INFO  org.hibernate.dialect.Dialect - HHH000400: Using 
dialect:org.hibernate.dialect.PostgreSQL10Dialect**

This connected me to the DB

It's not so weird because Springboot does version dependency by itself and reduces the development work. On the flip side, if Springboot chooses incorrect dependency, it wastes a lot many hours.

NHibernate.MappingException: No persister for: XYZ

I got this off of here:

In my case the mapping class was not public. In other words, instead of:

public class UserMap : ClassMap<user>  // note the public!

I just had:

class UserMap : ClassMap<user>

Detect application heap size in Android

Debug.getNativeHeapSize() will do the trick, I should think. It's been there since 1.0, though.

The Debug class has lots of great methods for tracking allocations and other performance concerns. Also, if you need to detect a low-memory situation, check out Activity.onLowMemory().

How does OkHttp get Json string?

Below code is for getting data from online server using GET method and okHTTP library for android kotlin...

Log.e("Main",response.body!!.string())

in above line !! is the thing using which you can get the json from response body

val client = OkHttpClient()
            val request: Request = Request.Builder()
                .get()
                .url("http://172.16.10.126:8789/test/path/jsonpage")
                .addHeader("", "")
                .addHeader("", "")
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // Handle this
                    Log.e("Main","Try again latter!!!")
                }

                override fun onResponse(call: Call, response: Response) {
                    // Handle this
                    Log.e("Main",response.body!!.string())
                }
            })

how to specify local modules as npm package dependencies

After struggling much with the npm link command (suggested solution for developing local modules without publishing them to a registry or maintaining a separate copy in the node_modules folder), I built a small npm module to help with this issue.

The fix requires two easy steps.

First:

npm install lib-manager --save-dev

Second, add this to your package.json:

{  
  "name": "yourModuleName",  
  // ...
  "scripts": {
    "postinstall": "./node_modules/.bin/local-link"
  }
}

More details at https://www.npmjs.com/package/lib-manager. Hope it helps someone.

SQL Server Restore Error - Access is Denied

I was having the same problem. It turned out that my SQL Server and SQL Server Agent services logon as were running under the Network Services account which didn't have write access to perform the restore of the back up.

I changed both of these services to logon on as Local System Account and this fixed the problem.

How do I check if a column is empty or null in MySQL?

As defined by the SQL-92 Standard, when comparing two strings of differing widths, the narrower value is right-padded with spaces to make it is same width as the wider value. Therefore, all string values that consist entirely of spaces (including zero spaces) will be deemed to be equal e.g.

'' = ' ' IS TRUE
'' = '  ' IS TRUE
' ' = '  ' IS TRUE
'  ' = '      ' IS TRUE
etc

Therefore, this should work regardless of how many spaces make up the some_col value:

SELECT * 
  FROM T
 WHERE some_col IS NULL 
       OR some_col = ' ';

or more succinctly:

SELECT * 
  FROM T
 WHERE NULLIF(some_col, ' ') IS NULL;

JavaFX and OpenJDK

For me this worked.

$ sudo apt-get install openjfx

Date formatting in WPF datagrid

Very late to the party here but in case anyone else stumbles across this page...

You can do it by setting the AutoGeneratingColumn handler in XAML:

<DataGrid AutoGeneratingColumn="OnAutoGeneratingColumn"  ..etc.. />

And then in code behind do something like this:

private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyType == typeof(System.DateTime))
        (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";
}

datetime.parse and making it work with a specific format

Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:

DateTime dt = DateTime.MinValue;

DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

How can I let a user download multiple files when a button is clicked?

This is the easiest way I have found to download multiple files.

$('body').on('click','.download_btn',function(){
    downloadFiles([
        ['File1.pdf', 'File1-link-here'],
        ['File2.pdf', 'File2-link-here'],
        ['File3.pdf', 'File3-link-here'],
        ['File4.pdf', 'File4-link-here']
    ]);
})
function downloadFiles(files){
    if(files.length == 0){
        return;
    }
    file = files.pop();
    var Link = $('body').append('<a href="'+file[1]+'" download="file[0]"></a>');
    Link[0].click(); 
    Link.remove();
    downloadFiles(files);
}

This should be work for you. Thank You.

How to group by month from Date field using sql

SELECT  to_char(Closing_Date,'MM'), 
        Category,  
        COUNT(Status) TotalCount 
FROM    MyTable
WHERE   Closing_Date >= '2012-02-01' 
AND     Closing_Date <= '2012-12-31'
AND     Defect_Status1 IS NOT NULL
GROUP BY Category;

Fastest way to extract frames using ffmpeg?

Output one image every minute, named img001.jpg, img002.jpg, img003.jpg, etc. The %03d dictates that the ordinal number of each output image will be formatted using 3 digits.

ffmpeg -i myvideo.avi -vf fps=1/60 img%03d.jpg

Change the fps=1/60 to fps=1/30 to capture a image every 30 seconds. Similarly if you want to capture a image every 5 seconds then change fps=1/60 to fps=1/5

SOURCE: https://trac.ffmpeg.org/wiki/Create a thumbnail image every X seconds of the video

How does Trello access the user's clipboard?

I actually built a Chrome extension that does exactly this, and for all web pages. The source code is on GitHub.

I find three bugs with Trello's approach, which I know because I've faced them myself :)

The copy doesn't work in these scenarios:

  1. If you already have Ctrl pressed and then hover a link and hit C, the copy doesn't work.
  2. If your cursor is in some other text field in the page, the copy doesn't work.
  3. If your cursor is in the address bar, the copy doesn't work.

I solved #1 by always having a hidden span, rather than creating one when user hits Ctrl/Cmd.

I solved #2 by temporarily clearing the zero-length selection, saving the caret position, doing the copy and restoring the caret position.

I haven't found a fix for #3 yet :) (For information, check the open issue in my GitHub project).

What does ECU units, CPU core and memory mean when I launch a instance

ECUs (EC2 Computer Units) are a rough measure of processor performance that was introduced by Amazon to let you compare their EC2 instances ("servers").

CPU performance is of course a multi-dimensional measure, so putting a single number on it (like "5 ECU") can only be a rough approximation. If you want to know more exactly how well a processor performs for a task you have in mind, you should choose a benchmark that is similar to your task.

In early 2014, there was a nice benchmarking site comparing cloud hosting offers by tens of different benchmarks, over at CloudHarmony benchmarks. However, this seems gone now (and archive.org can't help as it was a web application). Only an introductory blog post is still available.

Also useful: ec2instances.info, which at least aggregates the ECU information of different EC2 instances for comparison. (Add column "Compute Units (ECU)" to make it work.)

Given a class, see if instance has method (Ruby)

Actually this doesn't work for both Objects and Classes.

This does:

class TestClass
  def methodName
  end
end

So with the given answer, this works:

TestClass.method_defined? :methodName # => TRUE

But this does NOT work:

t = TestClass.new
t.method_defined? : methodName  # => ERROR!

So I use this for both classes and objects:

Classes:

TestClass.methods.include? 'methodName'  # => TRUE

Objects:

t = TestClass.new
t.methods.include? 'methodName'  # => TRUE

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

I resolved this issue by removing android:screenOrientation="portrait" and added below code into my onCreate

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

while my theme properties are

<item name="android:windowIsTranslucent">true</item>
<item name="android:windowDisablePreview">true</item>

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

In my case, my xml had multiple namespaces and attributes. So I used this site to generate the objects - https://xmltocsharp.azurewebsites.net/

And used the below code to deserialize

 XmlDocument doc =  new XmlDocument();
        doc.Load("PathTo.xml");
        User obj;
        using (TextReader textReader = new StringReader(doc.OuterXml))
        {
            using (XmlTextReader reader = new XmlTextReader(textReader))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(User));
                obj = (User)serializer.Deserialize(reader);
            }
        }

How to check if two words are anagrams

let's take a question: Given two strings s and t, write a function to determine if t is an anagram of s.

For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false.

Method 1(Using HashMap ):

public class Method1 {

    public static void main(String[] args) {
        String a = "protijayi";
        String b = "jayiproti";
        System.out.println(isAnagram(a, b ));// output => true

    }

    private static boolean isAnagram(String a, String b) {
        Map<Character ,Integer> map = new HashMap<>();
        for( char c : a.toCharArray()) {
            map.put(c,    map.getOrDefault(c, 0 ) + 1 );
        }
        for(char c : b.toCharArray()) {
            int count = map.getOrDefault(c, 0);
            if(count  == 0 ) {return false ; }
            else {map.put(c, count - 1 ) ; }
        }
        
        return true;
    }

}

Method 2 :

public class Method2 {
public static void main(String[] args) {
    String a = "protijayi";
    String b = "jayiproti";

    
    System.out.println(isAnagram(a, b));// output=> true
}

private static boolean isAnagram(String a, String b) {
   
    
    int[] alphabet = new int[26];
    for(int i = 0 ; i < a.length() ;i++) {
         alphabet[a.charAt(i) - 'a']++ ;
    }
    for (int i = 0; i < b.length(); i++) {
         alphabet[b.charAt(i) - 'a']-- ;
    }
    
    for(  int w :  alphabet ) {
         if(w != 0 ) {return false;}
    }
    return true;
    
}
}

Method 3 :

public class Method3 {
public static void main(String[] args) {
    String a = "protijayi";
    String b = "jayiproti";
    
    
    System.out.println(isAnagram(a, b ));// output => true
}

private static boolean isAnagram(String a, String b) {
    char[] ca = a.toCharArray() ;
    char[] cb = b.toCharArray();
    Arrays.sort(   ca     );
    
    Arrays.sort(   cb        );
    return Arrays.equals(ca , cb );
}
}

Method 4 :

public class AnagramsOrNot {
    public static void main(String[] args) {
        String a = "Protijayi";
        String b = "jayiProti";
        isAnagram(a, b);
    }

    private static void isAnagram(String a, String b) {
        Map<Integer, Integer> map = new LinkedHashMap<>();

        a.codePoints().forEach(code -> map.put(code, map.getOrDefault(code, 0) + 1));
        System.out.println(map);
        b.codePoints().forEach(code -> map.put(code, map.getOrDefault(code, 0) - 1));
        System.out.println(map);
        if (map.values().contains(0)) {
            System.out.println("Anagrams");
        } else {
            System.out.println("Not Anagrams");
        }
    }
}

In Python:

def areAnagram(a, b):
    if len(a) != len(b): return False
    count1 = [0] * 256
    count2 = [0] * 256
    for i in a:count1[ord(i)] += 1
    for i in b:count2[ord(i)] += 1

    for i in range(256):
        if(count1[i] != count2[i]):return False    

    return True


str1 = "Giniiii"
str2 = "Protijayi"
print(areAnagram(str1, str2))

Let's take another famous Interview Question: Group the Anagrams from a given String:

public class GroupAnagrams {
    public static void main(String[] args) {
        String a = "Gini Gina Protijayi iGin aGin jayiProti Soudipta";
        Map<String, List<String>> map = Arrays.stream(a.split(" ")).collect(Collectors.groupingBy(GroupAnagrams::sortedString));
        System.out.println("MAP => " + map);
        map.forEach((k,v) -> System.out.println(k +" and the anagrams are =>" + v ));
        /*
         Look at the Map output:
        MAP => {Giin=[Gini, iGin], Paiijorty=[Protijayi, jayiProti], Sadioptu=[Soudipta], Gain=[Gina, aGin]}
        As we can see, there are multiple Lists. Hence, we have to use a flatMap(List::stream)
        Now, Look at the output:
        Paiijorty and the anagrams are =>[Protijayi, jayiProti]
       
        Now, look at this output:
        Sadioptu and the anagrams are =>[Soudipta]
        List contains only word. No anagrams.
        That means we have to work with map.values(). List contains all the anagrams.
        
                     
        */
        String stringFromMapHavingListofLists = map.values().stream().flatMap(List::stream).collect(Collectors.joining(" "));
        System.out.println(stringFromMapHavingListofLists);
    }

    public static String sortedString(String a) {
        String sortedString = a.chars().sorted()
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();

        return sortedString;

    }
    
    /*
     * The output : Gini iGin Protijayi jayiProti Soudipta Gina aGin
     * All the anagrams are side by side.
     */
}

Now to Group Anagrams in Python is again easy.We have to : Sort the lists. Then, Create a dictionary. Now dictionary will tell us where are those anagrams are( Indices of Dictionary). Then values of the dictionary is the actual indices of the anagrams.

def groupAnagrams(words):
 
    # sort each word in the list
    A = [''.join(sorted(word)) for word in words]
    dict = {}
    for indexofsamewords, names in enumerate(A):
     dict.setdefault(names, []).append(indexofsamewords)
    print(dict)
    #{'AOOPR': [0, 2, 5, 11, 13], 'ABTU': [1, 3, 4], 'Sorry': [6], 'adnopr': [7], 'Sadioptu': [8, 16], ' KPaaehiklry': [9], 'Taeggllnouy': [10], 'Leov': [12], 'Paiijorty': [14, 18], 'Paaaikpr': [15], 'Saaaabhmryz': [17], ' CNaachlortttu': [19], 'Saaaaborvz': [20]}
 
    for index in dict.values():
     print([words[i] for i in index])
 

if __name__ == '__main__':
 
    # list of words
    words = ["ROOPA","TABU","OOPAR","BUTA","BUAT" , "PAROO","Soudipta",
        "Kheyali Park", "Tollygaunge", "AROOP","Love","AOORP", "Protijayi","Paikpara","dipSouta","Shyambazaar",
        "jayiProti", "North Calcutta", "Sovabazaar"]
 
    groupAnagrams(words)
 

The Output :

['ROOPA', 'OOPAR', 'PAROO', 'AROOP', 'AOORP']
['TABU', 'BUTA', 'BUAT']
['Soudipta', 'dipSouta']
['Kheyali Park']
['Tollygaunge']
['Love']
['Protijayi', 'jayiProti']
['Paikpara']
['Shyambazaar']
['North Calcutta']
['Sovabazaar']

Another Important Anagram Question : Find the Anagram occuring Max. number of times. In the Example, ROOPA is the word which has occured maximum number of times. Hence, ['ROOPA' 'OOPAR' 'PAROO' 'AROOP' 'AOORP'] will be the final output.

from sqlite3 import collections
from statistics import mode, mean

import numpy as np


# list of words
words = ["ROOPA","TABU","OOPAR","BUTA","BUAT" , "PAROO","Soudipta",
        "Kheyali Park", "Tollygaunge", "AROOP","Love","AOORP",
         "Protijayi","Paikpara","dipSouta","Shyambazaar",
        "jayiProti", "North Calcutta", "Sovabazaar"]

print(".....Method 1....... ")

sortedwords = [''.join(sorted(word)) for word in words]
print(sortedwords)
print("...........")
LongestAnagram = np.array(words)[np.array(sortedwords) == mode(sortedwords)]
# Longest anagram 
print("Longest anagram by Method 1:")
print(LongestAnagram)

print(".....................................................")  

print(".....Method 2....... ")  

A = [''.join(sorted(word)) for word in words]

dict = {}

for indexofsamewords,samewords in  enumerate(A):
    dict.setdefault(samewords,[]).append(samewords)
#print(dict)  
#{'AOOPR': ['AOOPR', 'AOOPR', 'AOOPR', 'AOOPR', 'AOOPR'], 'ABTU': ['ABTU', 'ABTU', 'ABTU'], 'Sadioptu': ['Sadioptu', 'Sadioptu'], ' KPaaehiklry': [' KPaaehiklry'], 'Taeggllnouy': ['Taeggllnouy'], 'Leov': ['Leov'], 'Paiijorty': ['Paiijorty', 'Paiijorty'], 'Paaaikpr': ['Paaaikpr'], 'Saaaabhmryz': ['Saaaabhmryz'], ' CNaachlortttu': [' CNaachlortttu'], 'Saaaaborvz': ['Saaaaborvz']}
     
aa =  max(dict.items() , key = lambda x : len(x[1]))
print("aa => " , aa)    
word, anagrams = aa 
print("Longest anagram by Method 2:")
print(" ".join(anagrams))    

The Output :

.....Method 1....... 
['AOOPR', 'ABTU', 'AOOPR', 'ABTU', 'ABTU', 'AOOPR', 'Sadioptu', ' KPaaehiklry', 'Taeggllnouy', 'AOOPR', 'Leov', 'AOOPR', 'Paiijorty', 'Paaaikpr', 'Sadioptu', 'Saaaabhmryz', 'Paiijorty', ' CNaachlortttu', 'Saaaaborvz']
...........
Longest anagram by Method 1:
['ROOPA' 'OOPAR' 'PAROO' 'AROOP' 'AOORP']
.....................................................
.....Method 2....... 
aa =>  ('AOOPR', ['AOOPR', 'AOOPR', 'AOOPR', 'AOOPR', 'AOOPR'])
Longest anagram by Method 2:
AOOPR AOOPR AOOPR AOOPR AOOPR






















     

Remove the title bar in Windows Forms

Also add this bit of code to your form to allow it to be draggable still.

Just add it right before the constructor (the method that calls InitializeComponent()


private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;

///
/// Handling the window messages
///
protected override void WndProc(ref Message message)
{
    base.WndProc(ref message);

    if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT)
        message.Result = (IntPtr)HTCAPTION;
}

That code is from: https://jachman.wordpress.com/2006/06/08/enhanced-drag-and-move-winforms-without-having-a-titlebar/

Now to get rid of the title bar but still have a border combine the code from the other response:

this.ControlBox = false;

this.Text = String.Empty;

with this line:

this.FormBorderStyle = FormBorderStyle.FixedSingle;


Put those 3 lines of code into the form's OnLoad event and you should have a nice 'floating' form that is draggable with a thin border (use FormBorderStyle.None if you want no border).

Python:Efficient way to check if dictionary is empty or not

any(d)

This will return true if the dict. d contains at least one truelike key, false otherwise.

Example:

any({0:'test'}) == False

another (more general) way is to check the number of items:

len(d)

Android Horizontal RecyclerView scroll Direction

You can do it with just xml.

the app:reverseLayout="true" do the job!

<android.support.v7.widget.RecyclerView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:divider="@null"
                        android:orientation="horizontal"
                        app:reverseLayout="true"
                        app:layoutManager="android.support.v7.widget.LinearLayoutManager" />

Angular2 module has no exported member

This error can also occur if your interface name is different than the file it is contained in. Read about ES6 modules for details. If the SignInComponent was an interface, as was in my case, then

SignInComponent

should be in a file named SignInComponent.ts.

How do I convert a PDF document to a preview image in PHP?

For those who don't have ImageMagick for whatever reason, GD functions will also work, in conjunction with GhostScript. Run the ghostscript command with exec() to convert a PDF to JPG, and manipulate the resulting file with imagecreatefromjpeg().

Run the ghostscript command:

exec('gs -dSAFER -dBATCH -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r300 -sOutputFile=whatever.jpg input.pdf')

To manipulate, create a new placeholder image, $newimage = imagecreatetruecolor(...), and bring in the current image. $image = imagecreatefromjpeg('whatever.jpg'), and then you can use imagecopyresampled() to change the size, or any number of other built-in, non-imagemagick commands

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Download the following jars and add it to your WEB-INF/lib directory:

Negate if condition in bash script

You can use unequal comparison -ne instead of -eq:

wget -q --tries=10 --timeout=20 --spider http://google.com
if [[ $? -ne 0 ]]; then
    echo "Sorry you are Offline"
    exit 1
fi

Android Google Maps API V2 Zoom to Current Location

private void setUpMapIfNeeded(){
    if (mMap == null){
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();//invoke of map fragment by id from main xml file

     if (mMap != null) {
         mMap.setMyLocationEnabled(true);//Makes the users current location visible by displaying a blue dot.

         LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);//use of location services by firstly defining location manager.
         String provider=lm.getBestProvider(new Criteria(), true);

         if(provider==null){
             onProviderDisabled(provider);
              }
         Location loc=lm.getLastKnownLocation(provider);


         if (loc!=null){
             onLocationChanged(loc);
      }
         }
     }
}

    // Initialize map options. For example:
    // mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

@Override
public void onLocationChanged(Location location) {

   LatLng latlng=new LatLng(location.getLatitude(),location.getLongitude());// This methods gets the users current longitude and latitude.

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));//Moves the camera to users current longitude and latitude
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng,(float) 14.6));//Animates camera and zooms to preferred state on the user's current location.
}

    // TODO Auto-generated method stub

Is it possible to start a shell session in a running container (without ssh)

Here's my solution

In the Dockerfile:

# ...
RUN mkdir -p /opt
ADD initd.sh /opt/
RUN chmod +x /opt/initd.sh
ENTRYPOINT ["/opt/initd.sh"]

In the initd.sh file

#!/bin/bash
...
/etc/init.d/gearman-job-server start
/etc/init.d/supervisor start
#very important!!!
/bin/bash

After image is built you have two options using exec or attach:

  1. Use exec (preferred) and run:

    docker run --name $CONTAINER_NAME -dt $IMAGE_NAME
    

    then

    docker exec -it $CONTAINER_NAME /bin/bash
    

    and use CTRL + D to detach

  2. Use attach and run:

    docker run --name $CONTAINER_NAME -dit $IMAGE_NAME
    

    then

    docker attach $CONTAINER_NAME
    

    and use CTRL + P and CTRL + Q to detach

    Note: The difference between options is in parameter -i

Change image source in code behind - Wpf

The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.

You simply want to pass the actual path to the UriSource:

logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

For those who are still stuck...

Using NetBeans 8.1 and GlassFish 4.1 with CDI, for some reason I had this issue only locally, not on the remote server. What did the trick:

-> using javaee-web-api 7.0 instead of the default pom version provided by NetBeans, which is javaee-web-api 6.0, so:

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
    <type>jar</type>
</dependency>

-> upload this javaee-web-api-7.0.jar as a lib to on the server (lib folder in the domain1 folder) and restart the server.

How do I convert an array object to a string in PowerShell?

$a = 'This', 'Is', 'a', 'cat'

Using double quotes (and optionally use the separator $ofs)

# This Is a cat
"$a"

# This-Is-a-cat
$ofs = '-' # after this all casts work this way until $ofs changes!
"$a"

Using operator join

# This-Is-a-cat
$a -join '-'

# ThisIsacat
-join $a

Using conversion to [string]

# This Is a cat
[string]$a

# This-Is-a-cat
$ofs = '-'
[string]$a

Can an abstract class have a constructor?

Yes, an abstract class can have a constructor. Consider this:

abstract class Product { 
    int multiplyBy;
    public Product( int multiplyBy ) {
        this.multiplyBy = multiplyBy;
    }

    public int mutiply(int val) {
       return multiplyBy * val;
    }
}

class TimesTwo extends Product {
    public TimesTwo() {
        super(2);
    }
}

class TimesWhat extends Product {
    public TimesWhat(int what) {
        super(what);
    }
}

The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.

Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.

NOTE: As there is no default (or no-arg) constructor in the parent abstract class, the constructor used in subclass must explicitly call the parent constructor.

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

I had this issue with an MVC project and here is how I fixed it.

  1. Open BundleConfig.cs
  2. Find :

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

    Change to:

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.bundle.min.js"));
    

This will set the bundle file to load. It is already in the correct order. You just have to make sure that you are rendering this bundle in your view.

Collection that allows only unique items in .NET?

How about just an extension method on HashSet?

public static void AddOrThrow<T>(this HashSet<T> hash, T item)
{
    if (!hash.Add(item))
        throw new ValueExistingException();
}

How to convert a String to Bytearray

The easiest way in 2018 should be TextEncoder but the returned element is not byte array, it is Uint8Array. (And not all browsers support it)

let utf8Encode = new TextEncoder();
utf8Encode.encode("eee")
> Uint8Array [ 101, 101, 101 ]

Sort a Custom Class List<T>

You are correct that your cTag class must implement IComparable<T> interface. Then you can just call Sort() on your list.

To implement IComparable<T> interface, you must implement CompareTo(T other) method. The easiest way to do this is to call CompareTo method of the field you want to compare, which in your case is date.

public class cTag:IComparable<cTag> {
    public int id { get; set; }
    public int regnumber { get; set; }
    public string date { get; set; }
    public int CompareTo(cTag other) {
        return date.CompareTo(other.date);
    }
}

However, this wouldn't sort well, because this would use classic sorting on strings (since you declared date as string). So I think the best think to do would be to redefine the class and to declare date not as string, but as DateTime. The code would stay almost the same:

public class cTag:IComparable<cTag> {
    public int id { get; set; }
    public int regnumber { get; set; }
    public DateTime date { get; set; }
    public int CompareTo(cTag other) {
        return date.CompareTo(other.date);
    }
}

Only thing you'd have to do when creating the instance of the class to convert your string containing the date into DateTime type, but it can be done easily e.g. by DateTime.Parse(String) method.

How to make an element width: 100% minus padding?

box-sizing: border-box is a quick, easy way to fix it:

This will work in all modern browsers, and IE8+.

Here's a demo: http://jsfiddle.net/thirtydot/QkmSk/301/

.content {
    width: 100%;
    box-sizing: border-box;
}

The browser prefixed versions (-webkit-box-sizing, etc.) are not needed in modern browsers.

Get data from JSON file with PHP

Try:
$data = file_get_contents ("file.json");
        $json = json_decode($data, true);
        foreach ($json as $key => $value) {
            if (!is_array($value)) {
                echo $key . '=>' . $value . '<br/>';
            } else {
                foreach ($value as $key => $val) {
                    echo $key . '=>' . $val . '<br/>';
                }
            }
        }

How do I format XML in Notepad++?

For best results, you should use both TextFX XML tidy and XML tools pretty print. Here's how and why:

1.TextFX -> TextFX HTML Tidy -> Tidy: reindent XML

TextFX has the benefit of wrapping long lines, which XML Tools does not do, but it doesn't indent those new lines correctly.

2. XML Tools -> Pretty print (Text indent)

XML Tools complements TextFX by indenting the newly wrapped lines nicely.

Rails 4 LIKE query - ActiveRecord adds quotes

Try

 def self.search(search, page = 1 )
    paginate :per_page => 5, :page => page,
      :conditions => ["name LIKE  ? OR postal_code like ?", "%#{search}%","%#{search}%"],   order => 'name'
  end

See the docs on AREL conditions for more info.

How to set password for Redis?

open redis configuration file

sudo nano /etc/redis/redis.conf 

set passphrase

replace

# requirepass foobared

with

requirepass YOURPASSPHRASE

restart redis

redis-server restart

Python: finding an element in a list

If you just want to find out if an element is contained in the list or not:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> 'example' in li
True
>>> 'damn' in li
False

How to convert an address into a Google Maps Link (NOT MAP)

How about this?

https://maps.google.com/?q=1200 Pennsylvania Ave SE, Washington, District of Columbia, 20003

https://maps.google.com/?q=term

If you have lat-long then use below URL

https://maps.google.com/?ll=latitude,longitude

Example: maps.google.com/?ll=38.882147,-76.99017

UPDATE

As of year 2017, Google now has an official way to create cross-platform Google Maps URLs:

https://developers.google.com/maps/documentation/urls/guide

You can use links like

https://www.google.com/maps/search/?api=1&query=1200%20Pennsylvania%20Ave%20SE%2C%20Washington%2C%20District%20of%20Columbia%2C%2020003 

Passing a varchar full of comma delimited values to a SQL Server IN function

No Table No Function No Loop

Building on the idea of parsing your list into a table our DBA suggested using XML.

Declare @Ids varchar(50)
Set @Ids = ‘1,2,3,5,4,6,7,98,234’

DECLARE @XML XML
SET @XML = CAST('<i>' + REPLACE(@Ids, ',', '</i><i>') + '</i>' AS XML)

SELECT * 
FROM
    SomeTable 
    INNER JOIN @XML.nodes('i') x(i) 
        ON  SomeTable .Id = x.i.value('.', 'VARCHAR(MAX)')

These seems to have the same performance as @KM's answer but, I think, a lot simpler.

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Happened to me when switching flavors.

Now you can also use the google-services.json with different flavors.

See https://stackoverflow.com/a/34364376/570168

How can I use a custom font in Java?

If you include a font file (otf, ttf, etc.) in your package, you can use the font in your application via the method described here:

Oracle Java SE 6: java.awt.Font

There is a tutorial available from Oracle that shows this example:

try {
     GraphicsEnvironment ge = 
         GraphicsEnvironment.getLocalGraphicsEnvironment();
     ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
} catch (IOException|FontFormatException e) {
     //Handle exception
}

I would probably wrap this up in some sort of resource loader though as to not reload the file from the package every time you want to use it.

An answer more closely related to your original question would be to install the font as part of your application's installation process. That process will depend on the installation method you choose. If it's not a desktop app you'll have to look into the links provided.

How to get the version of ionic framework?

That is the version number of the Ionic CLI, which is different from the version number of Ionic's library. Here are a couple easy ways to check the version.

In the browser console, you can run ionic.version and it will print to the console what version it is.

Screenshot of Chrome Dev Tools console

You can also look at the bower.json file in your app, and it will show the version number like you see here. https://github.com/ionic-in-action/chapter5/blob/master/bower.json#L5

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

How to verify Facebook access token?

Just wanted to let you know that up until today I was first obtaining an app access token (via GET request to Facebook), and then using the received token as the app-token-or-admin-token in:

GET graph.facebook.com/debug_token?
    input_token={token-to-inspect}
    &access_token={app-token-or-admin-token}

However, I just realized a better way of doing this (with the added benefit of requiring one less GET request):

GET graph.facebook.com/debug_token?
    input_token={token-to-inspect}
    &access_token={app_id}|{app_secret}

As described in Facebook's documentation for Access Tokens here.

C# equivalent of the IsNull() function in SQL Server

I've been using the following extension method on my DataRow types:

    public static string ColumnIsNull(this System.Data.DataRow row, string colName, string defaultValue = "")
    {
        string val = defaultValue;
        if (row.Table.Columns.Contains(colName))
        {
            if (row[colName] != DBNull.Value)
            {
                val = row[colName]?.ToString();
            }
        }
        return val;
    }

usage:

MyControl.Text = MyDataTable.Rows[0].ColumnIsNull("MyColumn");
MyOtherControl.Text = MyDataTable.Rows[0].ColumnIsNull("AnotherCol", "Doh! I'm null");

I'm checking for the existence of the column first because if none of query results has a non-null value for that column, the DataTable object won't even provide that column.

CSS to select/style first word

What you are looking for is a pseudo-element that doesn't exist. There is :first-letter and :first-line, but no :first-word.

You can of course do this with JavaScript. Here's some code I found that does this: http://www.dynamicsitesolutions.com/javascript/first-word-selector/

How do I check if a string contains another string in Objective-C?

Swift 4 And Above

let str = "Hello iam midhun"

if str.contains("iam") {
  //contains substring
}
else {
  //doesn't contain substring
}

Objective-C

NSString *stringData = @"Hello iam midhun";

if ([stringData containsString:@"iam"]) {
    //contains substring
}
else {
    //doesn't contain substring
}

Swift presentViewController

Swift 3 and Swift 4

let vc = self.storyboard?.instantiateViewController(withIdentifier: "idMyViewControllerName") as! MyViewControllerName
self.present(vc, animated: true, completion: nil)

form with no action and where enter does not reload page

Add an onsubmit handler to the form (either via plain js or jquery $().submit(fn)), and return false unless your specific conditions are met.

Unless you don't want the form to submit, ever - in which case, why not just leave out the 'action' attribute on the form element?

Ansible: Set variable to file content

You can use fetch module to copy files from remote hosts to local, and lookup module to read the content of fetched files.

What is Cache-Control: private?

RFC 2616, section 14.9.1:

Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache...A private (non-shared) cache MAY cache the response.


Browsers could use this information. Of course, the current "user" may mean many things: OS user, a browser user (e.g. Chrome's profiles), etc. It's not specified.

For me, a more concrete example of Cache-Control: private is that proxy servers (which typically have many users) won't cache it. It is meant for the end user, and no one else.


FYI, the RFC makes clear that this does not provide security. It is about showing the correct content, not securing content.

This usage of the word private only controls where the response may be cached, and cannot ensure the privacy of the message content.

Where can I find MySQL logs in phpMyAdmin?

Open your PHPMyAdmin, don't select any database and look for Binary Log tab . You can select different logs from a drop down list and press GO Button to view them.

How to convert a ruby hash object to JSON?

require 'json/ext' # to use the C based extension instead of json/pure

puts {hash: 123}.to_json

How to change resolution (DPI) of an image?

You have to copy the bits over a new image with the target resolution, like this:

    using (Bitmap bitmap = (Bitmap)Image.FromFile("file.jpg"))
    {
        using (Bitmap newBitmap = new Bitmap(bitmap))
        {
            newBitmap.SetResolution(300, 300);
            newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
        }
    }

Get selected option text with JavaScript

Try options

_x000D_
_x000D_
function myNewFunction(sel) {_x000D_
  alert(sel.options[sel.selectedIndex].text);_x000D_
}
_x000D_
<select id="box1" onChange="myNewFunction(this);">_x000D_
  <option value="98">dog</option>_x000D_
  <option value="7122">cat</option>_x000D_
  <option value="142">bird</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Calculate date from week number

I used one of the solutions but it gave me wrong results, simply because it counts Sunday as a first day of the week.

I changed:

var firstDay = new DateTime(DateTime.Now.Year, 1, 1).AddDays((weekNumber - 1) * 7);
var lastDay = firstDay.AddDays(6);

to:

var lastDay = new DateTime(DateTime.Now.Year, 1, 1).AddDays((weekNumber) * 7);
var firstDay = lastDay.AddDays(-6);

and now it is working as a charm.

What is a Data Transfer Object (DTO)?

In general Value Objects should be Immutable. Like Integer or String objects in Java. We can use them for transferring data between software layers. If the software layers or services running in different remote nodes like in a microservices environment or in a legacy Java Enterprise App. We must make almost exact copies of two classes. This is the where we met DTOs.

|-----------|                                                   |--------------|
| SERVICE 1 |--> Credentials DTO >--------> Credentials DTO >-- | AUTH SERVICE |
|-----------|                                                   |--------------|

In legacy Java Enterprise Systems DTOs can have various EJB stuff in it.

I do not know this is a best practice or not but I personally use Value Objects in my Spring MVC/Boot Projects like this:

        |------------|         |------------------|                             |------------|
-> Form |            | -> Form |                  | -> Entity                   |            |
        | Controller |         | Service / Facade |                             | Repository |
<- View |            | <- View |                  | <- Entity / Projection View |            |
        |------------|         |------------------|                             |------------|

Controller layer doesn't know what are the entities are. It communicates with Form and View Value Objects. Form Objects has JSR 303 Validation annotations (for instance @NotNull) and View Value Objects have Jackson Annotations for custom serialization. (for instance @JsonIgnore)

Service layer communicates with repository layer via using Entity Objects. Entity objects have JPA/Hibernate/Spring Data annotations on it. Every layer communicates with only the lower layer. The inter-layer communication is prohibited because of circular/cyclic dependency.

User Service ----> XX CANNOT CALL XX ----> Order Service

Some ORM Frameworks have the ability of projection via using additional interfaces or classes. So repositories can return View objects directly. There for you do not need an additional transformation.

For instance this is our User entity:

@Entity
public final class User {
    private String id;
    private String firstname;
    private String lastname;
    private String phone;
    private String fax;
    private String address;
    // Accessors ...
}

But you should return a Paginated list of users that just include id, firstname, lastname. Then you can create a View Value Object for ORM projection.

public final class UserListItemView {
    private String id;
    private String firstname;
    private String lastname;
    // Accessors ...
}

You can easily get the paginated result from repository layer. Thanks to spring you can also use just interfaces for projections.

List<UserListItemView> find(Pageable pageable);

Don't worry for other conversion operations BeanUtils.copy method works just fine.

Returning null in a method whose signature says return int?

Do you realy want to return null ? Something you can do, is maybe initialise savedkey with 0 value and return 0 as a null value. It can be more simple.

CASE IN statement with multiple values

You can return the same value from several matches:

SELECT
  CASE c.Number
    WHEN '1121231' THEN 1
    WHEN '31242323' THEN 1
    WHEN '234523' THEN 2
    WHEN '2342423' THEN 2
  END AS Test
FROM tblClient c

This will probably result in the same execution plan as Martins suggestion, so it's more a matter of how you want to write it.

npm start error with create-react-app

add environment variables in windows

  1. C:\WINDOWS\System32
  2. C:\Program Files\nodejs
  3. C:\Program Files\nodejs\node_modules\npm\bin
  4. C:\WINDOWS\System32\WindowsPowerShell\v1.0
  5. C:\Users{your system name without curly braces}\AppData\Roaming\npm

these 5 are must in path.

and use the latest version of node.js

Return index of greatest value in an array

Unless I'm mistaken, I'd say it's to write your own function.

function findIndexOfGreatest(array) {
  var greatest;
  var indexOfGreatest;
  for (var i = 0; i < array.length; i++) {
    if (!greatest || array[i] > greatest) {
      greatest = array[i];
      indexOfGreatest = i;
    }
  }
  return indexOfGreatest;
}

Sending cookies with postman

Based @RBT's answer above, I tried Postman native app and want to give a couple of additional details.

In the latest postman desktop app, you can find the cookies option on the extreme right:

enter image description here

You can see the cookies for your localhost (these cookies are linked with the cookies in your chrome browser, although the app is running natively). Also you can set the cookies for a particular domain too.

enter image description here

laravel the requested url was not found on this server

Alternatively you could replace all the contents in your .htaccess file

Options +FollowSymLinks -Indexes
RewriteEngine On
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

See the docs here. https://laravel.com/docs/5.8/installation#web-server-configuration

jquery disable form submit on enter

Complete Solution in JavaScript for all browsers

The code above and most of the solutions are perfect. However, I think the most liked one "short answer" which is incomplete.

So here's the entire answer. in JavaScript with native Support for IE 7 as well.

var form = document.getElementById("testForm");
form.addEventListener("submit",function(e){e.preventDefault(); return false;});

This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.

Parallel foreach with asynchronous lambda

My lightweight implementation of ParallelForEach async.

Features:

  1. Throttling (max degree of parallelism).
  2. Exception handling (aggregation exception will be thrown at completion).
  3. Memory efficient (no need to store the list of tasks).

public static class AsyncEx
{
    public static async Task ParallelForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> asyncAction, int maxDegreeOfParallelism = 10)
    {
        var semaphoreSlim = new SemaphoreSlim(maxDegreeOfParallelism);
        var tcs = new TaskCompletionSource<object>();
        var exceptions = new ConcurrentBag<Exception>();
        bool addingCompleted = false;

        foreach (T item in source)
        {
            await semaphoreSlim.WaitAsync();
            asyncAction(item).ContinueWith(t =>
            {
                semaphoreSlim.Release();

                if (t.Exception != null)
                {
                    exceptions.Add(t.Exception);
                }

                if (Volatile.Read(ref addingCompleted) && semaphoreSlim.CurrentCount == maxDegreeOfParallelism)
                {
                    tcs.TrySetResult(null);
                }
            });
        }

        Volatile.Write(ref addingCompleted, true);
        await tcs.Task;
        if (exceptions.Count > 0)
        {
            throw new AggregateException(exceptions);
        }
    }
}

Usage example:

await Enumerable.Range(1, 10000).ParallelForEachAsync(async (i) =>
{
    var data = await GetData(i);
}, maxDegreeOfParallelism: 100);

React Error: Target Container is not a DOM Element

I figured it out!

After reading this blog post I realized that the placement of this line:

<script src="{% static "build/react.js" %}"></script>

was wrong. That line needs to be the last line in the <body> section, right before the </body> tag. Moving the line down solves the problem.

My explanation for this is that react was looking for the id in between the <head> tags, instead of in the <body> tags. Because of this it couldn't find the content id, and thus it wasn't a real DOM element.

escaping question mark in regex javascript

You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:

var gent = /I like your Apartment. Could we schedule a viewing\?/g;

How to get the path of src/test/resources directory in JUnit?

There are differences and constraints in options offered by @Steve C and @ashosborne1. They must be specified, I believe.

When can we can use: File resourcesDirectory = new File("src/test/resources");?

  • 1 When tests are going to be run via maven only but not via IDE.
  • 2.1 When tests are going to be run via maven or
  • 2.2 via IDE and only one project is imported into IDE. (I use “imported” term, cause it is used in IntelliJ IDEA. I think users of eclipse also import their maven project). This will work, cause working directory when you run tests via IDE is the same as your project.
  • 3.1 When tests are going to be run via maven or
  • 3.2 via IDE, and more than one projects are imported into IDE (when you are not a student, you usually import several projects), AND before you run tests via IDE, you manually configure working directory for your tests. That working directory should refer to your imported project that contains the tests. By default, working directory of all projects imported into IDE is only one. Probably it is a restriction of IntelliJ IDEA only, but I think all IDEs work like this. And this configuration that must be done manually, is not good at all. Working with several tests existing in different maven projects, but imported into one big “IDE” project, force us to remember this and don’t allow to relax and get pleasure from your work.

Solution offered by @ashosborne1 (personally I prefer this one) requires 2 additional requirements that must be done before you run tests. Here is a list of steps to use this solution:

  • Create a test folder (“teva”) and file (“readme”) inside of “src/test/resources/”:

    src/test/resources/teva/readme

    File must be created in the test folder, otherwise, it will not work. Maven ignores empty folders.

  • At least once build project via mvn clean install. It will run tests also. It may be enough to run only your test class/method via maven without building a whole project. As a result your test resources will be copied into test-classes, here is a path: target/test-classes/teva/readme

  • After that, you can access the folder using code, already offered by @ashosborne1 (I'm sorry, that I could not edit this code inside of this list of items correctly):

public static final String TEVA_FOLDER = "teva"; ... 
URL tevaUrl = YourTest.class.getClassLoader().getResource(TEVA_FOLDER); 
String tevaTestFolder = new File(tevaUrl.toURI()).getAbsolutePath();

Now you can run your test via IDE as many times as you want. Until you run mvn clean. It will drop the target folder.

Creating file inside a test folder and running maven first time, before you run tests via IDE are needed steps. Without these steps, if you just in your IDE create test resources, then write test and run it via IDE only, you'll get an error. Running tests via mvn copies test resources into target/test-classes/teva/readme and they become accessible for a classloader.

You may ask, why do I need import more than one maven project in IDE and why so many complicated things? For me, one of the main motivation: keeping IDA-related files far from code. I first create a new project in my IDE. It is a fake project, that is just a holder of IDE-related files. Then, I import already existing maven projects. I force these imported projects to keep IDEA files in my original fake project only. As a result I don't see IDE-related files among the code. SVN should not see them (don't offer to configure svn/git to ignore such files, please). Also it is just very convenient.

Android Respond To URL in Intent

I did it! Using <intent-filter>. Put the following into your manifest file:

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>

This works perfectly!

Ways to eliminate switch in code

Function pointers are one way to replace a huge chunky switch statement, they are especially good in languages where you can capture functions by their names and make stuff with them.

Of course, you ought not force switch statements out of your code, and there always is a chance you are doing it all wrong, which results with stupid redundant pieces of code. (This is unavoidable sometimes, but a good language should allow you to remove redundancy while staying clean.)

This is a great divide&conquer example:

Say you have an interpreter of some sort.

switch(*IP) {
    case OPCODE_ADD:
        ...
        break;
    case OPCODE_NOT_ZERO:
        ...
        break;
    case OPCODE_JUMP:
        ...
        break;
    default:
        fixme(*IP);
}

Instead, you can use this:

opcode_table[*IP](*IP, vm);

... // in somewhere else:
void opcode_add(byte_opcode op, Vm* vm) { ... };
void opcode_not_zero(byte_opcode op, Vm* vm) { ... };
void opcode_jump(byte_opcode op, Vm* vm) { ... };
void opcode_default(byte_opcode op, Vm* vm) { /* fixme */ };

OpcodeFuncPtr opcode_table[256] = {
    ...
    opcode_add,
    opcode_not_zero,
    opcode_jump,
    opcode_default,
    opcode_default,
    ... // etc.
};

Note that I don't know how to remove the redundancy of the opcode_table in C. Perhaps I should make a question about it. :)

How to find char in string and get all the indexes?

As the rule of thumb, NumPy arrays often outperform other solutions while working with POD, Plain Old Data. A string is an example of POD and a character too. To find all the indices of only one char in a string, NumPy ndarrays may be the fastest way:

def find1(str, ch):
  # 0.100 seconds for 1MB str 
  npbuf = np.frombuffer(str, dtype=np.uint8) # Reinterpret str as a char buffer
  return np.where(npbuf == ord(ch))          # Find indices with numpy

def find2(str, ch):
  # 0.920 seconds for 1MB str 
  return [i for i, c in enumerate(str) if c == ch] # Find indices with python

Chrome Dev Tools - Modify javascript and reload

This is a bit of a work around, but one way you can achieve this is by adding a breakpoint at the start of the javascript file or block you want to manipulate.

Then when you reload, the debugger will pause on that breakpoint, and you can make any changes you want to the source, save the file and then run the debugger through the modified code.

But as everyone has said, next reload the changes will be gone - at least it let's you run some slightly modified JS client side.

how much memory can be accessed by a 32 bit machine?

Yes, a 32-bit architecture is limited to addressing a maximum of 4 gigabytes of memory. Depending on the operating system, this number can be cut down even further due to reserved address space.

This limitation can be removed on certain 32-bit architectures via the use of PAE (Physical Address Extension), but it must be supported by the processor. PAE eanbles the processor to access more than 4 GB of memory, but it does not change the amount of virtual address space available to a single process—each process would still be limited to a maximum of 4 GB of address space.

And yes, theoretically a 64-bit architecture can address 16.8 million terabytes of memory, or 2^64 bytes. But I don't believe the current popular implementations fully support this; for example, the AMD64 architecture can only address up to 1 terabyte of memory. Additionally, your operating system will also place limitations on the amount of supported, addressable memory. Many versions of Windows (particularly versions designed for home or other non-server use) are arbitrarily limited.

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

SQL Server query to find all current database names

Another to add to the mix:

EXEC sp_databases

Opening port 80 EC2 Amazon web services

This is actually really easy:

  • Go to the "Network & Security" -> Security Group settings in the left hand navigation
  • Find the Security Group that your instance is apart of
  • Click on Inbound Rules
  • Use the drop down and add HTTP (port 80)
  • Click Apply and enjoy

Bootstrap 3: pull-right for col-lg only

Works fine too:

/* small screen portrait */

@media (max-width: 321px) {

  .pull-right { 
    float: none!important; 
  }

}


/* small screen lanscape */

@media (max-width: 480px) {

  .pull-right {
    float: none!important; 
  }

}

How to remove decimal values from a value of type 'double' in Java

I would try this:

String numWihoutDecimal = String.valueOf(percentageValue).split("\\.")[0];

I've tested this and it works so then it's just convert from this string to whatever type of number or whatever variable you want. You could do something like this.

int num = Integer.parseInt(String.valueOf(percentageValue).split("\\.")[0]);

Select and display only duplicate records in MySQL

Try this query:

SELECT id, COUNT( payer_email ) `tot`
FROM paypal_ipn_orders
GROUP BY id
HAVING `tot` >1

Does it help?

Using Cookie in Asp.Net Mvc 4

userCookie.Expires.AddDays(365); 

This line of code doesn't do anything. It is the equivalent of:

DateTime temp = userCookie.Expires.AddDays(365); 
//do nothing with temp

You probably want

userCookie.Expires = DateTime.Now.AddDays(365); 

DataTable: How to get item value with row name and column name? (VB)

'Create a class to hold the pair...

        Public Class ColumnValue
            Public ColumnName As String
            Public ColumnValue As New Object
        End Class

    'Build the pair...

        For Each row In [YourDataTable].Rows

              For Each item As DataColumn In row.Table.Columns
                Dim rowValue As New ColumnValue
                rowValue.ColumnName = item.Caption
                rowValue.ColumnValue = row.item(item.Ordinal)
                RowValues.Add(rowValue)
                rowValue = Nothing
              Next

        ' Now you can grab the value by the column name...

        Dim results = (From p In RowValues Where p.ColumnName = "MyColumn" Select  p.ColumnValue).FirstOrDefault    

        Next

col align right

Use float-right for block elements, or text-right for inline elements:

<div class="row">
     <div class="col">left</div>
     <div class="col text-right">inline content needs to be right aligned</div>
</div>
<div class="row">
      <div class="col">left</div>
      <div class="col">
          <div class="float-right">element needs to be right aligned</div>
      </div>
</div>

http://www.codeply.com/go/oPTBdCw1JV

If float-right is not working, remember that Bootstrap 4 is now flexbox, and many elements are display:flex which can prevent float-right from working.

In some cases, the utility classes like align-self-end or ml-auto work to right align elements that are inside a flexbox container like the Bootstrap 4 .row, Card or Nav. The ml-auto (margin-left:auto) is used in a flexbox element to push elements to the right.

Bootstrap 4 align right examples

If Radio Button is selected, perform validation on Checkboxes

function validateDays() {
    if (document.getElementById("option1").checked == true) {
        alert("You have selected Option 1");
    }
    else if (document.getElementById("option2").checked == true) {
        alert("You have selected Option 2");
    }
    else if (document.getElementById("option3").checked == true) {
        alert("You have selected Option 3");
    }
    else {
        // DO NOTHING
        }
    }

Javascript event handler with parameters

I don't understand exactly what your code is trying to do, but you can make variables available in any event handler using the advantages of function closures:

function addClickHandler(elem, arg1, arg2) {
    elem.addEventListener('click', function(e) {
        // in the event handler function here, you can directly refer
        // to arg1 and arg2 from the parent function arguments
    }, false);
}

Depending upon your exact coding situation, you can pretty much always make some sort of closure preserve access to the variables for you.

From your comments, if what you're trying to accomplish is this:

element.addEventListener('click', func(event, this.elements[i]))

Then, you could do this with a self executing function (IIFE) that captures the arguments you want in a closure as it executes and returns the actual event handler function:

element.addEventListener('click', (function(passedInElement) {
    return function(e) {func(e, passedInElement); };
}) (this.elements[i]), false);

For more info on how an IIFE works, see these other references:

Javascript wrapping code inside anonymous function

Immediately-Invoked Function Expression (IIFE) In JavaScript - Passing jQuery

What are good use cases for JavaScript self executing anonymous functions?

This last version is perhaps easier to see what it's doing like this:

// return our event handler while capturing an argument in the closure
function handleEvent(passedInElement) {
    return function(e) {
        func(e, passedInElement); 
    };
}

element.addEventListener('click', handleEvent(this.elements[i]));

It is also possible to use .bind() to add arguments to a callback. Any arguments you pass to .bind() will be prepended to the arguments that the callback itself will have. So, you could do this:

elem.addEventListener('click', function(a1, a2, e) {
    // inside the event handler, you have access to both your arguments
    // and the event object that the event handler passes
}.bind(elem, arg1, arg2));

How do I bind the enter key to a function in tkinter?

Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")
root.bind('<Return>', func)

def onclick():
    print("You clicked the button")

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Then you just have tweak things a little when making both the button click and hitting Return call the same function--because the command function needs to be a function that takes no arguments, whereas the bind function needs to be a function that takes one argument(the event object):

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event=None):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Or, you can just forgo using the button's command argument and instead use bind() to attach the onclick function to the button, which means the function needs to take one argument--just like with Return:

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me")
button.bind('<Button-1>', onclick)
button.pack()

root.mainloop()

Here it is in a class setting:

import tkinter as tk

class Application(tk.Frame):
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("300x200")

        tk.Frame.__init__(self, self.root)
        self.create_widgets()

    def create_widgets(self):
        self.root.bind('<Return>', self.parse)
        self.grid()

        self.submit = tk.Button(self, text="Submit")
        self.submit.bind('<Button-1>', self.parse)
        self.submit.grid()

    def parse(self, event):
        print("You clicked?")

    def start(self):
        self.root.mainloop()


Application().start()

python: how to check if a line is an empty line

If you want to ignore lines with only whitespace:

if not line.strip():
    ... do something

The empty string is a False value.

Or if you really want only empty lines:

if line in ['\n', '\r\n']:
    ... do  something

Process list on Linux via Python

You can use a third party library, such as PSI:

PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.

How to include a Font Awesome icon in React's render()

Alexander's answer from above really helped me out!

I was trying to get social accounts icons in the footer of my app I created with ReactJS so that I could easily add a hover state to them while also having them link my social accounts. This is what I ended up having to do:

$ npm i --save @fortawesome/fontawesome-free-brands

Then at the top of my footer component I included this:

import React from 'react';
import './styles/Footer.css';
import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import {faTwitter, faLinkedin, faGithub} from '@fortawesome/fontawesome-free-brands';

My component then looked like this:

<a href='https://github.com/yourusernamehere'>
  <FontAwesomeIcon className ='font-awesome' icon={faGithub} />
</a>

Worked like a charm.

Add column in dataframe from list

A solution improving on the great one from @sparrow.

Let df, be your dataset, and mylist the list with the values you want to add to the dataframe.

Let's suppose you want to call your new column simply, new_column

First make the list into a Series:

column_values = pd.Series(mylist)

Then use the insert function to add the column. This function has the advantage to let you choose in which position you want to place the column. In the following example we will position the new column in the first position from left (by setting loc=0)

df.insert(loc=0, column='new_column', value=column_values)

Cannot read property 'map' of undefined

I think you forgot to change

data={this.props.data}

to

data={this.state.data}

in the render function of CommentBox. I did the same mistake when I was following the tutorial. Thus the whole render function should look like

render: function() {
  return (
    <div className="commentBox">
      <h1>Comments</h1>
      <CommentList data={this.state.data} />
      <CommentForm />
    </div>
  );
}

instead of

render: function() {
  return (
    <div className="commentBox">
      <h1>Comments</h1>
      <CommentList data={this.props.data} />
      <CommentForm />
    </div>
  );

Java simple code: java.net.SocketException: Unexpected end of file from server

I would suggest using wire shark to trace packets. If you are using Ubuntu, sudo-apt get wireshark. Like Joni stated the only way to figure out whats going wrong is to follow the GET requests and their associated responses.

http://www.wireshark.org/download.html

Split string on whitespace in Python

Using split() will be the most Pythonic way of splitting on a string.

It's also useful to remember that if you use split() on a string that does not have a whitespace then that string will be returned to you in a list.

Example:

>>> "ark".split()
['ark']

Tomcat Server Error - Port 8080 already in use

The Way I solved this problem is , Install TCPview go to TCP view and check what ports is Tomcat utilizing there will be few other ports other than 8005,8009,8080 now go to Servers tab in eclipse double click on Tomcatv9.0 server and change port numbers there. This will solve the problem.

How to verify if $_GET exists?

You can use the array_key_exists() built-in function:

if (array_key_exists('id', $_GET)) {
    echo $_GET['id'];
}

or the isset() built-in function:

if (isset($_GET['id'])) {
    echo $_GET['id'];
}

How to put Google Maps V2 on a Fragment using ViewPager

Dynamically adding map fragment to view Pager:

If you are targeting an application earlier than API level 12 make an instance of SupportedMapFragment and add it to your view page adapter.

SupportMapFragment supportMapFragment=SupportMapFragment.newInstance();
        supportMapFragment.getMapAsync(this);

API level 12 or higher support MapFragment objects

MapFragment mMapFragment=MapFragment.newInstance();
            mMapFragment.getMapAsync(this);

Selecting specific rows and columns from NumPy array

As Toan suggests, a simple hack would be to just select the rows first, and then select the columns over that.

>>> a[[0,1,3], :]            # Returns the rows you want
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [12, 13, 14, 15]])
>>> a[[0,1,3], :][:, [0,2]]  # Selects the columns you want as well
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

[Edit] The built-in method: np.ix_

I recently discovered that numpy gives you an in-built one-liner to doing exactly what @Jaime suggested, but without having to use broadcasting syntax (which suffers from lack of readability). From the docs:

Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].

So you use it like this:

>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

And the way it works is that it takes care of aligning arrays the way Jaime suggested, so that broadcasting happens properly:

>>> np.ix_([0,1,3], [0,2])
(array([[0],
        [1],
        [3]]), array([[0, 2]]))

Also, as MikeC says in a comment, np.ix_ has the advantage of returning a view, which my first (pre-edit) answer did not. This means you can now assign to the indexed array:

>>> a[np.ix_([0,1,3], [0,2])] = -1
>>> a    
array([[-1,  1, -1,  3],
       [-1,  5, -1,  7],
       [ 8,  9, 10, 11],
       [-1, 13, -1, 15],
       [16, 17, 18, 19]])

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

if your application accepts errors raise from Oracle, then you can use it. we have an application, each time when an error happens, we call raise_application_error, the application will popup a red box to show the error message we provide through this method.

When using dotnet code, I just use "raise", dotnet exception mechanisim will automatically capture the error passed by Oracle ODP and shown inside my catch exception code.

How to redirect and append both stdout and stderr to a file with Bash?

There are two ways to do this, depending on your Bash version.

The classic and portable (Bash pre-4) way is:

cmd >> outfile 2>&1

A nonportable way, starting with Bash 4 is

cmd &>> outfile

(analog to &> outfile)

For good coding style, you should

  • decide if portability is a concern (then use classic way)
  • decide if portability even to Bash pre-4 is a concern (then use classic way)
  • no matter which syntax you use, not change it within the same script (confusion!)

If your script already starts with #!/bin/sh (no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.

Also remember that Bash 4 &>> is just shorter syntax — it does not introduce any new functionality or anything like that.

The syntax is (beside other redirection syntax) described here: http://bash-hackers.org/wiki/doku.php/syntax/redirection#appending_redirected_output_and_error_output

Restricting JTextField input to Integers

You can also use JFormattedTextField, which is much simpler to use. Example:

public static void main(String[] args) {
    NumberFormat format = NumberFormat.getInstance();
    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setValueClass(Integer.class);
    formatter.setMinimum(0);
    formatter.setMaximum(Integer.MAX_VALUE);
    formatter.setAllowsInvalid(false);
    // If you want the value to be committed on each keystroke instead of focus lost
    formatter.setCommitsOnValidEdit(true);
    JFormattedTextField field = new JFormattedTextField(formatter);

    JOptionPane.showMessageDialog(null, field);

    // getValue() always returns something valid
    System.out.println(field.getValue());
}

Fit Image in ImageButton in Android

I'm using android:scaleType="fitCenter" with satisfaction.

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

How to set Grid row and column positions programmatically

Here is an example which might help someone:

Grid test = new Grid();
test.ColumnDefinitions.Add(new ColumnDefinition());
test.ColumnDefinitions.Add(new ColumnDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());

Label t1 = new Label();
t1.Content = "Test1";
Label t2 = new Label();
t2.Content = "Test2";
Label t3 = new Label();
t3.Content = "Test3";
Label t4 = new Label();
t4.Content = "Test4";
Label t5 = new Label();
t5.Content = "Test5";
Label t6 = new Label();
t6.Content = "Test6";

Grid.SetColumn(t1, 0);
Grid.SetRow(t1, 0);
test.Children.Add(t1);

Grid.SetColumn(t2, 1);
Grid.SetRow(t2, 0);
test.Children.Add(t2);

Grid.SetColumn(t3, 0);
Grid.SetRow(t3, 1);
test.Children.Add(t3);

Grid.SetColumn(t4, 1);
Grid.SetRow(t4, 1);
test.Children.Add(t4);

Grid.SetColumn(t5, 0);
Grid.SetRow(t5, 2);
test.Children.Add(t5);

Grid.SetColumn(t6, 1);
Grid.SetRow(t6, 2);
test.Children.Add(t6);

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

You may use hot-node to prevent your server from crashing/ run-time-errors. Hot-node automatically restarts the nodejs application for you whenever there is a change in the node program[source] / process[running node program].

Install hot-node using npm using the global option:

npm install -g hotnode

Ubuntu, how do you remove all Python 3 but not 2

EDIT: As pointed out in recent comments, this solution may BREAK your system.

You most likely don't want to remove python3.

Please refer to the other answers for possible solutions.

Outdated answer (not recommended)

sudo apt-get remove 'python3.*'

How do you get the length of a string?

same way you do it in javascript:

"something".length