Programs & Examples On #Hoptoad

Find current directory and file's directory

pathlib module, introduced in Python 3.4 (PEP 428 — The pathlib module — object-oriented filesystem paths), makes path-related experience much much better.

$ pwd
/home/skovorodkin/stack
$ tree
.
+-- scripts
    +-- 1.py
    +-- 2.py

In order to get current working directory use Path.cwd():

from pathlib import Path

print(Path.cwd())  # /home/skovorodkin/stack

To get an absolute path to your script file, use Path.resolve() method:

print(Path(__file__).resolve())  # /home/skovorodkin/stack/scripts/1.py

And to get path of a directory where your script is located, access .parent (it is recommended to call .resolve() before .parent):

print(Path(__file__).resolve().parent)  # /home/skovorodkin/stack/scripts

Remember that __file__ is not reliable in some situations: How do I get the path of the current executed file in Python?.


Please note, that Path.cwd(), Path.resolve() and other Path methods return path objects (PosixPath in my case), not strings. In Python 3.4 and 3.5 that caused some pain, because open built-in function could only work with string or bytes objects, and did not support Path objects, so you had to convert Path objects to strings or use Path.open() method, but the latter option required you to change old code:

$ cat scripts/2.py
from pathlib import Path

p = Path(__file__).resolve()

with p.open() as f: pass
with open(str(p)) as f: pass
with open(p) as f: pass

print('OK')

$ python3.5 scripts/2.py
Traceback (most recent call last):
  File "scripts/2.py", line 11, in <module>
    with open(p) as f:
TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py')

As you can see open(p) does not work with Python 3.5.

PEP 519 — Adding a file system path protocol, implemented in Python 3.6, adds support of PathLike objects to open function, so now you can pass Path objects to open function directly:

$ python3.6 scripts/2.py
OK

Java character array initializer

You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?

When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
}

It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.

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

At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.

String ini = "Hi there";

for (int count = 0; count < ini.length(); count++) {
   System.out.println(ini.charAt(count));
}

Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string

String ini = "Hi there"; // stored in String constant pool

is stored differently in memory than

String ini = new String("Hi there"); // stored in heap memory and String constant pool

, which is stored differently than

char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string

.

Getting CheckBoxList Item values

to get the items checked you can use CheckedItems or GetItemsChecked. I tried below code in .NET 4.5

Iterate through the CheckedItems collection. This will give you the item number in the list of checked items, not the overall list. So if the first item in the list is not checked and the second item is checked, the code below will display text like Checked Item 1 = MyListItem2.

//Determine if there are any items checked. 
if(chBoxListTables.CheckedItems.Count != 0)  
{
    //looped through all checked items and show results.
    string s = "";
    for (int x = 0; x < chBoxListTables.CheckedItems.Count; x++)
    {
        s = s + (x + 1).ToString() + " = " + chBoxListTables.CheckedItems[x].ToString()+ ", ";
    }
    MessageBox.Show(s);//show result
}

-OR-

Step through the Items collection and call the GetItemChecked method for each item. This will give you the item number in the overall list, so if the first item in the list is not checked and the second item is checked, it will display something like Item 2 = MyListItem2.

int i;  
string s;   
s = "Checked items:\n" ;  
for (i = 0; i < checkedListBox1.Items.Count; i++)  
{  
   if (checkedListBox1.GetItemChecked(i))  
   {  
      s = s + "Item " + (i+1).ToString() + " = " + checkedListBox1.Items[i].ToString() + "\n";  
   }  
}  
MessageBox.Show (s);

Hope this helps...

How to change an Android app's name?

It depends what you want to do. I personally wanted to rename my project so it didn't say MainActivity at the top of the app and underneath the icon on my phone menu.

To do this I went into the Android Manifest.xml file and edited

<activity
        android:name=".MainActitivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

And edited the android:name=".Mynewname" and then edited the string title_activity_main in the strings.xml file to match the name.

Hope that helps!

What is the path for the startup folder in windows 2008 server

You can easily reach them by using the Run window and entering:

shell:startup

and

shell:common startup

Source.

How to change Android usb connect mode to charge only?

In your phone go to Settings->Connect to PC.

There you will see the option Default Connection Type. Select it and set it to your preference.

Passing parameter to controller action from a Html.ActionLink

You are using incorrect overload. You should use this overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
) 

And the correct code would be

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

Note that extra parameter at the end. For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.

How to call VS Code Editor from terminal / command line

VS Code is a must have code editor for 2018

For Windows 10 users a lot is possible, the same way the Mac OS users type code . .

Look for you VS Code \bin folder path e.g C:\Program Files\Microsoft VS Code\bin . The bin folder includes a file called code.cmd

Follow the steps below and be proud of the OS you use.

  1. Search for "Advanced System Setting" from Start.

  2. Click on Environment Variables

  3. On System Variables choose "path" from Variable tab and click on Edit.

  4. Click on New on the right side of the popup window.

  5. Copy your path from the Explorer's breadcrumb path and paste it into the new opened path in step 4, example:- C:\Program Files\Microsoft VS Code\bin

  6. Click Ok on all the open windows to confirm changes and restart your cmd

  7. Go to your cmd and navigate to you working directory on server and type code .

C:>cd wamp64\www\react-app> code . to open with VS Code on Windows.

Visual Studio Code also includes a command prompt (terminal) window and you can open one or more of them with
Ctrl + ` on your keyboard.

Hope this helps some one like it did to many of us.

onchange equivalent in angular2

You can use:

<input (input)="saverange()>

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

I found a solution to my problem (thanks to the help of ImportanceOfBeingErnest).

All I had to do was to install tkinter through the Linux bash terminal using the following command:

sudo apt-get install python3-tk

instead of installing it with pip or directly in the virtual environment in Pycharm.

Placing a textview on top of imageview in android

Try this:

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rel_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
    android:id="@+id/ImageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src=//source of image />

<TextView
    android:id="@+id/ImageViewText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@id/ImageView"
    android:layout_alignTop="@id/ImageView"
    android:layout_alignRight="@id/ImageView"
    android:layout_alignBottom="@id/ImageView"
    android:text=//u r text here
    android:gravity="center"
    />

Hope this could help you.

Preferred Java way to ping an HTTP URL for availability

Consider using the Restlet framework, which has great semantics for this sort of thing. It's powerful and flexible.

The code could be as simple as:

Client client = new Client(Protocol.HTTP);
Response response = client.get(url);
if (response.getStatus().isError()) {
    // uh oh!
}

'No JUnit tests found' in Eclipse

It looks like you're missing the runner definition on your test class, that could be the cause:

import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class BallTest {
...
}

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

To add a bit to accepted answer ...

If you get an UnfinishedStubbingException, be sure to set the method to be stubbed after the when closure, which is different than when you write Mockito.when

Mockito.doNothing().when(mock).method()    //method is declared after 'when' closes

Mockito.when(mock.method()).thenReturn(something)   //method is declared inside 'when'

Find a value in DataTable

this question asked in 2009 but i want to share my codes:

    Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable

    Dim x As Integer
    Dim y As Integer

    Dim bln As Boolean

    Dim dttable2 As New DataTable
    For x = 0 To dttable.Columns.Count - 1
        dttable2.Columns.Add(dttable.Columns(x).ColumnName)
    Next

    For x = 0 To dttable.Rows.Count - 1
        For y = 0 To searchcolumns.Length - 1
            If String.IsNullOrEmpty(searchcolumns(y)) = False Then
                If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
                    bln = True
                Else
                    bln = False
                    Exit For
                End If
            End If
        Next
        If bln = True Then
            dttable2.Rows.Add(dttable.Rows(x).ItemArray)
        End If
    Next

    Return dttable2


End Function

How to add not null constraint to existing column in MySQL

Just use an ALTER TABLE... MODIFY... query and add NOT NULL into your existing column definition. For example:

ALTER TABLE Person MODIFY P_Id INT(11) NOT NULL;

A word of caution: you need to specify the full column definition again when using a MODIFY query. If your column has, for example, a DEFAULT value, or a column comment, you need to specify it in the MODIFY statement along with the data type and the NOT NULL, or it will be lost. The safest practice to guard against such mishaps is to copy the column definition from the output of a SHOW CREATE TABLE YourTable query, modify it to include the NOT NULL constraint, and paste it into your ALTER TABLE... MODIFY... query.

Finding elements not in a list

list1 = [1,2,3,4]; list2 = [0,3,3,6]

print set(list2) - set(list1)

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

How to provide shadow to Button

Android now provides ExtendedFloatingActionButton which does the same thing for you.

Install Node.js on Ubuntu

npm is automatically installed with Node.js in the latest version of Node.js. What do you see when you type node --version and npm --version in the terminal?

You can upgrade npm using npm itself as well:

[sudo] npm install -g npm

Should we pass a shared_ptr by reference or by value?

There was a recent blog post: https://medium.com/@vgasparyan1995/pass-by-value-vs-pass-by-reference-to-const-c-f8944171e3ce

So the answer to this is: Do (almost) never pass by const shared_ptr<T>&.
Simply pass the underlying class instead.

Basically the only reasonable parameters types are:

  • shared_ptr<T> - Modify and take ownership
  • shared_ptr<const T> - Don't modify, take ownership
  • T& - Modify, no ownership
  • const T& - Don't modify, no ownership
  • T - Don't modify, no ownership, Cheap to copy

As @accel pointed out in https://stackoverflow.com/a/26197326/1930508 the advice from Herb Sutter is:

Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership

But in how many cases are you not sure? So this is a rare situation

Authentication failed to bitbucket

I was trying the git push --all bitbucket call and it was throwing back the "fatal: Authentication failed for 'https://..." response. The solution that worked for me was to change the command to:

git push --all https://{username}@{url}

On Windows, this popped up a dialog that allowed me to enter my password and the push worked.

How to set an environment variable from a Gradle build?

This looks like an old thread but there is one more variant of how we can set an environment variable in the Gradle task.

task runSomeRandomTask(type: NpmTask, dependsOn: [npmInstall]) {
    environment = [ 'NODE_ENV': 'development', BASE_URL: '3000' ]
    args = ['run']
}

The above Gradle task integrates the Gradle and npm tasks.

This way we can pass multiple environment variables. Hope this helps to broaden the understanding which the answers above have already provided. Cheers!!

jQuery: How to get the event object in an event handler function without passing it as an argument?

If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:

Markup:

  <a href="#" id="link1" >click</a>

Javascript:

  $(document).ready(function(){
      $("#link1").click(clickWithEvent);  //Bind the click event to the link
  });
  function clickWithEvent(evt){
     myFunc('p1', 'p2', 'p3');
     function myFunc(p1,p2,p3){  //Defined as local function, but has access to evt
        alert(evt.type);        
     }
  }

Since the event ob

SQL Server: converting UniqueIdentifier to string in a case statement

Instead of Str(RequestID), try convert(varchar(38), RequestID)

Two divs side by side - Fluid display

You can also use the Grid View its also Responsive its something like this:

#wrapper {
   width: auto;
    height: auto;
    box-sizing: border-box;
    display: grid;
    grid-auto-flow: row;
    grid-template-columns: repeat(6, 1fr);
}

#left{
    text-align: left;
    grid-column: 1/4;
}

#right {
    text-align: right;
    grid-column: 4/6;
}

and the HTML should look like this :

<div id="wrapper">
<div id="left" > ...some awesome stuff </div>
<div id="right" > ...some awesome stuff </div>
</div>

here is a link for more information:

https://www.w3schools.com/css/css_rwd_grid.asp

im quite new but i thougt i could share my little experience

How to add a new row to datagridview programmatically

An example of copy row from dataGridView and added a new row in The same dataGridView:

DataTable Dt = new DataTable();
Dt.Columns.Add("Column1");
Dt.Columns.Add("Column2");

DataRow dr = Dt.NewRow();
DataGridViewRow dgvR = (DataGridViewRow)dataGridView1.CurrentRow;
dr[0] = dgvR.Cells[0].Value; 
dr[1] = dgvR.Cells[1].Value;              

Dt.Rows.Add(dR);
dataGridView1.DataSource = Dt;

Is there a Visual Basic 6 decompiler?

In my own experience where I needed to try and find out what some old VB6 programs were doing, I turned to Process Explorer (Sysinternals). I did the following:

  1. Run Process Explorer
  2. Run VB6 .exe
  3. Locate exe in Process Explorer
  4. Right click on process
  5. Check the "Strings" tab

This didn't show the actual functions, but it listed their names, folders of where files were being copied from and to and if it accessed a DB it would also display the connection string. Enough to help you get an idea, but may be useless for complex programs. The programs I was looking at were pretty basic (no pun intended).

YMMV.

How to redirect page after click on Ok button on sweet alert?

To specify a callback function, you have to use an object as the first argument, and the callback function as the second argument.

echo '<script>
    setTimeout(function() {
        swal({
            title: "Wow!",
            text: "Message!",
            type: "success"
        }, function() {
            window.location = "redirectURL";
        });
    }, 1000);
</script>';

Collection that allows only unique items in .NET?

From the HashSet<T> page on MSDN:

The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

(emphasis mine)

How does numpy.histogram() work?

Another useful thing to do with numpy.histogram is to plot the output as the x and y coordinates on a linegraph. For example:

arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()

enter image description here

This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.

pip install returning invalid syntax

"D:\Program Files\Py\Scripts\pip.exe" install numpy -U

YOUR PATH to pip.exe in Python folder + install + YOUR LIB + -U

enter image description here

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Increasing the JVM maximum heap size for memory intensive applications

Below conf works for me:

JAVA_HOME=/JDK1.7.51-64/jdk1.7.0_51/
PATH=/JDK1.7.51-64/jdk1.7.0_51/bin:$PATH
export PATH
export JAVA_HOME

JVM_ARGS="-d64 -Xms1024m -Xmx15360m -server"

/JDK1.7.51-64/jdk1.7.0_51/bin/java $JVM_ARGS -jar `dirname $0`/ApacheJMeter.jar "$@"

How to delete all records from table in sqlite with Android?

this metod delate all data from database

 public void deleteAll()
{
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("delete from "+ TABLE_NAME);
    db.close();
}

Multiple commands on a single line in a Windows batch file

Can be achieved also with scriptrunner

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 

Which also have some features as rollback , timeout and waiting.

CSS: fixed to bottom and centered

The problem lies in position: static. Static means don't do anyting at all with the position. position: absolute is what you want. Centering the element is still tricky though. The following should work:

#whatever {
  position: absolute;
  bottom: 0px;
  margin-right: auto;
  margin-left: auto;
  left: 0px;
  right: 0px;
}

or

#whatever {
  position: absolute;
  bottom: 0px;
  margin-right: auto;
  margin-left: auto;
  left: 50%;
  transform: translate(-50%, 0);
}

But I recommend the first method. I used centering techniques from this answer: How to center absolutely positioned element in div?

How to get a context in a recycler view adapter

First add a global variable

Context mContext;

Then change your constructor to this

public FeedAdapter(Context context, List<Post> myDataset) {
    mContext = context;
    mDataset = myDataset;
}

The pass your context when creating the adapter.

FeedAdapter myAdapter = new FeedAdapter(this,myDataset);

Failed Apache2 start, no error log

I also just ran in to a similar problem, that is service apache2 reload fails but prints no useful information. This is because the script in /etc/init.d/apache (on Debian, at least) eats the output of the apache2ctl configtest command it runs to sanitize the Apache config.

An easy solution to get a more meaningful explanation for the failure is to run apache2ctl configtest again yourself, which will print the (hopefully useful) error messages to the console.

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

Converting an int to a binary string representation in Java?

Convert Integer to Binary:

import java.util.Scanner;

public class IntegerToBinary {

    public static void main(String[] args) {

        Scanner input = new Scanner( System.in );

        System.out.println("Enter Integer: ");
        String integerString =input.nextLine();

        System.out.println("Binary Number: "+Integer.toBinaryString(Integer.parseInt(integerString)));
    }

}

Output:

Enter Integer:

10

Binary Number: 1010

How can I return the sum and average of an int array?

You have tried the wrong variable, ints is not the correct name of the argument.

public int Sum(params int[] customerssalary)
{
    return customerssalary.Sum();
}

public double Avg(params int[] customerssalary)
{
    return customerssalary.Average();
}

But do you think that these methods are really needed?

JPA : How to convert a native query result set to POJO class collection

Using Hibernate :

@Transactional(readOnly=true)
public void accessUser() {
    EntityManager em = repo.getEntityManager();
    org.hibernate.Session session = em.unwrap(org.hibernate.Session.class);
    org.hibernate.SQLQuery q = (org.hibernate.SQLQuery) session.createSQLQuery("SELECT u.username, u.name, u.email, 'blabla' as passe, login_type as loginType FROM users u")
        .addScalar("username", StringType.INSTANCE).addScalar("name", StringType.INSTANCE)
        .addScalar("email", StringType.INSTANCE).addScalar("passe", StringType.INSTANCE)
        .addScalar("loginType", IntegerType.INSTANCE)
        .setResultTransformer(Transformers.aliasToBean(User2DTO.class));

    List<User2DTO> userList = q.list();
}

How do SO_REUSEADDR and SO_REUSEPORT differ?

Welcome to the wonderful world of portability... or rather the lack of it. Before we start analyzing these two options in detail and take a deeper look how different operating systems handle them, it should be noted that the BSD socket implementation is the mother of all socket implementations. Basically all other systems copied the BSD socket implementation at some point in time (or at least its interfaces) and then started evolving it on their own. Of course the BSD socket implementation was evolved as well at the same time and thus systems that copied it later got features that were lacking in systems that copied it earlier. Understanding the BSD socket implementation is the key to understanding all other socket implementations, so you should read about it even if you don't care to ever write code for a BSD system.

There are a couple of basics you should know before we look at these two options. A TCP/UDP connection is identified by a tuple of five values:

{<protocol>, <src addr>, <src port>, <dest addr>, <dest port>}

Any unique combination of these values identifies a connection. As a result, no two connections can have the same five values, otherwise the system would not be able to distinguish these connections any longer.

The protocol of a socket is set when a socket is created with the socket() function. The source address and port are set with the bind() function. The destination address and port are set with the connect() function. Since UDP is a connectionless protocol, UDP sockets can be used without connecting them. Yet it is allowed to connect them and in some cases very advantageous for your code and general application design. In connectionless mode, UDP sockets that were not explicitly bound when data is sent over them for the first time are usually automatically bound by the system, as an unbound UDP socket cannot receive any (reply) data. Same is true for an unbound TCP socket, it is automatically bound before it will be connected.

If you explicitly bind a socket, it is possible to bind it to port 0, which means "any port". Since a socket cannot really be bound to all existing ports, the system will have to choose a specific port itself in that case (usually from a predefined, OS specific range of source ports). A similar wildcard exists for the source address, which can be "any address" (0.0.0.0 in case of IPv4 and :: in case of IPv6). Unlike in case of ports, a socket can really be bound to "any address" which means "all source IP addresses of all local interfaces". If the socket is connected later on, the system has to choose a specific source IP address, since a socket cannot be connected and at the same time be bound to any local IP address. Depending on the destination address and the content of the routing table, the system will pick an appropriate source address and replace the "any" binding with a binding to the chosen source IP address.

By default, no two sockets can be bound to the same combination of source address and source port. As long as the source port is different, the source address is actually irrelevant. Binding socketA to ipA:portA and socketB to ipB:portB is always possible if ipA != ipB holds true, even when portA == portB. E.g. socketA belongs to a FTP server program and is bound to 192.168.0.1:21 and socketB belongs to another FTP server program and is bound to 10.0.0.1:21, both bindings will succeed. Keep in mind, though, that a socket may be locally bound to "any address". If a socket is bound to 0.0.0.0:21, it is bound to all existing local addresses at the same time and in that case no other socket can be bound to port 21, regardless which specific IP address it tries to bind to, as 0.0.0.0 conflicts with all existing local IP addresses.

Anything said so far is pretty much equal for all major operating system. Things start to get OS specific when address reuse comes into play. We start with BSD, since as I said above, it is the mother of all socket implementations.

BSD

SO_REUSEADDR

If SO_REUSEADDR is enabled on a socket prior to binding it, the socket can be successfully bound unless there is a conflict with another socket bound to exactly the same combination of source address and port. Now you may wonder how is that any different than before? The keyword is "exactly". SO_REUSEADDR mainly changes the way how wildcard addresses ("any IP address") are treated when searching for conflicts.

Without SO_REUSEADDR, binding socketA to 0.0.0.0:21 and then binding socketB to 192.168.0.1:21 will fail (with error EADDRINUSE), since 0.0.0.0 means "any local IP address", thus all local IP addresses are considered in use by this socket and this includes 192.168.0.1, too. With SO_REUSEADDR it will succeed, since 0.0.0.0 and 192.168.0.1 are not exactly the same address, one is a wildcard for all local addresses and the other one is a very specific local address. Note that the statement above is true regardless in which order socketA and socketB are bound; without SO_REUSEADDR it will always fail, with SO_REUSEADDR it will always succeed.

To give you a better overview, let's make a table here and list all possible combinations:

SO_REUSEADDR       socketA        socketB       Result
---------------------------------------------------------------------
  ON/OFF       192.168.0.1:21   192.168.0.1:21    Error (EADDRINUSE)
  ON/OFF       192.168.0.1:21      10.0.0.1:21    OK
  ON/OFF          10.0.0.1:21   192.168.0.1:21    OK
   OFF             0.0.0.0:21   192.168.1.0:21    Error (EADDRINUSE)
   OFF         192.168.1.0:21       0.0.0.0:21    Error (EADDRINUSE)
   ON              0.0.0.0:21   192.168.1.0:21    OK
   ON          192.168.1.0:21       0.0.0.0:21    OK
  ON/OFF           0.0.0.0:21       0.0.0.0:21    Error (EADDRINUSE)

The table above assumes that socketA has already been successfully bound to the address given for socketA, then socketB is created, either gets SO_REUSEADDR set or not, and finally is bound to the address given for socketB. Result is the result of the bind operation for socketB. If the first column says ON/OFF, the value of SO_REUSEADDR is irrelevant to the result.

Okay, SO_REUSEADDR has an effect on wildcard addresses, good to know. Yet that isn't it's only effect it has. There is another well known effect which is also the reason why most people use SO_REUSEADDR in server programs in the first place. For the other important use of this option we have to take a deeper look on how the TCP protocol works.

A socket has a send buffer and if a call to the send() function succeeds, it does not mean that the requested data has actually really been sent out, it only means the data has been added to the send buffer. For UDP sockets, the data is usually sent pretty soon, if not immediately, but for TCP sockets, there can be a relatively long delay between adding data to the send buffer and having the TCP implementation really send that data. As a result, when you close a TCP socket, there may still be pending data in the send buffer, which has not been sent yet but your code considers it as sent, since the send() call succeeded. If the TCP implementation was closing the socket immediately on your request, all of this data would be lost and your code wouldn't even know about that. TCP is said to be a reliable protocol and losing data just like that is not very reliable. That's why a socket that still has data to send will go into a state called TIME_WAIT when you close it. In that state it will wait until all pending data has been successfully sent or until a timeout is hit, in which case the socket is closed forcefully.

At most, the amount of time the kernel will wait before it closes the socket, regardless if it still has data in flight or not, is called the Linger Time. The Linger Time is globally configurable on most systems and by default rather long (two minutes is a common value you will find on many systems). It is also configurable per socket using the socket option SO_LINGER which can be used to make the timeout shorter or longer, and even to disable it completely. Disabling it completely is a very bad idea, though, since closing a TCP socket gracefully is a slightly complex process and involves sending forth and back a couple of packets (as well as resending those packets in case they got lost) and this whole close process is also limited by the Linger Time. If you disable lingering, your socket may not only lose data in flight, it is also always closed forcefully instead of gracefully, which is usually not recommended. The details about how a TCP connection is closed gracefully are beyond the scope of this answer, if you want to learn more about, I recommend you have a look at this page. And even if you disabled lingering with SO_LINGER, if your process dies without explicitly closing the socket, BSD (and possibly other systems) will linger nonetheless, ignoring what you have configured. This will happen for example if your code just calls exit() (pretty common for tiny, simple server programs) or the process is killed by a signal (which includes the possibility that it simply crashes because of an illegal memory access). So there is nothing you can do to make sure a socket will never linger under all circumstances.

The question is, how does the system treat a socket in state TIME_WAIT? If SO_REUSEADDR is not set, a socket in state TIME_WAIT is considered to still be bound to the source address and port and any attempt to bind a new socket to the same address and port will fail until the socket has really been closed, which may take as long as the configured Linger Time. So don't expect that you can rebind the source address of a socket immediately after closing it. In most cases this will fail. However, if SO_REUSEADDR is set for the socket you are trying to bind, another socket bound to the same address and port in state TIME_WAIT is simply ignored, after all its already "half dead", and your socket can bind to exactly the same address without any problem. In that case it plays no role that the other socket may have exactly the same address and port. Note that binding a socket to exactly the same address and port as a dying socket in TIME_WAIT state can have unexpected, and usually undesired, side effects in case the other socket is still "at work", but that is beyond the scope of this answer and fortunately those side effects are rather rare in practice.

There is one final thing you should know about SO_REUSEADDR. Everything written above will work as long as the socket you want to bind to has address reuse enabled. It is not necessary that the other socket, the one which is already bound or is in a TIME_WAIT state, also had this flag set when it was bound. The code that decides if the bind will succeed or fail only inspects the SO_REUSEADDR flag of the socket fed into the bind() call, for all other sockets inspected, this flag is not even looked at.

SO_REUSEPORT

SO_REUSEPORT is what most people would expect SO_REUSEADDR to be. Basically, SO_REUSEPORT allows you to bind an arbitrary number of sockets to exactly the same source address and port as long as all prior bound sockets also had SO_REUSEPORT set before they were bound. If the first socket that is bound to an address and port does not have SO_REUSEPORT set, no other socket can be bound to exactly the same address and port, regardless if this other socket has SO_REUSEPORT set or not, until the first socket releases its binding again. Unlike in case of SO_REUESADDR the code handling SO_REUSEPORT will not only verify that the currently bound socket has SO_REUSEPORT set but it will also verify that the socket with a conflicting address and port had SO_REUSEPORT set when it was bound.

SO_REUSEPORT does not imply SO_REUSEADDR. This means if a socket did not have SO_REUSEPORT set when it was bound and another socket has SO_REUSEPORT set when it is bound to exactly the same address and port, the bind fails, which is expected, but it also fails if the other socket is already dying and is in TIME_WAIT state. To be able to bind a socket to the same addresses and port as another socket in TIME_WAIT state requires either SO_REUSEADDR to be set on that socket or SO_REUSEPORT must have been set on both sockets prior to binding them. Of course it is allowed to set both, SO_REUSEPORT and SO_REUSEADDR, on a socket.

There is not much more to say about SO_REUSEPORT other than that it was added later than SO_REUSEADDR, that's why you will not find it in many socket implementations of other systems, which "forked" the BSD code before this option was added, and that there was no way to bind two sockets to exactly the same socket address in BSD prior to this option.

Connect() Returning EADDRINUSE?

Most people know that bind() may fail with the error EADDRINUSE, however, when you start playing around with address reuse, you may run into the strange situation that connect() fails with that error as well. How can this be? How can a remote address, after all that's what connect adds to a socket, be already in use? Connecting multiple sockets to exactly the same remote address has never been a problem before, so what's going wrong here?

As I said on the very top of my reply, a connection is defined by a tuple of five values, remember? And I also said, that these five values must be unique otherwise the system cannot distinguish two connections any longer, right? Well, with address reuse, you can bind two sockets of the same protocol to the same source address and port. That means three of those five values are already the same for these two sockets. If you now try to connect both of these sockets also to the same destination address and port, you would create two connected sockets, whose tuples are absolutely identical. This cannot work, at least not for TCP connections (UDP connections are no real connections anyway). If data arrived for either one of the two connections, the system could not tell which connection the data belongs to. At least the destination address or destination port must be different for either connection, so that the system has no problem to identify to which connection incoming data belongs to.

So if you bind two sockets of the same protocol to the same source address and port and try to connect them both to the same destination address and port, connect() will actually fail with the error EADDRINUSE for the second socket you try to connect, which means that a socket with an identical tuple of five values is already connected.

Multicast Addresses

Most people ignore the fact that multicast addresses exist, but they do exist. While unicast addresses are used for one-to-one communication, multicast addresses are used for one-to-many communication. Most people got aware of multicast addresses when they learned about IPv6 but multicast addresses also existed in IPv4, even though this feature was never widely used on the public Internet.

The meaning of SO_REUSEADDR changes for multicast addresses as it allows multiple sockets to be bound to exactly the same combination of source multicast address and port. In other words, for multicast addresses SO_REUSEADDR behaves exactly as SO_REUSEPORT for unicast addresses. Actually, the code treats SO_REUSEADDR and SO_REUSEPORT identically for multicast addresses, that means you could say that SO_REUSEADDR implies SO_REUSEPORT for all multicast addresses and the other way round.


FreeBSD/OpenBSD/NetBSD

All these are rather late forks of the original BSD code, that's why they all three offer the same options as BSD and they also behave the same way as in BSD.


macOS (MacOS X)

At its core, macOS is simply a BSD-style UNIX named "Darwin", based on a rather late fork of the BSD code (BSD 4.3), which was then later on even re-synchronized with the (at that time current) FreeBSD 5 code base for the Mac OS 10.3 release, so that Apple could gain full POSIX compliance (macOS is POSIX certified). Despite having a microkernel at its core ("Mach"), the rest of the kernel ("XNU") is basically just a BSD kernel, and that's why macOS offers the same options as BSD and they also behave the same way as in BSD.

iOS / watchOS / tvOS

iOS is just a macOS fork with a slightly modified and trimmed kernel, somewhat stripped down user space toolset and a slightly different default framework set. watchOS and tvOS are iOS forks, that are stripped down even further (especially watchOS). To my best knowledge they all behave exactly as macOS does.


Linux

Linux < 3.9

Prior to Linux 3.9, only the option SO_REUSEADDR existed. This option behaves generally the same as in BSD with two important exceptions:

  1. As long as a listening (server) TCP socket is bound to a specific port, the SO_REUSEADDR option is entirely ignored for all sockets targeting that port. Binding a second socket to the same port is only possible if it was also possible in BSD without having SO_REUSEADDR set. E.g. you cannot bind to a wildcard address and then to a more specific one or the other way round, both is possible in BSD if you set SO_REUSEADDR. What you can do is you can bind to the same port and two different non-wildcard addresses, as that's always allowed. In this aspect Linux is more restrictive than BSD.

  2. The second exception is that for client sockets, this option behaves exactly like SO_REUSEPORT in BSD, as long as both had this flag set before they were bound. The reason for allowing that was simply that it is important to be able to bind multiple sockets to exactly to the same UDP socket address for various protocols and as there used to be no SO_REUSEPORT prior to 3.9, the behavior of SO_REUSEADDR was altered accordingly to fill that gap. In that aspect Linux is less restrictive than BSD.

Linux >= 3.9

Linux 3.9 added the option SO_REUSEPORT to Linux as well. This option behaves exactly like the option in BSD and allows binding to exactly the same address and port number as long as all sockets have this option set prior to binding them.

Yet, there are still two differences to SO_REUSEPORT on other systems:

  1. To prevent "port hijacking", there is one special limitation: All sockets that want to share the same address and port combination must belong to processes that share the same effective user ID! So one user cannot "steal" ports of another user. This is some special magic to somewhat compensate for the missing SO_EXCLBIND/SO_EXCLUSIVEADDRUSE flags.

  2. Additionally the kernel performs some "special magic" for SO_REUSEPORT sockets that isn't found in other operating systems: For UDP sockets, it tries to distribute datagrams evenly, for TCP listening sockets, it tries to distribute incoming connect requests (those accepted by calling accept()) evenly across all the sockets that share the same address and port combination. Thus an application can easily open the same port in multiple child processes and then use SO_REUSEPORT to get a very inexpensive load balancing.


Android

Even though the whole Android system is somewhat different from most Linux distributions, at its core works a slightly modified Linux kernel, thus everything that applies to Linux should apply to Android as well.


Windows

Windows only knows the SO_REUSEADDR option, there is no SO_REUSEPORT. Setting SO_REUSEADDR on a socket in Windows behaves like setting SO_REUSEPORT and SO_REUSEADDR on a socket in BSD, with one exception:

Prior to Windows 2003, a socket with SO_REUSEADDR could always been bound to exactly the same source address and port as an already bound socket, even if the other socket did not have this option set when it was bound. This behavior allowed an application "to steal" the connected port of another application. Needless to say that this has major security implications!

Microsoft realized that and added another important socket option: SO_EXCLUSIVEADDRUSE. Setting SO_EXCLUSIVEADDRUSE on a socket makes sure that if the binding succeeds, the combination of source address and port is owned exclusively by this socket and no other socket can bind to them, not even if it has SO_REUSEADDR set.

This default behavior was changed first in Windows 2003, Microsoft calls that "Enhanced Socket Security" (funny name for a behavior that is default on all other major operating systems). For more details just visit this page. There are three tables: The first one shows the classic behavior (still in use when using compatibility modes!), the second one shows the behavior of Windows 2003 and up when the bind() calls are made by the same user, and the third one when the bind() calls are made by different users.


Solaris

Solaris is the successor of SunOS. SunOS was originally based on a fork of BSD, SunOS 5 and later was based on a fork of SVR4, however SVR4 is a merge of BSD, System V, and Xenix, so up to some degree Solaris is also a BSD fork, and a rather early one. As a result Solaris only knows SO_REUSEADDR, there is no SO_REUSEPORT. The SO_REUSEADDR behaves pretty much the same as it does in BSD. As far as I know there is no way to get the same behavior as SO_REUSEPORT in Solaris, that means it is not possible to bind two sockets to exactly the same address and port.

Similar to Windows, Solaris has an option to give a socket an exclusive binding. This option is named SO_EXCLBIND. If this option is set on a socket prior to binding it, setting SO_REUSEADDR on another socket has no effect if the two sockets are tested for an address conflict. E.g. if socketA is bound to a wildcard address and socketB has SO_REUSEADDR enabled and is bound to a non-wildcard address and the same port as socketA, this bind will normally succeed, unless socketA had SO_EXCLBIND enabled, in which case it will fail regardless the SO_REUSEADDR flag of socketB.


Other Systems

In case your system is not listed above, I wrote a little test program that you can use to find out how your system handles these two options. Also if you think my results are wrong, please first run that program before posting any comments and possibly making false claims.

All that the code requires to build is a bit POSIX API (for the network parts) and a C99 compiler (actually most non-C99 compiler will work as well as long as they offer inttypes.h and stdbool.h; e.g. gcc supported both long before offering full C99 support).

All that the program needs to run is that at least one interface in your system (other than the local interface) has an IP address assigned and that a default route is set which uses that interface. The program will gather that IP address and use it as the second "specific address".

It tests all possible combinations you can think of:

  • TCP and UDP protocol
  • Normal sockets, listen (server) sockets, multicast sockets
  • SO_REUSEADDR set on socket1, socket2, or both sockets
  • SO_REUSEPORT set on socket1, socket2, or both sockets
  • All address combinations you can make out of 0.0.0.0 (wildcard), 127.0.0.1 (specific address), and the second specific address found at your primary interface (for multicast it's just 224.1.2.3 in all tests)

and prints the results in a nice table. It will also work on systems that don't know SO_REUSEPORT, in which case this option is simply not tested.

What the program cannot easily test is how SO_REUSEADDR acts on sockets in TIME_WAIT state as it's very tricky to force and keep a socket in that state. Fortunately most operating systems seems to simply behave like BSD here and most of the time programmers can simply ignore the existence of that state.

Here's the code (I cannot include it here, answers have a size limit and the code would push this reply over the limit).

Can I target all <H> tags with a single selector?

You can also use PostCSS and the custom selectors plugin

@custom-selector :--headings h1, h2, h3, h4, h5, h6;

article :--headings {
  margin-top: 0;
}

Output:

article h1,
article h2,
article h3,
article h4,
article h5,
article h6 {
  margin-top: 0;
}

Open a PDF using VBA in Excel

Here is a simplified version of this script to copy a pdf into a XL file.


Sub CopyOnePDFtoExcel()

    Dim ws As Worksheet
    Dim PDF_path As String

    PDF_path = "C:\Users\...\Documents\This-File.pdf"


    'open the pdf file
    ActiveWorkbook.FollowHyperlink PDF_path

    SendKeys "^a", True
    SendKeys "^c"

    Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)

    Application.ScreenUpdating = False

    Set ws = ThisWorkbook.Sheets("Sheet1")

    ws.Activate
    ws.Range("A1").ClearContents
    ws.Range("A1").Select
    ws.Paste

    Application.ScreenUpdating = True

End Sub

Changing MongoDB data store directory

In debian/ubuntu, you'll need to edit the /etc/init.d/mongodb script. Really, this file should be pulling the settings from /etc/mongodb.conf but it doesn't seem to pull the default directory (probably a bug)

This is a bit of a hack, but adding these to the script made it start correctly:

add:

DBDIR=/database/mongodb

change:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --config $CONF run"}

to:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --dbpath $DBDIR --config $CONF run"}

Setting and getting localStorage with jQuery

Use setItem and getItem if you want to write simple strings to localStorage. Also you should be using text() if it's the text you're after as you say, else you will get the full HTML as a string.

Sample using .text()

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// alert the value to check if we got it
alert(localStorage.getItem('test'));

JSFiddle: https://jsfiddle.net/f3zLa3zc/


Storing the HTML itself

// get html
var html = $('#test')[0].outerHTML;

// set localstorage
localStorage.setItem('htmltest', html);

// test if it works
alert(localStorage.getItem('htmltest'));

JSFiddle:
https://jsfiddle.net/psfL82q3/1/


Update on user comment

A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable and blur() is used to change the contents of the div and overwrite the old localStorage entry.

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// bind text to 'blur' event for div
$('#test').on('blur', function() {

    // check the new text
    var newText = $(this).text();

    // overwrite the old text
    localStorage.setItem('test', newText);

    // test if it works
    alert(localStorage.getItem('test'));

});

If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.

JSFiddle:
https://jsfiddle.net/g1b8m1fc/

How can I escape latex code received through user input?

Python’s raw strings are just a way to tell the Python interpreter that it should interpret backslashes as literal slashes. If you read strings entered by the user, they are already past the point where they could have been raw. Also, user input is most likely read in literally, i.e. “raw”.

This means the interpreting happens somewhere else. But if you know that it happens, why not escape the backslashes for whatever is interpreting it?

s = s.replace("\\", "\\\\")

(Note that you can't do r"\" as “a raw string cannot end in a single backslash”, but I could have used r"\\" as well for the second argument.)

If that doesn’t work, your user input is for some arcane reason interpreting the backslashes, so you’ll need a way to tell it to stop that.

How do I avoid the "#DIV/0!" error in Google docs spreadsheet?

Wrap your formula with IFERROR.

=IFERROR(yourformula)

What is the purpose and use of **kwargs?

On the basis that a good sample is sometimes better than a long discourse I will write two functions using all python variable argument passing facilities (both positional and named arguments). You should easily be able to see what it does by yourself:

def f(a = 0, *args, **kwargs):
    print("Received by f(a, *args, **kwargs)")
    print("=> f(a=%s, args=%s, kwargs=%s" % (a, args, kwargs))
    print("Calling g(10, 11, 12, *args, d = 13, e = 14, **kwargs)")
    g(10, 11, 12, *args, d = 13, e = 14, **kwargs)

def g(f, g = 0, *args, **kwargs):
    print("Received by g(f, g = 0, *args, **kwargs)")
    print("=> g(f=%s, g=%s, args=%s, kwargs=%s)" % (f, g, args, kwargs))

print("Calling f(1, 2, 3, 4, b = 5, c = 6)")
f(1, 2, 3, 4, b = 5, c = 6)

And here is the output:

Calling f(1, 2, 3, 4, b = 5, c = 6)
Received by f(a, *args, **kwargs) 
=> f(a=1, args=(2, 3, 4), kwargs={'c': 6, 'b': 5}
Calling g(10, 11, 12, *args, d = 13, e = 14, **kwargs)
Received by g(f, g = 0, *args, **kwargs)
=> g(f=10, g=11, args=(12, 2, 3, 4), kwargs={'c': 6, 'b': 5, 'e': 14, 'd': 13})

Adding a column to an existing table in a Rails migration

You could rollback the last migration by

rake db:rollback STEP=1

or rollback this specific migration by

rake db:migrate:down VERSION=<YYYYMMDDHHMMSS>

and edit the file, then run rake db:mirgate again.

Alert handling in Selenium WebDriver (selenium 2) with Java

This is what worked for me using Explicit Wait from here WebDriver: Advanced Usage

public void checkAlert() {
    try {
        WebDriverWait wait = new WebDriverWait(driver, 2);
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        alert.accept();
    } catch (Exception e) {
        //exception handling
    }
}

Starting the week on Monday with isoWeekday()

Here is a more generic solution for any given weekday. Working demo on jsfiddle

var myIsoWeekDay = 2; // say our weeks start on tuesday, for monday you would type 1, etc.

var startOfPeriod = moment("2013-06-23T00:00:00"),

// how many days do we have to substract?
var daysToSubtract = moment(startOfPeriod).isoWeekday() >= myIsoWeekDay ?
    moment(startOfPeriod).isoWeekday() - myIsoWeekDay :
    7 + moment(startOfPeriod).isoWeekday() - myIsoWeekDay;

// subtract days from start of period
var begin = moment(startOfPeriod).subtract('d', daysToSubtract);

Iterate two Lists or Arrays with one ForEach statement in C#

Here's a custom IEnumerable<> extension method that can be used to loop through two lists simultaneously.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    public static class LinqCombinedSort
    {
        public static void Test()
        {
            var a = new[] {'a', 'b', 'c', 'd', 'e', 'f'};
            var b = new[] {3, 2, 1, 6, 5, 4};

            var sorted = from ab in a.Combine(b)
                         orderby ab.Second
                         select ab.First;

            foreach(char c in sorted)
            {
                Console.WriteLine(c);
            }
        }

        public static IEnumerable<Pair<TFirst, TSecond>> Combine<TFirst, TSecond>(this IEnumerable<TFirst> s1, IEnumerable<TSecond> s2)
        {
            using (var e1 = s1.GetEnumerator())
            using (var e2 = s2.GetEnumerator())
            {
                while (e1.MoveNext() && e2.MoveNext())
                {
                    yield return new Pair<TFirst, TSecond>(e1.Current, e2.Current);
                }
            }

        }


    }
    public class Pair<TFirst, TSecond>
    {
        private readonly TFirst _first;
        private readonly TSecond _second;
        private int _hashCode;

        public Pair(TFirst first, TSecond second)
        {
            _first = first;
            _second = second;
        }

        public TFirst First
        {
            get
            {
                return _first;
            }
        }

        public TSecond Second
        {
            get
            {
                return _second;
            }
        }

        public override int GetHashCode()
        {
            if (_hashCode == 0)
            {
                _hashCode = (ReferenceEquals(_first, null) ? 213 : _first.GetHashCode())*37 +
                            (ReferenceEquals(_second, null) ? 213 : _second.GetHashCode());
            }
            return _hashCode;
        }

        public override bool Equals(object obj)
        {
            var other = obj as Pair<TFirst, TSecond>;
            if (other == null)
            {
                return false;
            }
            return Equals(_first, other._first) && Equals(_second, other._second);
        }
    }

}

Write objects into file with Node.js

could you try doing JSON.stringify(obj);

Like this

 var stringify = JSON.stringify(obj);
fs.writeFileSync('./data.json', stringify , 'utf-8'); 

How does the "this" keyword work?

A little bit info about this keyword

Let's log this keyword to the console in global scope without any more code but

console.log(this)

In Client/Browser this keyword is a global object which is window

console.log(this === window) // true

and

In Server/Node/Javascript runtime this keyword is also a global object which is module.exports

console.log(this === module.exports) // true
console.log(this === exports) // true

Keep in mind exports is just a reference to module.exports

jQuery SVG vs. Raphael

Since it's not mentioned here yet: You should also take a look at Dojox.drawing, which also provides good SVG drawing capabilities. It has a pretty impressive set of features. I'm just starting a project with it, but it seems to me that it's far superior (at least in terms of features) to Raphael and JQuerySVG.

This presentation convinced me to use it instead of Raphael/JQuerySVG: http://www.slideshare.net/elazutkin/dojo-gfx-svg-in-the-real-world-2114082

Reference: http://dojotoolkit.org/reference-guide/dojox/index.html

Reference on Dojocampus: http://docs.dojocampus.org/dojox/drawing

Download Dojo (including Dojox): http://dojotoolkit.org/download/

Subtract two dates in SQL and get days of the result

EDIT: It seems I was wrong about the performance on the code example. The best performer is whichever snippet runs second in the posted case. This demonstrates what I was trying to explain, and the time differences are not as dramatic:

----------------------------------
--  Monitor time differences
----------------------------------
CREATE CLUSTERED INDEX dtIDX ON #ArbDates (MyDate)
DECLARE @Stopwatch DATETIME 
SET @Stopwatch = GETDATE()
    -- SARGABLE
    SELECT *
    FROM #ArbDates
    WHERE MyDate > DATEADD(DAY, -364, '2010-01-01')


PRINT DATEDIFF(MS, @Stopwatch, GETDATE())
SET @Stopwatch = GETDATE()
    -- NOT SARGABLE
    SELECT *
    FROM #ArbDates
    WHERE DATEDIFF(DAY, MyDate, '2010-01-01') < 365
PRINT DATEDIFF(MS, @Stopwatch, GETDATE())

Excuse me for posting late and my crudely commented example, but I think it important to mention SARG.

SELECT I.Fee
FROM Item I
WHERE  I.DateCreated > DATEADD(DAY, -364, GETDATE())

Although the temp table in the code below has no index, the performance is still enhanced by the fact that a comparison is done between an expression and a value in the table and not an expression that modifies the value in the table and a constant. Hope this is found to be useful.

USE tempdb
GO

IF OBJECT_ID('tempdb.dbo.#ArbDates') IS NOT NULL DROP TABLE #ArbDates
DECLARE @Stopwatch DATETIME 

----------------------------------
--  Build test data: 100000 rows
----------------------------------
;WITH Base10 (n) AS
(
    SELECT 1 UNION ALL  SELECT 1 UNION ALL  SELECT 1 UNION ALL
    SELECT 1 UNION ALL  SELECT 1 UNION ALL  SELECT 1 UNION ALL
    SELECT 1 UNION ALL  SELECT 1 UNION ALL  SELECT 1 UNION ALL
    SELECT 1
)
,Base100000 (n) AS
(
    SELECT 1
    FROM Base10 T1, Base10 T3, Base10 T4, Base10 T5, Base10 T6
)
SELECT MyDate = CAST(RAND(CHECKSUM(NEWID()))*3653.0+36524.0 AS DATETIME) 
INTO #ArbDates 
FROM Base100000

----------------------------------
--  Monitor time differences
----------------------------------
SET @Stopwatch = GETDATE()

    -- NOT SARGABLE
    SELECT *
    FROM #ArbDates
    WHERE DATEDIFF(DAY, MyDate, '2010-01-01') < 365

PRINT DATEDIFF(MS, @Stopwatch, GETDATE())
SET @Stopwatch = GETDATE()

    -- SARGABLE
    SELECT *
    FROM #ArbDates
    WHERE MyDate > DATEADD(DAY, -364, '2010-01-01')

PRINT DATEDIFF(MS, @Stopwatch, GETDATE())

pandas groupby sort descending order

As of Pandas 0.18 one way to do this is to use the sort_index method of the grouped data.

Here's an example:

np.random.seed(1)
n=10
df = pd.DataFrame({'mygroups' : np.random.choice(['dogs','cats','cows','chickens'], size=n), 
                   'data' : np.random.randint(1000, size=n)})

grouped = df.groupby('mygroups', sort=False).sum()
grouped.sort_index(ascending=False)
print grouped

data
mygroups      
dogs      1831
chickens  1446
cats       933

As you can see, the groupby column is sorted descending now, indstead of the default which is ascending.

Rename multiple files based on pattern in Unix

Using find, xargs and sed:

find . -name "fgh*" -type f -print0 | xargs -0 -I {} sh -c 'mv "{}" "$(dirname "{}")/`echo $(basename "{}") | sed 's/^fgh/jkl/g'`"'

It's more complex than @nik's solution but it allows to rename files recursively. For instance, the structure,

.
+-- fghdir
¦   +-- fdhfilea
¦   +-- fghfilea
+-- fghfile\ e
+-- fghfilea
+-- fghfileb
+-- fghfilec
+-- other
    +-- fghfile\ e
    +-- fghfilea
    +-- fghfileb
    +-- fghfilec

would be transformed to this,

.
+-- fghdir
¦   +-- fdhfilea
¦   +-- jklfilea
+-- jklfile\ e
+-- jklfilea
+-- jklfileb
+-- jklfilec
+-- other
    +-- jklfile\ e
    +-- jklfilea
    +-- jklfileb
    +-- jklfilec

The key to make it work with xargs is to invoke the shell from xargs.

How to read a Parquet file into Pandas DataFrame?

pandas 0.21 introduces new functions for Parquet:

pd.read_parquet('example_pa.parquet', engine='pyarrow')

or

pd.read_parquet('example_fp.parquet', engine='fastparquet')

The above link explains:

These engines are very similar and should read/write nearly identical parquet format files. These libraries differ by having different underlying dependencies (fastparquet by using numba, while pyarrow uses a c-library).

Convert timestamp to date in Oracle SQL

You can try the simple one

select to_date('2020-07-08T15:30:42Z','yyyy-mm-dd"T"hh24:mi:ss"Z"') from dual;

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

Go to:

Settings -> Preferences You will see a dialog box. There click the Backup / Auto-completion tab where you can set the auto complete option :)

Best practice to run Linux service as a different user

  • Some daemons (e.g. apache) do this by themselves by calling setuid()
  • You could use the setuid-file flag to run the process as a different user.
  • Of course, the solution you mentioned works as well.

If you intend to write your own daemon, then I recommend calling setuid(). This way, your process can

  1. Make use of its root privileges (e.g. open log files, create pid files).
  2. Drop its root privileges at a certain point during startup.

Git branching: master vs. origin/master vs. remotes/origin/master

  1. origin - This is a custom and most common name to point to remote.

$ git remote add origin https://github.com/git/git.git --- You will run this command to link your github project to origin. Here origin is user-defined. You can rename it by $ git remote rename old-name new-name


  1. master - The default branch name in Git is master. For both remote and local computer.

  1. origin/master - This is just a pointer to refer master branch in remote repo. Remember i said origin points to remote.

$ git fetch origin - Downloads objects and refs from remote repository to your local computer [origin/master]. That means it will not affect your local master branch unless you merge them using $ git merge origin/master. Remember to checkout the correct branch where you need to merge before run this command

Note: Fetched content is represented as a remote branch. Fetch gives you a chance to review changes before integrating them into your copy of the project. To show changes between yours and remote $git diff master..origin/master

How to download all dependencies and packages to directory

This will download all packages and dependencies (no already installed) to a directory of your choice:

sudo apt-get install -d -o Dir::Cache=/path-to/directory/apt/cache -o Dir::State::Lists=/path-to/directory/apt/lists packages

Make sure /path-to/directory/apt/cache and /path-to/directory/apt/lists exist. If you don't set -o Dir::Cache it points to /var/cache/apt, Dir::State::Lists points to /var/lib/apt/lists (which keeps the index files of available packages)

Both -o options can be used with update and upgrade instead of install.

On different machine run the same command without '-d'

How does the stack work in assembly language?

(I've made a gist of all the code in this answer in case you want to play with it)

I have only ever did most basic things in asm during my CS101 course back in 2003. And I had never really "got it" how asm and stack work until I've realized that it's all basicaly like programming in C or C++ ... but without local variables, parameters and functions. Probably doesn't sound easy yet :) Let me show you (for x86 asm with Intel syntax).


1. What is the stack

Stack is usually a contiguous chunk of memory allocated for every thread before they start. You can store there whatever you want. In C++ terms (code snippet #1):

const int STACK_CAPACITY = 1000;
thread_local int stack[STACK_CAPACITY];

2. Stack's top and bottom

In principle, you could store values in random cells of stack array (snippet #2.1):

stack[333] = 123;
stack[517] = 456;
stack[555] = stack[333] + stack[517];

But imagine how hard would it be to remember which cells of stack are already in use and wich ones are "free". That's why we store new values on the stack next to each other.

One weird thing about (x86) asm's stack is that you add things there starting with the last index and move to lower indexes: stack[999], then stack[998] and so on (snippet #2.2):

stack[999] = 123;
stack[998] = 456;
stack[997] = stack[999] + stack[998];

And still (caution, you're gonna be confused now) the "official" name for stack[999] is bottom of the stack.
The last used cell (stack[997] in the example above) is called top of the stack (see Where the top of the stack is on x86).


3. Stack pointer (SP)

For the purpose of this discussion let's assume CPU registers are represented as global variables (see General-Purpose Registers).

int AX, BX, SP, BP, ...;
int main(){...}

There is special CPU register (SP) that tracks the top of the stack. SP is a pointer (holds a memory address like 0xAAAABBCC). But for the purposes of this post I'll use it as an array index (0, 1, 2, ...).

When a thread starts, SP == STACK_CAPACITY and then the program and OS modify it as needed. The rule is you can't write to stack cells beyond stack's top and any index less then SP is invalid and unsafe (because of system interrupts), so you first decrement SP and then write a value to the newly allocated cell.

When you want to push several values in the stack in a row, you can reserve space for all of them upfront (snippet #3):

SP -= 3;
stack[999] = 12;
stack[998] = 34;
stack[997] = stack[999] + stack[998];

Note. Now you can see why allocation on the stack is so fast - it's just a single register decrement.


4. Local variables

Let's take a look at this simplistic function (snippet #4.1):

int triple(int a) {
    int result = a * 3;
    return result;
}

and rewrite it without using of local variable (snippet #4.2):

int triple_noLocals(int a) {
    SP -= 1; // move pointer to unused cell, where we can store what we need
    stack[SP] = a * 3;
    return stack[SP];
}

and see how it is being called (snippet #4.3):

// SP == 1000
someVar = triple_noLocals(11);
// now SP == 999, but we don't need the value at stack[999] anymore
// and we will move the stack index back, so we can reuse this cell later
SP += 1; // SP == 1000 again

5. Push / pop

Addition of a new element on the top of the stack is such a frequent operation, that CPUs have a special instruction for that, push. We'll implent it like this (snippet 5.1):

void push(int value) {
    --SP;
    stack[SP] = value;
}

Likewise, taking the top element of the stack (snippet 5.2):

void pop(int& result) {
    result = stack[SP];
    ++SP; // note that `pop` decreases stack's size
}

Common usage pattern for push/pop is temporarily saving some value. Say, we have something useful in variable myVar and for some reason we need to do calculations which will overwrite it (snippet 5.3):

int myVar = ...;
push(myVar); // SP == 999
myVar += 10;
... // do something with new value in myVar
pop(myVar); // restore original value, SP == 1000

6. Function parameters

Now let's pass parameters using stack (snippet #6):

int triple_noL_noParams() { // `a` is at index 999, SP == 999
    SP -= 1; // SP == 998, stack[SP + 1] == a
    stack[SP] = stack[SP + 1] * 3;
    return stack[SP];
}

int main(){
    push(11); // SP == 999
    assert(triple(11) == triple_noL_noParams());
    SP += 2; // cleanup 1 local and 1 parameter
}

7. return statement

Let's return value in AX register (snippet #7):

void triple_noL_noP_noReturn() { // `a` at 998, SP == 998
    SP -= 1; // SP == 997

    stack[SP] = stack[SP + 1] * 3;
    AX = stack[SP];

    SP += 1; // finally we can cleanup locals right in the function body, SP == 998
}

void main(){
    ... // some code
    push(AX); // save AX in case there is something useful there, SP == 999
    push(11); // SP == 998
    triple_noL_noP_noReturn();
    assert(triple(11) == AX);
    SP += 1; // cleanup param
             // locals were cleaned up in the function body, so we don't need to do it here
    pop(AX); // restore AX
    ...
}

8. Stack base pointer (BP) (also known as frame pointer) and stack frame

Lets take more "advanced" function and rewrite it in our asm-like C++ (snippet #8.1):

int myAlgo(int a, int b) {
    int t1 = a * 3;
    int t2 = b * 3;
    return t1 - t2;
}

void myAlgo_noLPR() { // `a` at 997, `b` at 998, old AX at 999, SP == 997
    SP -= 2; // SP == 995

    stack[SP + 1] = stack[SP + 2] * 3; 
    stack[SP]     = stack[SP + 3] * 3;
    AX = stack[SP + 1] - stack[SP];

    SP += 2; // cleanup locals, SP == 997
}

int main(){
    push(AX); // SP == 999
    push(22); // SP == 998
    push(11); // SP == 997
    myAlgo_noLPR();
    assert(myAlgo(11, 22) == AX);
    SP += 2;
    pop(AX);
}

Now imagine we decided to introduce new local variable to store result there before returning, as we do in tripple (snippet #4.1). The body of the function will be (snippet #8.2):

SP -= 3; // SP == 994
stack[SP + 2] = stack[SP + 3] * 3; 
stack[SP + 1] = stack[SP + 4] * 3;
stack[SP]     = stack[SP + 2] - stack[SP + 1];
AX = stack[SP];
SP += 3;

You see, we had to update every single reference to function parameters and local variables. To avoid that, we need an anchor index, which doesn't change when the stack grows.

We will create the anchor right upon function entry (before we allocate space for locals) by saving current top (value of SP) into BP register. Snippet #8.3:

void myAlgo_noLPR_withAnchor() { // `a` at 997, `b` at 998, SP == 997
    push(BP);   // save old BP, SP == 996
    BP = SP;    // create anchor, stack[BP] == old value of BP, now BP == 996
    SP -= 2;    // SP == 994

    stack[BP - 1] = stack[BP + 1] * 3;
    stack[BP - 2] = stack[BP + 2] * 3;
    AX = stack[BP - 1] - stack[BP - 2];

    SP = BP;    // cleanup locals, SP == 996
    pop(BP);    // SP == 997
}

The slice of stack, wich belongs to and is in full control of the function is called function's stack frame. E.g. myAlgo_noLPR_withAnchor's stack frame is stack[996 .. 994] (both idexes inclusive).
Frame starts at function's BP (after we've updated it inside function) and lasts until the next stack frame. So the parameters on the stack are part of the caller's stack frame (see note 8a).

Notes:
8a. Wikipedia says otherwise about parameters, but here I adhere to Intel software developer's manual, see vol. 1, section 6.2.4.1 Stack-Frame Base Pointer and Figure 6-2 in section 6.3.2 Far CALL and RET Operation. Function's parameters and stack frame are part of function's activation record (see The gen on function perilogues).
8b. positive offsets from BP point to function parameters and negative offsets point to local variables. That's pretty handy for debugging
8c. stack[BP] stores the address of the previous stack frame, stack[stack[BP]] stores pre-previous stack frame and so on. Following this chain, you can discover frames of all the functions in the programm, which didn't return yet. This is how debuggers show you call stack
8d. the first 3 instructions of myAlgo_noLPR_withAnchor, where we setup the frame (save old BP, update BP, reserve space for locals) are called function prologue


9. Calling conventions

In snippet 8.1 we've pushed parameters for myAlgo from right to left and returned result in AX. We could as well pass params left to right and return in BX. Or pass params in BX and CX and return in AX. Obviously, caller (main()) and called function must agree where and in which order all this stuff is stored.

Calling convention is a set of rules on how parameters are passed and result is returned.

In the code above we've used cdecl calling convention:

  • Parameters are passed on the stack, with the first argument at the lowest address on the stack at the time of the call (pushed last <...>). The caller is responsible for popping parameters back off the stack after the call.
  • the return value is placed in AX
  • EBP and ESP must be preserved by the callee (myAlgo_noLPR_withAnchor function in our case), such that the caller (main function) can rely on those registers not having been changed by a call.
  • All other registers (EAX, <...>) may be freely modified by the callee; if a caller wishes to preserve a value before and after the function call, it must save the value elsewhere (we do this with AX)

(Source: example "32-bit cdecl" from Stack Overflow Documentation; copyright 2016 by icktoofay and Peter Cordes ; licensed under CC BY-SA 3.0. An archive of the full Stack Overflow Documentation content can be found at archive.org, in which this example is indexed by topic ID 3261 and example ID 11196.)


10. Function calls

Now the most interesting part. Just like data, executable code is also stored in memory (completely unrelated to memory for stack) and every instruction has an address.
When not commanded otherwise, CPU executes instructions one after another, in the order they are stored in memory. But we can command CPU to "jump" to another location in memory and execute instructions from there on. In asm it can be any address, and in more high-level languages like C++ you can only jump to addresses marked by labels (there are workarounds but they are not pretty, to say the least).

Let's take this function (snippet #10.1):

int myAlgo_withCalls(int a, int b) {
    int t1 = triple(a);
    int t2 = triple(b);
    return t1 - t2;
}

And instead of calling tripple C++ way, do the following:

  1. copy tripple's code to the beginning of myAlgo body
  2. at myAlgo entry jump over tripple's code with goto
  3. when we need to execute tripple's code, save on the stack address of the code line just after tripple call, so we can return here later and continue execution (PUSH_ADDRESS macro below)
  4. jump to the address of the 1st line (tripple function) and execute it to the end (3. and 4. together are CALL macro)
  5. at the end of the tripple (after we've cleaned up locals), take return address from the top of the stack and jump there (RET macro)

Because there is no easy way to jump to particular code address in C++, we will use labels to mark places of jumps. I won't go into detail how macros below work, just believe me they do what I say they do (snippet #10.2):

// pushes the address of the code at label's location on the stack
// NOTE1: this gonna work only with 32-bit compiler (so that pointer is 32-bit and fits in int)
// NOTE2: __asm block is specific for Visual C++. In GCC use https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
#define PUSH_ADDRESS(labelName) {               \
    void* tmpPointer;                           \
    __asm{ mov [tmpPointer], offset labelName } \
    push(reinterpret_cast<int>(tmpPointer));    \
}

// why we need indirection, read https://stackoverflow.com/a/13301627/264047
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)

// generates token (not a string) we will use as label name. 
// Example: LABEL_NAME(155) will generate token `lbl_155`
#define LABEL_NAME(num) TOKENPASTE2(lbl_, num)

#define CALL_IMPL(funcLabelName, callId)    \
    PUSH_ADDRESS(LABEL_NAME(callId));       \
    goto funcLabelName;                     \
    LABEL_NAME(callId) :

// saves return address on the stack and jumps to label `funcLabelName`
#define CALL(funcLabelName) CALL_IMPL(funcLabelName, __LINE__)

// takes address at the top of stack and jump there
#define RET() {                                         \
    int tmpInt;                                         \
    pop(tmpInt);                                        \
    void* tmpPointer = reinterpret_cast<void*>(tmpInt); \
    __asm{ jmp tmpPointer }                             \
}

void myAlgo_asm() {
    goto my_algo_start;

triple_label:
    push(BP);
    BP = SP;
    SP -= 1;

    // stack[BP] == old BP, stack[BP + 1] == return address
    stack[BP - 1] = stack[BP + 2] * 3;
    AX = stack[BP - 1];

    SP = BP;     
    pop(BP);
    RET();

my_algo_start:
    push(BP);   // SP == 995
    BP = SP;    // BP == 995; stack[BP] == old BP, 
                // stack[BP + 1] == dummy return address, 
                // `a` at [BP + 2], `b` at [BP + 3]
    SP -= 2;    // SP == 993

    push(AX);
    push(stack[BP + 2]);
    CALL(triple_label);
    stack[BP - 1] = AX;
    SP -= 1;
    pop(AX);

    push(AX);
    push(stack[BP + 3]);
    CALL(triple_label);
    stack[BP - 2] = AX;
    SP -= 1;
    pop(AX);

    AX = stack[BP - 1] - stack[BP - 2];

    SP = BP; // cleanup locals, SP == 997
    pop(BP);
}

int main() {
    push(AX);
    push(22);
    push(11);
    push(7777); // dummy value, so that offsets inside function are like we've pushed return address
    myAlgo_asm();
    assert(myAlgo_withCalls(11, 22) == AX);
    SP += 1; // pop dummy "return address"
    SP += 2;
    pop(AX);
}

Notes:
10a. because return address is stored on the stack, in principle we can change it. This is how stack smashing attack works
10b. the last 3 instructions at the "end" of triple_label (cleanup locals, restore old BP, return) are called function's epilogue


11. Assembly

Now let's look at real asm for myAlgo_withCalls. To do that in Visual Studio:

  • set build platform to x86 (not x86_64)
  • build type: Debug
  • set break point somewhere inside myAlgo_withCalls
  • run, and when execution stops at break point press Ctrl + Alt + D

One difference with our asm-like C++ is that asm's stack operate on bytes instead of ints. So to reserve space for one int, SP will be decremented by 4 bytes.
Here we go (snippet #11.1, line numbers in comments are from the gist):

;   114: int myAlgo_withCalls(int a, int b) {
 push        ebp        ; create stack frame 
 mov         ebp,esp  
; return address at (ebp + 4), `a` at (ebp + 8), `b` at (ebp + 12)
 
 sub         esp,0D8h   ; reserve space for locals. Compiler can reserve more bytes then needed. 0D8h is hexadecimal == 216 decimal 
 
 push        ebx        ; cdecl requires to save all these registers
 push        esi  
 push        edi  
 
 ; fill all the space for local variables (from (ebp-0D8h) to (ebp)) with value 0CCCCCCCCh repeated 36h times (36h * 4 == 0D8h)
 ; see https://stackoverflow.com/q/3818856/264047
 ; I guess that's for ease of debugging, so that stack is filled with recognizable values
 ; 0CCCCCCCCh in binary is 110011001100...
 lea         edi,[ebp-0D8h]     
 mov         ecx,36h    
 mov         eax,0CCCCCCCCh  
 rep stos    dword ptr es:[edi]  
 
;   115:    int t1 = triple(a);
 mov         eax,dword ptr [ebp+8]   ; push parameter `a` on the stack
 push        eax  
 
 call        triple (01A13E8h)  
 add         esp,4                   ; clean up param 
 mov         dword ptr [ebp-8],eax   ; copy result from eax to `t1`
 
;   116:    int t2 = triple(b);
 mov         eax,dword ptr [ebp+0Ch] ; push `b` (0Ch == 12)
 push        eax  
 
 call        triple (01A13E8h)  
 add         esp,4  
 mov         dword ptr [ebp-14h],eax ; t2 = eax
 
 mov         eax,dword ptr [ebp-8]   ; calculate and store result in eax
 sub         eax,dword ptr [ebp-14h]  

 pop         edi  ; restore registers
 pop         esi  
 pop         ebx  
 
 add         esp,0D8h  ; check we didn't mess up esp or ebp. this is only for debug builds
 cmp         ebp,esp  
 call        __RTC_CheckEsp (01A116Dh)  
 
 mov         esp,ebp  ; destroy frame
 pop         ebp  
 ret  

And asm for tripple (snippet #11.2):

 push        ebp  
 mov         ebp,esp  
 sub         esp,0CCh  
 push        ebx  
 push        esi  
 push        edi  
 lea         edi,[ebp-0CCh]  
 mov         ecx,33h  
 mov         eax,0CCCCCCCCh  
 rep stos    dword ptr es:[edi]  
 imul        eax,dword ptr [ebp+8],3  
 mov         dword ptr [ebp-8],eax  
 mov         eax,dword ptr [ebp-8]  
 pop         edi  
 pop         esi  
 pop         ebx  
 mov         esp,ebp  
 pop         ebp  
 ret  

Hope, after reading this post, assembly doesn't look as cryptic as before :)


Here are links from the post's body and some further reading:

Android: Changing Background-Color of the Activity (Main View)

Try this:

_x000D_
_x000D_
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"


</androidx.constraintlayout.widget.ConstraintLayout>
    />
_x000D_
_x000D_
_x000D_

How the single threaded non blocking IO model works in Node.js

if you read a bit further - "Of course, on the backend, there are threads and processes for DB access and process execution. However, these are not explicitly exposed to your code, so you can’t worry about them other than by knowing that I/O interactions e.g. with the database, or with other processes will be asynchronous from the perspective of each request since the results from those threads are returned via the event loop to your code."

about - "everything runs in parallel except your code" - your code is executed synchronously, whenever you invoke an asynchronous operation such as waiting for IO, the event loop handles everything and invokes the callback. it just not something you have to think about.

in your example: there are two requests A (comes first) and B. you execute request A, your code continue to run synchronously and execute request B. the event loop handles request A, when it finishes it invokes the callback of request A with the result, same goes to request B.

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

That is because is does not exist, since it is bounded to Windows.

Use the standard functions from <stdio.h> instead, such as getc

The suggested ncurses library is good if you want to write console-based GUIs, but I don't think it is what you want.

What is the difference between a process and a thread?

Real world example for Process and Thread This will give you the basic idea about thread and process enter image description here

I borrowed the above info from Scott Langham's Answer - thanks

How to find my Subversion server version number?

To find the version of the subversion REPOSITORY you can:

  1. Look to the repository on the web and on the bottom of the page it will say something like:
    "Powered by Subversion version 1.5.2 (r32768)."
  2. From the command line: <insert curl, grep oneliner here>

If not displayed, view source of the page

<svn version="1.6.13 (r1002816)" href="http://subversion.tigris.org/"> 

Now for the subversion CLIENT:

svn --version

will suffice

Parse JSON from HttpURLConnection object

The JSON string will just be the body of the response you get back from the URL you have called. So add this code

...
BufferedReader in = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) 
    System.out.println(inputLine);
in.close();

That will allow you to see the JSON being returned to the console. The only missing piece you then have is using a JSON library to read that data and provide you with a Java representation.

Here's an example using JSON-LIB

how to use JSON.stringify and json_decode() properly

jsonText = $_REQUEST['myJSON'];

$decodedText = html_entity_decode($jsonText);

$myArray = json_decode($decodedText, true);`

What exactly is the meaning of an API?

  1. an API(Application Programming Interface) is a set of defined functions and methods for interfacing with the underlying operating system or another program or service running on the computer.

  2. It is usually used by establishing a reference to a library in your software or importing a function from a dll.

  3. It is used in one form or another in almost all software, being explicitly called in your program or implicitly called by the compiler.

Insert into ... values ( SELECT ... FROM ... )

For Microsoft SQL Server, I will recommend learning to interpret the SYNTAX provided on MSDN. With Google it's easier than ever, to look for syntax.

For this particular case, try

Google: insert site:microsoft.com

The first result will be http://msdn.microsoft.com/en-us/library/ms174335.aspx

scroll down to the example ("Using the SELECT and EXECUTE options to insert data from other tables") if you find it difficult to interpret the syntax given at the top of the page.

[ WITH <common_table_expression> [ ,...n ] ]
INSERT 
{
        [ TOP ( expression ) [ PERCENT ] ] 
        [ INTO ] 
        { <object> | rowset_function_limited 
          [ WITH ( <Table_Hint_Limited> [ ...n ] ) ]
        }
    {
        [ ( column_list ) ] 
        [ <OUTPUT Clause> ]
        { VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n     ] 
        | derived_table       <<<<------- Look here ------------------------
        | execute_statement   <<<<------- Look here ------------------------
        | <dml_table_source>  <<<<------- Look here ------------------------
        | DEFAULT VALUES 
        }
    }
}
[;]

This should be applicable for any other RDBMS available there. There is no point in remembering all the syntax for all products IMO.

Appending the same string to a list of strings in Python

Updating with more options

list1 = ['foo', 'fob', 'faz', 'funk']
addstring = 'bar'
for index, value in enumerate(list1):
    list1[index] = addstring + value #this will prepend the string
    #list1[index] = value + addstring this will append the string

Avoid using keywords as variables like 'list', renamed 'list' as 'list1' instead

Display current time in 12 hour format with AM/PM

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");

This will display the date and time

How to start a background process in Python?

Note: This answer is less current than it was when posted in 2009. Using the subprocess module shown in other answers is now recommended in the docs

(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions.)


If you want your process to start in the background you can either use system() and call it in the same way your shell script did, or you can spawn it:

import os
os.spawnl(os.P_DETACH, 'some_long_running_command')

(or, alternatively, you may try the less portable os.P_NOWAIT flag).

See the documentation here.

Phone: numeric keyboard for text input

As of mid-2015, I believe this is the best solution:

<input type="number" pattern="[0-9]*" inputmode="numeric">

This will give you the numeric keypad on both Android and iOS:

enter image description here

It also gives you the expected desktop behavior with the up/down arrow buttons and keyboard friendly up/down arrow key incrementing:

enter image description here

Try it in this code snippet:

_x000D_
_x000D_
<form>_x000D_
  <input type="number" pattern="[0-9]*" inputmode="numeric">_x000D_
  <button type="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

By combining both type="number" and pattern="[0-9]*, we get a solution that works everywhere. And, its forward compatible with the future HTML 5.1 proposed inputmode attribute.

Note: Using a pattern will trigger the browser's native form validation. You can disable this using the novalidate attribute, or you can customize the error message for a failed validation using the title attribute.


If you need to be able to enter leading zeros, commas, or letters - for example, international postal codes - check out this slight variant.


Credits and further reading:

http://www.smashingmagazine.com/2015/05/form-inputs-browser-support-issue/ http://danielfriesen.name/blog/2013/09/19/input-type-number-and-ios-numeric-keypad/

The right way of setting <a href=""> when it's a local file

The href value inside the base tag will become your reference point for all your relative paths and thus override your current directory path value otherwise - the '~' is the root of your site

    <head>
        <base href="~/" />
    </head>

php.ini & SMTP= - how do you pass username & password

After working all day on this, I finally found a solution. Here's how I send from Windows XP with WAMP.

  1. Use Google's SMTP server. You probably need an account.
  2. Download and install Fake Sendmail. I just downloaded it, unzipped it and put it in the WAMP folder.
  3. Create a test PHP file. See below.
<?php
    $message = "test message body";
    $result = mail('[email protected]', 'message subject', $message);
    echo "result: $result";
?>
  1. Update your php.ini file and your sendmail.ini file (sendmail.ini is in the sendmail folder).
  2. Check the error.log file in the sendmail folder that you just created if it doesn't work.

Reference:

How to calculate sum of a formula field in crystal Reports?

The only reason that I know of why a formula wouldn't be available to summarize on is if it didn't reference any database fields or whose value wasn't dynamic throughout sections of the report. For example, if you have a formula that returns a constant it won't be available. Or if it only references a field that is set throughout the report and returns a value based on that field, like "if {parameter}=1 then 1" would not be available either.

In general, the formula's value should not be static through the sections of the report you're summarizing over (Though the way Crystal determines this is beyond me and this doesn't seem to be a hard and fast rule)

EDIT: One other reason why a formula wouldn't be available is if you're already using a summary function in that formula. Only one level of summaries at a time!

How to initialize an array in Kotlin with values?

You can create an Int Array like this:

val numbers = IntArray(5, { 10 * (it + 1) })

5 is the Int Array size. the lambda function is the element init function. 'it' range in [0,4], plus 1 make range in [1,5]

origin function is:

 /**
 * An array of ints. When targeting the JVM, instances of this class are 
 * represented as `int[]`.
 * @constructor Creates a new array of the specified [size], with all elements 
 *  initialized to zero.
 */
 public class IntArray(size: Int) {
       /**
        * Creates a new array of the specified [size], where each element is 
        * calculated by calling the specified
        * [init] function. The [init] function returns an array element given 
        * its index.
        */
      public inline constructor(size: Int, init: (Int) -> Int)
  ...
 }

IntArray class defined in the Arrays.kt

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

Try using the passive command before using ls.

From FTP client, to check if the FTP server supports passive mode, after login, type quote PASV.

Following are connection examples to a vsftpd server with passive mode on and off

vsftpd with pasv_enable=NO:

# ftp localhost
Connected to localhost.localdomain.
220 (vsFTPd 2.3.5)
Name (localhost:john): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> quote PASV
550 Permission denied.
ftp> 

vsftpd with pasv_enable=YES:

# ftp localhost
Connected to localhost.localdomain.
220 (vsFTPd 2.3.5)
Name (localhost:john): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> quote PASV
227 Entering Passive Mode (127,0,0,1,173,104).
ftp> 

How to run Pip commands from CMD

Newer versions of Python come with py, the Python Launcher, which is always in the PATH.

Here is how to invoke pip via py:

py -m pip install <packagename>

py allows having several versions of Python on the same machine.

As an example, here is how to invoke the pip from Python 2.7:

py -2.7 -m pip install <packagename>

List files in local git repo?

git ls-tree --full-tree -r HEAD and git ls-files return all files at once. For a large project with hundreds or thousands of files, and if you are interested in a particular file/directory, you may find more convenient to explore specific directories. You can do it by obtaining the ID/SHA-1 of the directory that you want to explore and then use git cat-file -p [ID/SHA-1 of directory]. For example:

git cat-file -p 14032aabd85b43a058cfc7025dd4fa9dd325ea97
100644 blob b93a4953fff68df523aa7656497ee339d6026d64    glyphicons-halflings-regular.eot
100644 blob 94fb5490a2ed10b2c69a4a567a4fd2e4f706d841    glyphicons-halflings-regular.svg
100644 blob 1413fc609ab6f21774de0cb7e01360095584f65b    glyphicons-halflings-regular.ttf
100644 blob 9e612858f802245ddcbf59788a0db942224bab35    glyphicons-halflings-regular.woff
100644 blob 64539b54c3751a6d9adb44c8e3a45ba5a73b77f0    glyphicons-halflings-regular.woff2

In the example above, 14032aabd85b43a058cfc7025dd4fa9dd325ea97 is the ID/SHA-1 of the directory that I wanted to explore. In this case, the result was that four files within that directory were being tracked by my Git repo. If the directory had additional files, it would mean those extra files were not being tracked. You can add files using git add <file>... of course.

Visual Studio replace tab with 4 spaces?

First set in the following path Tools->Options->Text Editor->All Languages->Tabs if still didn't work modify as mentioned below Go to Edit->Advanced->Set Indentation ->Spaces

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Here's one slight alteration to the answers of a query that creates the table upon execution (i.e. you don't have to create the table first):

SELECT * INTO #Temp
FROM (
select OptionNo, OptionName from Options where OptionActive = 1
) as X

How to save image in database using C#

This is a method that uses a FileUpload control in asp.net:

byte[] buffer = new byte[fu.FileContent.Length];
Stream s = fu.FileContent;
s.Read(buffer, 0, buffer.Length);
//Then save 'buffer' to the varbinary column in your db where you want to store the image.

How to jQuery clone() and change id?

This is the simplest solution working for me.

$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

For aspnetcore-3.1, you can also use Problem() like below;

https://docs.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-3.1

 [Route("/error-local-development")]
public IActionResult ErrorLocalDevelopment(
    [FromServices] IWebHostEnvironment webHostEnvironment)
{
    if (webHostEnvironment.EnvironmentName != "Development")
    {
        throw new InvalidOperationException(
            "This shouldn't be invoked in non-development environments.");
    }

    var context = HttpContext.Features.Get<IExceptionHandlerFeature>();

    return Problem(
        detail: context.Error.StackTrace,
        title: context.Error.Message);
}

PHP Get Highest Value from Array

greatestValue=> try this its very easy

$a=array(10,20,52,105,56,89,96);
$c=0;
foreach($a as $b)
{
if($b>$c)
$c=$b;

}
echo $c;

IF EXISTS in T-SQL

Yes it stops execution so this is generally preferable to HAVING COUNT(*) > 0 which often won't.

With EXISTS if you look at the execution plan you will see that the actual number of rows coming out of table1 will not be more than 1 irrespective of number of matching records.

In some circumstances SQL Server can convert the tree for the COUNT query to the same as the one for EXISTS during the simplification phase (with a semi join and no aggregate operator in sight) an example of that is discussed in the comments here.

For more complicated sub trees than shown in the question you may occasionally find the COUNT performs better than EXISTS however. Because the semi join needs only retrieve one row from the sub tree this can encourage a plan with nested loops for that part of the tree - which may not work out optimal in practice.

C++ cast to derived class

You can't cast a base object to a derived type - it isn't of that type.

If you have a base type pointer to a derived object, then you can cast that pointer around using dynamic_cast. For instance:

DerivedType D;
BaseType B;

BaseType *B_ptr=&B
BaseType *D_ptr=&D;// get a base pointer to derived type

DerivedType *derived_ptr1=dynamic_cast<DerivedType*>(D_ptr);// works fine
DerivedType *derived_ptr2=dynamic_cast<DerivedType*>(B_ptr);// returns NULL

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

In my maven project this error occurs, after i closed my projects and reopens them. The dependencys wasn´t build correctly at that time. So for me the solution was just to update the Maven Dependencies of the projects!

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

You can also specify the range with the coord_cartesian command to set the y-axis range that you want, an like in the previous post use scales = free_x

p <- ggplot(plot, aes(x = pred, y = value)) +
     geom_point(size = 2.5) +
     theme_bw()+
     coord_cartesian(ylim = c(-20, 80))
p <- p + facet_wrap(~variable, scales = "free_x")
p

enter image description here

Can I run a 64-bit VMware image on a 32-bit machine?

If your hardware is 32-bit only, then no. If you have 64 bit hardware and a 32-bit operating system, then maybe. See Hardware and Firmware Requirements for 64-Bit Guest Operating Systems for details. It has nothing to do with one vs. multiple processors.

How to change the port of Tomcat from 8080 to 80?

On a linux server you can just use this commands to reconfigure Tomcat to listen on port 80:

sed -i 's|port="8080"|port="80"|g' /etc/tomcat?/server.xml
sed -i 's|#AUTHBIND=no|AUTHBIND=yes|g' /etc/default/tomcat?
service tomcat8 restart

How do I run msbuild from the command line using Windows SDK 7.1?

Using the "Developer Command Prompt for Visual Studio 20XX" instead of "cmd" will set the path for msbuild automatically without having to add it to your environment variables.

how do I print an unsigned char as hex in c++ using ostream?

I think TrungTN and anon's answer is okay, but MartinStettner's way of implementing the hex() function is not really simple, and too dark, considering hex << (int)mychar is already a workaround.

here is my solution to make "<<" operator easier:

#include <sstream>
#include <iomanip>

string uchar2hex(unsigned char inchar)
{
  ostringstream oss (ostringstream::out);
  oss << setw(2) << setfill('0') << hex << (int)(inchar);
  return oss.str();
}

int main()
{
  unsigned char a = 131;
  std::cout << uchar2hex(a) << std::endl;
}

It's just not worthy implementing a stream operator :-)

HashMap to return default value for non-found keys?

You can simply create a new class that inherits HashMap and add getDefault method. Here is a sample code:

public class DefaultHashMap<K,V> extends HashMap<K,V> {
    public V getDefault(K key, V defaultValue) {
        if (containsKey(key)) {
            return get(key);
        }

        return defaultValue;
    }
}

I think that you should not override get(K key) method in your implementation, because of the reasons specified by Ed Staub in his comment and because you will break the contract of Map interface (this can potentially lead to some hard-to-find bugs).

HTTP POST and GET using cURL in Linux

I think Amith Koujalgi is correct but also, in cases where the webservice responses are in JSON then it might be more useful to see the results in a clean JSON format instead of a very long string. Just add | grep }| python -mjson.tool to the end of curl commands here is two examples:

GET approach with JSON result

curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool 

POST approach with JSON result

curl -X POST  -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool

enter image description here

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

bootstrap.yml or bootstrap.properties

It's only used/needed if you're using Spring Cloud and your application's configuration is stored on a remote configuration server (e.g. Spring Cloud Config Server).

From the documentation:

A Spring Cloud application operates by creating a "bootstrap" context, which is a parent context for the main application. Out of the box it is responsible for loading configuration properties from the external sources, and also decrypting properties in the local external configuration files.

Note that the bootstrap.yml or bootstrap.properties can contain additional configuration (e.g. defaults) but generally you only need to put bootstrap config here.

Typically it contains two properties:

  • location of the configuration server (spring.cloud.config.uri)
  • name of the application (spring.application.name)

Upon startup, Spring Cloud makes an HTTP call to the config server with the name of the application and retrieves back that application's configuration.

application.yml or application.properties

Contains standard application configuration - typically default configuration since any configuration retrieved during the bootstrap process will override configuration defined here.

How to select clear table contents without destroying the table?

How about:

ACell.ListObject.DataBodyRange.Rows.Delete

That will keep your table structure and headings, but clear all the data and rows.

EDIT: I'm going to just modify a section of my answer from your previous post, as it does mostly what you want. This leaves just one row:

With loSource
   .Range.AutoFilter
   .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
   .DataBodyRange.Rows(1).Specialcells(xlCellTypeConstants).ClearContents
End With

If you want to leave all the rows intact with their formulas and whatnot, just do:

With loSource
   .Range.AutoFilter
   .DataBodyRange.Specialcells(xlCellTypeConstants).ClearContents
End With

Which is close to what @Readify suggested, except it won't clear formulas.

How do I check which version of NumPy I'm using?

>> import numpy
>> print numpy.__version__

github markdown colspan

Compromise minimum solution:

| One    | Two | Three | Four    | Five  | Six 
| -
| Span <td colspan=3>triple  <td colspan=2>double

So you can omit closing </td> for speed, ?r can leave for consistency.

Result from http://markdown-here.com/livedemo.html : markdown table with colspan

Works in Jupyter Markdown.

Update:

As of 2019 year all pipes in the second line are compulsory in Jupyter Markdown.

| One    | Two | Three | Four    | Five  | Six
|-|-|-|-|-|-
| Span <td colspan=3>triple  <td colspan=2>double

minimally:

One    | Two | Three | Four    | Five  | Six
-|||||-
Span <td colspan=3>triple  <td colspan=2>double

How to get the list of properties of a class?

public List<string> GetPropertiesNameOfClass(object pObject)
{
    List<string> propertyList = new List<string>();
    if (pObject != null)
    {
        foreach (var prop in pObject.GetType().GetProperties())
        {
            propertyList.Add(prop.Name);
        }
    }
    return propertyList;
}

This function is for getting list of Class Properties.

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

After doing some research found the solution. Run the below command.

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

For Arch Linux add this line to /etc/sysctl.d/99-sysctl.conf:

fs.inotify.max_user_watches=524288

How do I disable a jquery-ui draggable?

In the case of a dialog, it has a property called draggable, set it to false.

$("#yourDialog").dialog({
    draggable: false
});

Eventhough the question is old, i tried the proposed solution and it did not work for the dialog. Hope this may help others like me.

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

There is a simple trick for this. After you constructed the frame with all it buttons do this:

frame.getRootPane().setDefaultButton(submitButton);

For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked.


And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:

@Override
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode()==KeyEvent.VK_ENTER){
        System.out.println("Hello");

        JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
    }

}

UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:

SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);

Getting the base url of the website and globally passing it to twig in Symfony 2

Why do you need to get this root url ? Can't you generate directly absolute URL's ?

{{ url('_demo_hello', { 'name': 'Thomas' }) }}

This Twig code will generate the full http:// url to the _demo_hello route.

In fact, getting the base url of the website is only getting the full url of the homepage route :

{{ url('homepage') }}

(homepage, or whatever you call it in your routing file).

How to make Bootstrap Panel body with fixed height

You can use max-height in an inline style attribute, as below:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

To use scrolling with content that overflows a given max-height, you can alternatively try the following:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>

To restrict the height to a fixed value you can use something like this.

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

Specify the same value for both max-height and min-height (either in pixels or in points – as long as it’s consistent).

You can also put the same styles in css class in a stylesheet (or a style tag as shown below) and then include the same in your tag. See below:

Style Code:

.fixed-panel {
  min-height: 10;
  max-height: 10;
  overflow-y: scroll;
}

Apply Style :

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>

Hope this helps with your need.

How can I show current location on a Google Map on Android Marshmallow?

For using FusedLocationProviderClient with Google Play Services 11 and higher:

see here: How to get current Location in GoogleMap using FusedLocationProviderClient

For using (now deprecated) FusedLocationProviderApi:

If your project uses Google Play Services 10 or lower, using the FusedLocationProviderApi is the optimal choice.

The FusedLocationProviderApi offers less battery drain than the old open source LocationManager API. Also, if you're already using Google Play Services for Google Maps, there's no reason not to use it.

Here is a full Activity class that places a Marker at the current location, and also moves the camera to the current position.

It also checks for the Location permission at runtime for Android 6 and later (Marshmallow, Nougat, Oreo). In order to properly handle the Location permission runtime check that is necessary on Android M/Android 6 and later, you need to ensure that the user has granted your app the Location permission before calling mGoogleMap.setMyLocationEnabled(true) and also before requesting location updates.

public class MapLocationActivity extends AppCompatActivity
        implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportActionBar().setTitle("Map Location Activity");

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {}

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {}

    @Override
    public void onLocationChanged(Location location)
    {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

        //move map camera
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapLocationActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context=".MapLocationActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

Result:

Show permission explanation if needed using an AlertDialog (this happens if the user denies a permission request, or grants the permission and then later revokes it in the settings):

enter image description here

Prompt the user for Location permission by calling ActivityCompat.requestPermissions():

enter image description here

Move camera to current location and place Marker when the Location permission is granted:

enter image description here

How do I clone a Django model instance object and save it to the database?

There is a package that can do this which creates a UI within the django admin site: https://github.com/RealGeeks/django-modelclone

pip install django-modelclone

Add "modelclone" to INSTALLED_APPS and import it within admin.py.

Then, whenever you want to make a model clonable, you just replace "admin.ModelAdmin" in the given admin model class "modelclone.ClonableModelAdmin". This results in a "Duplicate" button appearing within the instance details page for that given model.

How to resolve the "ADB server didn't ACK" error?

On my end, I used Resource Monitor to see which application was still listening to port 5037 after all the Eclipse and adb restart were unsuccessful for me.

Start > All Programs > Accessories > System Tools >
Resource Monitor > Network > Listening Ports

This eventually showed that java.exe was listening to port 5037, hence, preventing adb from doing so. I killed java.exe, immediately start adb (with adb start-server) and received a confirmation that adb was able to start:

android-sdks\platform-tools>adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *

Syntax for a for loop in ruby

If you don't need to access your array, (just a simple for loop) you can use upto or each :

Upto:

1.9.3p392 :030 > 2.upto(4) {|i| puts i}
2
3
4
 => 2 

Each:

1.9.3p392 :031 > (2..4).each {|i| puts i}
2
3
4
 => 2..4 

SQL Server: how to select records with specific date from datetime column

SELECT *
FROM LogRequests
WHERE cast(dateX as date) between '2014-05-09' and '2014-05-10';

This will select all the data between the 2 dates

Is it possible to append Series to rows of DataFrame without making a list first?

Try using this command. See the example given below:

Before image

df.loc[len(df)] = ['Product 9',99,9.99,8.88,1.11]

df

After Image

Is it possible to break a long line to multiple lines in Python?

There is more than one way to do it.

1). A long statement:

>>> def print_something():
         print 'This is a really long line,', \
               'but we can make it across multiple lines.'

2). Using parenthesis:

>>> def print_something():
        print ('Wow, this also works?',
               'I never knew!')

3). Using \ again:

>>> x = 10
>>> if x == 10 or x > 0 or \
       x < 100:
       print 'True'

Quoting PEP8:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.

Visually managing MongoDB documents and collections

MongoVue is the best I found till now, it has great features like database or collection copy and text mode viewing for records which is extremely useful

Yarn install command error No such file or directory: 'install'

The following steps worked on Pop!_OS 20.10 & ubuntu 20.04

  1. sudo apt remove cmdtest
  2. sudo apt remove yarn
  3. curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
  4. echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
  5. sudo apt-get update
  6. sudo apt-get install yarn -y
  7. yarn install

Specifying width and height as percentages without skewing photo proportions in HTML

Note: it is invalid to provide percentages directly as <img> width or height attribute unless you're using HTML 4.01 (see current spec, obsolete spec and this answer for more details). That being said, browsers will often tolerate such behaviour to support backwards-compatibility.

Those percentage widths in your 2nd example are actually applying to the container your <img> is in, and not the image's actual size. Say you have the following markup:

<div style="width: 1000px; height: 600px;">
    <img src="#" width="50%" height="50%">
</div>

Your resulting image will be 500px wide and 300px tall.

jQuery Resize

If you're trying to reduce an image to 50% of its width, you can do it with a snippet of jQuery:

$( "img" ).each( function() {
    var $img = $( this );
    $img.width( $img.width() * .5 );
});

Just make sure you take off any height/width = 50% attributes first.

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

Open Source Javascript PDF viewer

There are some guys at Mozilla working on implementing a PDF reader using HTML5 and JavaScript. It is called pdf.js and one of the developers just made an interesting blog post about the project.

Using BeautifulSoup to extract text without tags

I think you could solve this with .strip() in gazpacho:

Input:

html = """\
<p>
  <strong class="offender">YOB:</strong> 1987<br />
  <strong class="offender">RACE:</strong> WHITE<br />
  <strong class="offender">GENDER:</strong> FEMALE<br />
  <strong class="offender">HEIGHT:</strong> 5'05''<br />
  <strong class="offender">WEIGHT:</strong> 118<br />
  <strong class="offender">EYE COLOR:</strong> GREEN<br />
  <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""

Code:

soup = Soup(html)
text = soup.find("p").strip(whitespace=False) # to keep \n characters intact
lines = [
    line.strip()
    for line in text.split("\n")
    if line != ""
]
data = dict([line.split(": ") for line in lines])

Output:

print(data)
# {'YOB': '1987',
#  'RACE': 'WHITE',
#  'GENDER': 'FEMALE',
#  'HEIGHT': "5'05''",
#  'WEIGHT': '118',
#  'EYE COLOR': 'GREEN',
#  'HAIR COLOR': 'BROWN'}

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

After much pain, googling and hair pulling, I ended up uninstalling MVC 4 using nuget, deleting all references to MVC, razor and infrastructure from the web config, deleting the dlls from the bin folder - then using nuget to reinstall everything. It took less time then trying to figure out why the dlls did not match.

Redirect stderr and stdout in Bash

do_something 2>&1 | tee -a some_file

This is going to redirect stderr to stdout and stdout to some_file and print it to stdout.

Is try-catch like error handling possible in ASP Classic?

1) Add On Error Resume Next at top of the page

2) Add following code at bottom of the page

If Err.Number <> 0 Then

  Response.Write (Err.Description)   

  Response.End 

End If

On Error GoTo 0

How to redirect the output of the time command to a file in Linux?

If you are using csh you can use:

/usr/bin/time --output=outfile -p $SHELL  -c 'your command'

For example:

/usr/bin/time --output=outtime.txt -p csh -c 'cat file'

Getting attributes of Enum's value

Bryan Rowe and AdamCrawford thanks for your answers!

But if somebody need method for get Discription (not extension) you can use it:

string GetEnumDiscription(Enum EnumValue)
        {
            var type = EnumValue.GetType();
            var memInfo = type.GetMember(EnumValue.ToString());
            var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? ((DescriptionAttribute)attributes[0]).Description : null;
        }

How to get the current time in Google spreadsheet using script editor?

Use the Date object provided by javascript. It's not unique or special to Google's scripting environment.

How to count how many values per level in a given factor?

Using plyr package:

library(plyr)

count(mydf$V1)

It will return you a frequency of each value.

Non greedy (reluctant) regex matching in sed?

Another sed version:

sed 's|/[:alnum:].*||' file.txt

It matches / followed by an alphanumeric character (so not another forward slash) as well as the rest of characters till the end of the line. Afterwards it replaces it with nothing (ie. deletes it.)

How to run a javascript function during a mouseover on a div

Here's a jQuery solution.

<script type="text/javascript" src="/path/to/your/copy/of/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#sub1").mouseover(function() {
        $("#welcome").toggle();
    });
});
</script>

Using this markup:

<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Welcome message</div>

You didn't really specify if (or when) you wanted to hide the welcome message, but this would toggle hiding or showing each time you moused over the text.

Stop floating divs from wrapping

I had a somewhat similar problem where a bounded area consisted of an image in a float:left block and a non-float text block. The area has a fluid width. The text would, by design, wrap up along the right side of the image. The trouble was, the text began with an <h4> tag, the first word of which is the tiny word "From." As I resized the window to a smaller width, the non-floated text would, for a certain range of widths, leave only the word "From" at the top of the wrap area, the rest of the text having been squeezed below the float block. My solution was to make the first word of the tag bigger, by replacing the space that followed it with this code, <span style="opacity:0;">x</span> . The effect was to make the first word, instead of "From", "FromxNextWord", where the "x", being invisible, looked like a space. Now my first word was big enough not to be abandoned by the rest of the text block.

Showing Difference between two datetime values in hours

In the sample, we are creating two datetime objects, one with current time and another one with 75 seconds added to the current time. Then we will call the method .Subtract() on the second DateTime object. This will return a TimeSpan object. Once we get the TimeSpan object, we can use the properties of TimeSpan to get the actual Hours, Minutes and Seconds.

DateTime startTime = DateTime.Now;

 DateTime endTime = DateTime.Now.AddSeconds( 75 );

 TimeSpan span = endTime.Subtract ( startTime );
 Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
 Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
 Console.WriteLine( "Time Difference (hours): " + span.Hours );
 Console.WriteLine( "Time Difference (days): " + span.Days );

Result:

Time Difference (seconds): 15
Time Difference (minutes): 1
Time Difference (hours): 0
Time Difference (days): 0

How can I mock an ES6 module import using Jest?

Adding more to Andreas' answer. I had the same problem with ES6 code, but I did not want to mutate the imports. That looked hacky. So I did this:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
  });
});

And added file dependency.js in the " __ mocks __" folder parallel to file dependency.js. This worked for me. Also, this gave me the option to return suitable data from the mock implementation. Make sure you give the correct path to the module you want to mock.

The ResourceConfig instance does not contain any root resource classes

Another possible cause of this error is that you have forgotten to add the libraries that are already in the /WEBINF/lib folder to the build path (e.g. when importing a .war-file and not checking the libraries when asked in the wizard). Just happened to me.

How can I ping a server port with PHP?

function ping($ip){
    $output = shell_exec("ping $ip");
    var_dump($output);
}
ping('127.0.0.1');

UPDATE: If you pass an hardcoded IP (like in this example and most of the real-case scenarios), this function can be enough.

But since some users seem to be very concerned about safety, please remind to never pass user generated inputs to the shell_exec function: If the IP comes from an untrusted source, at least check it with a filter before using it.

Google OAuth 2 authorization - Error: redirect_uri_mismatch

What you need to do is go back to your Developer Console and go to APIs & Auth > Consent Screen and fill that out. Specifically, the product name.

Pandas dataframe get first row of each group

>>> df.groupby('id').first()
     value
id        
1    first
2    first
3    first
4   second
5    first
6    first
7   fourth

If you need id as column:

>>> df.groupby('id').first().reset_index()
   id   value
0   1   first
1   2   first
2   3   first
3   4  second
4   5   first
5   6   first
6   7  fourth

To get n first records, you can use head():

>>> df.groupby('id').head(2).reset_index(drop=True)
    id   value
0    1   first
1    1  second
2    2   first
3    2  second
4    3   first
5    3   third
6    4  second
7    4   fifth
8    5   first
9    6   first
10   6  second
11   7  fourth
12   7   fifth

spring autowiring with unique beans: Spring expected single matching bean but found 2

The issue is because you have a bean of type SuggestionService created through @Component annotation and also through the XML config . As explained by JB Nizet, this will lead to the creation of a bean with name 'suggestionService' created via @Component and another with name 'SuggestionService' created through XML .

When you refer SuggestionService by @Autowired, in your controller, Spring autowires "by type" by default and find two beans of type 'SuggestionService'

You could do the following

  1. Remove @Component from your Service and depend on mapping via XML - Easiest

  2. Remove SuggestionService from XML and autowire the dependencies - use util:map to inject the indexSearchers map.

  3. Use @Resource instead of @Autowired to pick the bean by its name .

     @Resource(name="suggestionService")
     private SuggestionService service;
    

or

    @Resource(name="SuggestionService")
    private SuggestionService service;

both should work.The third is a dirty fix and it's best to resolve the bean conflict through other ways.

Php artisan make:auth command is not defined

In the Laravel 6 application the make:auth command no longer exists.

Laravel UI is a new first-party package that extracts the UI portion of a Laravel project into a separate laravel/ui package. The separate package enables the Laravel team to iterate on the UI package separately from the main Laravel codebase.

You can install the laravel/ui package via composer:

composer require laravel/ui

The ui:auth Command

Besides the new ui command, the laravel/ui package comes with another command for generating the auth scaffolding:

php artisan ui:auth

If you run the ui:auth command, it will generate the auth routes, a HomeController, auth views, and a app.blade.php layout file.


If you want to generate the views alone, type the following command instead:

php artisan ui:auth --views

If you want to generate the auth scaffolding at the same time:

php artisan ui vue --auth
php artisan ui react --auth

php artisan ui vue --auth command will create all of the views you need for authentication and place them in the resources/views/auth directory

The ui command will also create a resources/views/layouts directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.

More detail follow. laravel-news & documentation

Simply you've to follow this two-step.

composer require laravel/ui
php artisan ui:auth

Reset ID autoincrement ? phpmyadmin

I agree with rpd, this is the answer and can be done on a regular basis to clean up your id column that is getting bigger with only a few hundred rows of data, but maybe an id of 34444543!, as the data is deleted out regularly but id is incremented automatically.

ALTER TABLE users DROP id

The above sql can be run via sql query or as php. This will delete the id column.

Then re add it again, via the code below:

ALTER TABLE  `users` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST

Place this in a piece of code that may get run maybe in an admin panel, so when anyone enters that page it will run this script that auto cleans your database, and tidys it.

How can I represent a range in Java?

For a range of Comparable I use the following :

public class Range<T extends Comparable<T>> {

    /**
     * Include start, end in {@link Range}
     */
    public enum Inclusive {START,END,BOTH,NONE }

    /**
     * {@link Range} start and end values
     */
    private T start, end;
    private Inclusive inclusive;

    /**
     * Create a range with {@link Inclusive#START}
     * @param start
     *<br/> Not null safe
     * @param end
     *<br/> Not null safe
     */
    public Range(T start, T end) {  this(start, end, null); }

    /**
     * @param start
     *<br/> Not null safe
     * @param end
     *<br/> Not null safe
     *@param inclusive
     *<br/>If null {@link Inclusive#START} used
     */
    public Range(T start, T end, Inclusive inclusive) {

        if((start == null) || (end == null)) {
            throw new NullPointerException("Invalid null start / end value");
        }
        setInclusive(inclusive);

        if( isBigger(start, end) ) {
            this.start = end;   this.end   = start;
        }else {
            this.start = start;  this.end   = end;
        }
    }

    /**
     * Convenience method
     */
    public boolean isBigger(T t1, T t2) { return t1.compareTo(t2) > 0; }

    /**
     * Convenience method
     */
    public boolean isSmaller(T t1, T t2) { return t1.compareTo(t2) < 0; }

    /**
     * Check if this {@link Range} contains t
     *@param t
     *<br/>Not null safe
     *@return
     *false for any value of t, if this.start equals this.end
     */
    public boolean contains(T t) { return contains(t, inclusive); }

    /**
     * Check if this {@link Range} contains t
     *@param t
     *<br/>Not null safe
     *@param inclusive
     *<br/>If null {@link Range#inclusive} used
     *@return
     *false for any value of t, if this.start equals this.end
     */
    public boolean contains(T t, Inclusive inclusive) {

        if(t == null) {
            throw new NullPointerException("Invalid null value");
        }

        inclusive = (inclusive == null) ? this.inclusive : inclusive;

        switch (inclusive) {
            case NONE:
                return ( isBigger(t, start) && isSmaller(t, end) );
            case BOTH:
                return ( ! isBigger(start, t)  && ! isBigger(t, end) ) ;
            case START: default:
                return ( ! isBigger(start, t)  &&  isBigger(end, t) ) ;
            case END:
                return ( isBigger(t, start)  &&  ! isBigger(t, end) ) ;
        }
    }

    /**
     * Check if this {@link Range} contains other range
     * @return
     * false for any value of range, if this.start equals this.end
     */
    public boolean contains(Range<T> range) {
        return contains(range.start) && contains(range.end);
    }

    /**
     * Check if this {@link Range} intersects with other range
     * @return
     * false for any value of range, if this.start equals this.end
     */
    public boolean intersects(Range<T> range) {
        return contains(range.start) || contains(range.end);
    }

    /**
    * Get {@link #start}
    */
    public T getStart() { return start; }

    /**
    * Set {@link #start}
    * <br/>Not null safe
    * <br/>If start > end they are switched
    */
    public Range<T> setStart(T start) {

        if(start.compareTo(end)>0) {
            this.start = end;
            this.end  = start;
        }else {
            this.start = start;
        }
        return this;
    }

    /**
    * Get {@link #end}
    */
    public T getEnd() {  return end;  }

    /**
    * Set {@link #end}
    * <br/>Not null safe
    *  <br/>If start > end they are switched
    */
    public  Range<T> setEnd(T end) {

        if(start.compareTo(end)>0) {
            this.end  = start;
            this.start = end;
        }else {
            this.end = end;
        }
        return this;
    }

    /**
    * Get {@link #inclusive}
    */
    public Inclusive getInclusive() { return inclusive; }

    /**
    * Set {@link #inclusive}
    * @param inclusive
    *<br/>If null {@link Inclusive#START} used
    */
    public  Range<T> setInclusive(Inclusive inclusive) {

        this.inclusive = (inclusive == null) ? Inclusive.START : inclusive;
        return this;
    }
}

(This is a somewhat shorted version. The full code is available here )

Load text file as strings using numpy.loadtxt()

Use genfromtxt instead. It's a much more general method than loadtxt:

import numpy as np
print np.genfromtxt('col.txt',dtype='str')

Using the file col.txt:

foo bar
cat dog
man wine

This gives:

[['foo' 'bar']
 ['cat' 'dog']
 ['man' 'wine']]

If you expect that each row has the same number of columns, read the first row and set the attribute filling_values to fix any missing rows.

Fixed size div?

<div id="normal>text..</div>
<div id="small1" class="smallDiv"></div>
<div id="small2" class="smallDiv"></div>
<div id="small3" class="smallDiv"></div>

css:

.smallDiv { height: 150px; width: 150px; }

Changing datagridview cell color dynamically

Considere use DataBindingComplete event for update the style. The next code change the style of the cell:

    private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
    }

powershell - list local users and their groups

Update as an alternative to the excellent answer from 2010:

You can now use the Get-LocalGroupMember, Get-LocalGroup, Get-LocalUser etc. to get and map users and groups

Example:

PS C:\WINDOWS\system32> Get-LocalGroupMember -name users

ObjectClass Name                             PrincipalSource 
----------- ----                             --------------- 
User        DESKTOP-R05QDNL\someUser1        Local           
User        DESKTOP-R05QDNL\someUser2        MicrosoftAccount
Group       NT AUTHORITY\INTERACTIVE         Unknown  

You could combine that with Get-LocalUser. Alias glu can also be used instead. Aliases exists for the majority of the new cmndlets.

In case some are wondering (I know you didn't ask about this) Adding users could be for example done like so:

$description = "Netshare user"
$userName = "Test User"
$user = "test.user"
$pwd = "pwd123"

New-LocalUser $user -Password (ConvertTo-SecureString $pwd -AsPlainText -Force) -FullName $userName -Description $description

How to find length of digits in an integer?

For posterity, no doubt by far the slowest solution to this problem:

def num_digits(num, number_of_calls=1):
    "Returns the number of digits of an integer num."
    if num == 0 or num == -1:
        return 1 if number_of_calls == 1 else 0
    else:
        return 1 + num_digits(num/10, number_of_calls+1)

"Application tried to present modally an active controller"?

In my case, I was presenting the rootViewController of an UINavigationController when I was supposed to present the UINavigationController itself.

How to check 'undefined' value in jQuery

If you have names of the element and not id we can achieve the undefined check on all text elements (for example) as below and fill them with a default value say 0.0:

var aFieldsCannotBeNull=['ast_chkacc_bwr','ast_savacc_bwr'];
 jQuery.each(aFieldsCannotBeNull,function(nShowIndex,sShowKey) {
   var $_oField = jQuery("input[name='"+sShowKey+"']");
   if($_oField.val().trim().length === 0){
       $_oField.val('0.0')
    }
  })

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

The JWT aud (Audience) Claim

According to RFC 7519:

The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.

The Audience (aud) claim as defined by the spec is generic, and is application specific. The intended use is to identify intended recipients of the token. What a recipient means is application specific. An audience value is either a list of strings, or it can be a single string if there is only one aud claim. The creator of the token does not enforce that aud is validated correctly, the responsibility is the recipient's to determine whether the token should be used.

Whatever the value is, when a recipient is validating the JWT and it wishes to validate that the token was intended to be used for its purposes, it MUST determine what value in aud identifies itself, and the token should only validate if the recipient's declared ID is present in the aud claim. It does not matter if this is a URL or some other application specific string. For example, if my system decides to identify itself in aud with the string: api3.app.com, then it should only accept the JWT if the aud claim contains api3.app.com in its list of audience values.

Of course, recipients may choose to disregard aud, so this is only useful if a recipient would like positive validation that the token was created for it specifically.

My interpretation based on the specification is that the aud claim is useful to create purpose-built JWTs that are only valid for certain purposes. For one system, this may mean you would like a token to be valid for some features but not for others. You could issue tokens that are restricted to only a certain "audience", while still using the same keys and validation algorithm.

Since in the typical case a JWT is generated by a trusted service, and used by other trusted systems (systems which do not want to use invalid tokens), these systems simply need to coordinate the values they will be using.

Of course, aud is completely optional and can be ignored if your use case doesn't warrant it. If you don't want to restrict tokens to being used by specific audiences, or none of your systems actually will validate the aud token, then it is useless.

Example: Access vs. Refresh Tokens

One contrived (yet simple) example I can think of is perhaps we want to use JWTs for access and refresh tokens without having to implement separate encryption keys and algorithms, but simply want to ensure that access tokens will not validate as refresh tokens, or vice-versa.

By using aud, we can specify a claim of refresh for refresh tokens and a claim of access for access tokens upon creating these tokens. When a request is made to get a new access token from a refresh token, we need to validate that the refresh token was a genuine refresh token. The aud validation as described above will tell us whether the token was actually a valid refresh token by looking specifically for a claim of refresh in aud.

OAuth Client ID vs. JWT aud Claim

The OAuth Client ID is completely unrelated, and has no direct correlation to JWT aud claims. From the perspective of OAuth, the tokens are opaque objects.

The application which accepts these tokens is responsible for parsing and validating the meaning of these tokens. I don't see much value in specifying OAuth Client ID within a JWT aud claim.

How do I display images from Google Drive on a website?

List View

<iframe src="https://drive.google.com/embeddedfolderview?id=YOURID#list" width="700" height="500" frameborder="0"></iframe>

Grid View

<iframe src="https://drive.google.com/embeddedfolderview?id=YOURID#grid" width="700" height="500" frameborder="0"></iframe>

Read More at: https://thomas.vanhoutte.be/miniblog/embed-add-google-drive-folder-file-website/

Format a datetime into a string with milliseconds

I assume you mean you're looking for something that is faster than datetime.datetime.strftime(), and are essentially stripping the non-alpha characters from a utc timestamp.

You're approach is marginally faster, and I think you can speed things up even more by slicing the string:

>>> import timeit
>>> t=timeit.Timer('datetime.utcnow().strftime("%Y%m%d%H%M%S%f")','''
... from datetime import datetime''')
>>> t.timeit(number=10000000)
116.15451288223267

>>> def replaceutc(s):
...     return s\
...         .replace('-','') \
...         .replace(':','') \
...         .replace('.','') \
...         .replace(' ','') \
...         .strip()
... 
>>> t=timeit.Timer('replaceutc(str(datetime.datetime.utcnow()))','''
... from __main__ import replaceutc
... import datetime''')
>>> t.timeit(number=10000000)
77.96774983406067

>>> def sliceutc(s):
...     return s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
... 
>>> t=timeit.Timer('sliceutc(str(datetime.utcnow()))','''
... from __main__ import sliceutc
... from datetime import datetime''')
>>> t.timeit(number=10000000)
62.378515005111694

What is the difference between . (dot) and $ (dollar sign)?

... or you could avoid the . and $ constructions by using pipelining:

third xs = xs |> tail |> tail |> head

That's after you've added in the helper function:

(|>) x y = y x

Error: fix the version conflict (google-services plugin)

Important Update

Both Firebase & Play-service dependencies are having independent versions unlike past. If you have version conflicts then you can update your com.google.gms:google-services. and start defining independent version.

Step(1): Update com.google.gms:google-services

Open project level build.gradle and update com.google.gms:google-services to version 4.1.0 MUST CHECK newer if available.

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
        classpath 'com.google.gms:google-services:4.1.0' //< update this 
    }
}

Step(2): Update Firebase dependencies Latest Versions

Firebase dependency versions can be individual.

com.google.firebase:firebase-core:16.0.3    //Analytics, check latest too
com.google.firebase:firebase-database:16.0.2    //Realtime Database, check latest too

Step(3): Update Play Services dependencies Latest Versions

Play services versions also can have individual versions.

com.google.android.gms:play-services-ads:17.1.2 //Ads, check latest too
com.google.android.gms:play-services-analytics:16.0.6   //Analytics, check latest too

Still having issue? You can check which dependency is making conflict by reading this answer.

What is the meaning of @_ in Perl?

@ is used for an array.

In a subroutine or when you call a function in Perl, you may pass the parameter list. In that case, @_ is can be used to pass the parameter list to the function:

sub Average{

    # Get total number of arguments passed.
    $n = scalar(@_);
    $sum = 0;

    foreach $item (@_){

        # foreach is like for loop... It will access every
        # array element by an iterator
        $sum += $item;
    }

    $average = $sum / $n;

    print "Average for the given numbers: $average\n";
}

Function call

Average(10, 20, 30);

If you observe the above code, see the foreach $item(@_) line... Here it passes the input parameter.

How can I change the Y-axis figures into percentages in a barplot?

ggplot2 and scales packages can do that:

y <- c(12, 20)/100
x <- c(1, 2)

library(ggplot2)
library(scales)
myplot <- qplot(as.factor(x), y, geom="bar")
myplot + scale_y_continuous(labels=percent)

It seems like the stat() option has been taken off, causing the error message. Try this:

library(scales)

myplot <- ggplot(mtcars, aes(factor(cyl))) + 
          geom_bar(aes(y = (..count..)/sum(..count..))) + 
          scale_y_continuous(labels=percent)

myplot

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

Actually, as I know, you can't do some actions exactly when resize is off, simply because you don't know future user's actions. But you can assume the time passed between two resize events, so if you wait a little more than this time and no resize is made, you can call your function.
Idea is that we use setTimeout and it's id in order to save or delete it. For example we know that time between two resize events is 500ms, therefore we will wait 750ms.

_x000D_
_x000D_
var a;_x000D_
$(window).resize(function(){_x000D_
  clearTimeout(a);_x000D_
  a = setTimeout(function(){_x000D_
    // call your function_x000D_
  },750);_x000D_
});
_x000D_
_x000D_
_x000D_

Conversion from Long to Double in Java

I think it is good for you.

BigDecimal.valueOf([LONG_VALUE]).doubleValue()

How about this code? :D

How can I scan barcodes on iOS?

If you are developing for iOS >10.2 with Swift 4 then you can try my solution. I mixed up this and this tutorial and came up with a ViewController which scans a QR Code and print() it out. I also have a Switch in my UI to toggle the camera light, might be helpful as well. For now I only tested it on a iPhone SE, please let me know if it doesn't work on newer iPhones.

Here you go:

import UIKit
import AVFoundation

class QRCodeScanner: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

    let captureSession: AVCaptureSession = AVCaptureSession()
    var videoPreviewLayer: AVCaptureVideoPreviewLayer?
    let qrCodeFrameView: UIView = UIView()
    var captureDevice: AVCaptureDevice?

    override func viewDidLoad() {
        // Get the back-facing camera for capturing videos
        let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInDualCamera], mediaType: AVMediaType.video, position: .back)

        captureDevice = deviceDiscoverySession.devices.first
        if captureDevice == nil {
            print("Failed to get the camera device")
            return
        }

        do {
            // Get an instance of the AVCaptureDeviceInput class using the previous device object.
            let input = try AVCaptureDeviceInput(device: captureDevice!)

            // Set the input device on the capture session.
            captureSession.addInput(input)

            // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
            let captureMetadataOutput = AVCaptureMetadataOutput()
            captureSession.addOutput(captureMetadataOutput)

            // Set delegate and use the default dispatch queue to execute the call back
            captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
            captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]

            // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.

            videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)

            if let videoPreviewLayer = videoPreviewLayer {
                videoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
                videoPreviewLayer.frame = view.layer.bounds
                view.layer.addSublayer(videoPreviewLayer)

                // Start video capture.
                captureSession.startRunning()

                if let hasFlash = captureDevice?.hasFlash, let hasTorch = captureDevice?.hasTorch {
                    if hasFlash && hasTorch {
                        view.bringSubview(toFront: bottomBar)
                        try captureDevice?.lockForConfiguration()
                    }
                }
            }

            // QR Code Overlay
            qrCodeFrameView.layer.borderColor = UIColor.green.cgColor
            qrCodeFrameView.layer.borderWidth = 2
            view.addSubview(qrCodeFrameView)
            view.bringSubview(toFront: qrCodeFrameView)

        } catch {
            // If any error occurs, simply print it out and don't continue any more.
            print("Error: \(error)")
            return
        }
    }

    // MARK: Buttons and Switch

    @IBAction func switchFlashChanged(_ sender: UISwitch) {
        do {
            if sender.isOn {
                captureDevice?.torchMode = .on
            } else {
                captureDevice?.torchMode = .off
            }
        }
    }

    // MARK: AVCaptureMetadataOutputObjectsDelegate

    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {

        // Check if the metadataObjects array is not nil and it contains at least one object.
        if metadataObjects.count == 0 {
            qrCodeFrameView.frame = CGRect.zero
            return
        }

        // Get the metadata object.
        let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject

        if metadataObj.type == AVMetadataObject.ObjectType.qr {
            // If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds
            let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
            qrCodeFrameView.frame = barCodeObject!.bounds

            print("QR Code: \(metadataObj.stringValue)")
        }
    }
}

What are access specifiers? Should I inherit with private, protected or public?

what are Access Specifiers?

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:

Public - The members declared as Public are accessible from outside the Class through an object of the class.

Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.

Private - These members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

int main()
{
    MyClass obj;
    obj.a = 10;     //Allowed
    obj.b = 20;     //Not Allowed, gives compiler error
    obj.c = 30;     //Not Allowed, gives compiler error
}

Inheritance and Access Specifiers

Inheritance in C++ can be one of the following types:

  • Private Inheritance
  • Public Inheritance
  • Protected inheritance

Here are the member access rules with respect to each of these:

First and most important rule Private members of a class are never accessible from anywhere except the members of the same class.

Public Inheritance:

All Public members of the Base Class become Public Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.

Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:public Base
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Allowed
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Private Inheritance:

All Public members of the Base Class become Private Members of the Derived class &
All Protected members of the Base Class become Private Members of the Derived Class.

An code Example:

Class Base
{
    public:
      int a;
    protected:
      int b;
    private:
      int c;
};

class Derived:private Base   //Not mentioning private is OK because for classes it  defaults to private 
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Not Allowed, Compiler Error, a is private member of Derived now
        b = 20;  //Not Allowed, Compiler Error, b is private member of Derived now
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Protected Inheritance:

All Public members of the Base Class become Protected Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

A Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:protected Base  
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
        b = 20;  //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error
}

Remember the same access rules apply to the classes and members down the inheritance hierarchy.


Important points to note:

- Access Specification is per-Class not per-Object

Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.

- A Derived class can only access members of its own Base class

Consider the following code example:

class Myclass
{ 
    protected: 
       int x; 
}; 

class derived : public Myclass
{
    public: 
        void f( Myclass& obj ) 
        { 
            obj.x = 5; 
        } 
};

int main()
{
    return 0;
}

It gives an compilation error:

prog.cpp:4: error: ‘int Myclass::x’ is protected

Because the derived class can only access members of its own Base Class. Note that the object obj being passed here is no way related to the derived class function in which it is being accessed, it is an altogether different object and hence derived member function cannot access its members.


What is a friend? How does friend affect access specification rules?

You can declare a function or class as friend of another class. When you do so the access specification rules do not apply to the friended class/function. The class or function can access all the members of that particular class.

So do friends break Encapsulation?

No they don't, On the contrary they enhance Encapsulation!

friendship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private or protected members but You do not want everyone to have access by using the public access specifier then you should use friendship.

Matching an empty input box using CSS

If only the field is required you could go with input:valid

_x000D_
_x000D_
#foo-thing:valid + .msg { visibility: visible!important; }      
_x000D_
 <input type="text" id="foo-thing" required="required">_x000D_
 <span class="msg" style="visibility: hidden;">Yay not empty</span>
_x000D_
_x000D_
_x000D_

See live on jsFiddle

OR negate using #foo-thing:invalid (credit to @SamGoody)

How to pass model attributes from one Spring MVC controller to another controller?

I used @ControllerAdvice , please check is available in Spring 3.X; I am using it in Spring 4.0.

@ControllerAdvice 
public class CommonController extends ControllerBase{
@Autowired
MyService myServiceInstance;

    @ModelAttribute("userList")
    public List<User> getUsersList()
    {
       //some code
       return ...
    }
}

Laravel Mail::send() sending to multiple to or bcc addresses

Try this:

$toemail = explode(',', str_replace(' ', '', $request->toemail));

If two cells match, return value from third

=IF(ISNA(INDEX(B:B,MATCH(C2,A:A,0))),"",INDEX(B:B,MATCH(C2,A:A,0)))

Will return the answer you want and also remove the #N/A result that would appear if you couldn't find a result due to it not appearing in your lookup list.

Ross

Disabling the long-running-script message in Internet Explorer

I can't comment on the previous answers since I haven't tried them. However I know the following strategy works for me. It is a bit less elegant but gets the job done. It also doesn't require breaking code into chunks like some other approaches seem to do. In my case, that was not an option, because my code had recursive calls to the logic that was being looped; i.e., there was no practical way to just hop out of the loop, then be able to resume in some way by using global vars to preserve current state since those globals could be changed by references to them in a subsequent recursed call. So I needed a straight-forward way that would not offer a chance for the code to compromise the data state integrity.

Assuming the "stop script?" dialog is coming up during a for() loop executuion after a number of iterations (in my case, about 8-10), and messing with the registry is no option, here was the fix (for me, anyway):

var anarray = [];
var array_member = null;
var counter = 0; // Could also be initialized to the max desired value you want, if
                 // planning on counting downward.

function func_a()
{
 // some code
 // optionally, set 'counter' to some desired value.
 ...
 anarray = { populate array with objects to be processed that would have been
             processed by a for() }
 // 'anarry' is going to be reduced in size iteratively.  Therefore, if you need
 //  to maintain an orig. copy of it, create one, something like 'anarraycopy'.
 //  If you need only a shallow copy, use 'anarraycopy = anarray.slice(0);'
 //  A deep copy, depending on what kind of objects you have in the array, may be
 //  necessary.  The strategy for a deep copy will vary and is not discussed here.
 //  If you need merely to record the array's orig. size, set a local or
 //  global var equal to 'anarray.length;', depending on your needs.
 // - or -
 // plan to use 'counter' as if it was 'i' in a for(), as in
 // for(i=0; i < x; i++ {...}

   ...

   // Using 50 for example only.  Could be 100, etc. Good practice is to pick something
   // other than 0 due to Javascript engine processing; a 0 value is all but useless
   // since it takes time for Javascript to do anything. 50 seems to be good value to
   // use. It could be though that what value to use does  depend on how much time it
   // takes the code in func_c() to execute, so some profiling and knowing what the 
   // most likely deployed user base is going to be using might help. At the same 
   // time, this may make no difference.  Not entirely sure myself.  Also, 
   // using "'func_b()'" instead of just "func_b()" is critical.  I've found that the
   // callback will not occur unless you have the function in single-quotes.

   setTimeout('func_b()', 50);

  //  No more code after this.  function func_a() is now done.  It's important not to
  //  put any more code in after this point since setTimeout() does not act like
  //  Thread.sleep() in Java.  Processing just continues, and that is the problem
  //  you're trying to get around.

} // func_a()


function func_b()
{
 if( anarray.length == 0 )
 {
   // possibly do something here, relevant to your purposes
   return;
 }
//  -or- 
if( counter == x ) // 'x' is some value you want to go to.  It'll likely either
                   // be 0 (when counting down) or the max desired value you
                   // have for x if counting upward.
{
  // possibly do something here, relevant to your purposes
  return;
}

array_member = anarray[0];
anarray.splice(0,1); // Reduces 'anarray' by one member, the one at anarray[0].
                     // The one that was at anarray[1] is now at
                     // anarray[0] so will be used at the next iteration of func_b().

func_c();

setTimeout('func_b()', 50);

} // func_b()


function func_c()
{
  counter++; // If not using 'anarray'.  Possibly you would use
             // 'counter--' if you set 'counter' to the highest value
             // desired and are working your way backwards.

  // Here is where you have the code that would have been executed
  // in the for() loop.  Breaking out of it or doing a 'continue'
  // equivalent can be done with using 'return;' or canceling 
  // processing entirely can be done by setting a global var
  // to indicate the process is cancelled, then doing a 'return;', as in
  // 'bCancelOut = true; return;'.  Then in func_b() you would be evaluating
  // bCancelOut at the top to see if it was true.  If so, you'd just exit from
  // func_b() with a 'return;'

} // func_c()

Paste MS Excel data to SQL Server

why not just use export/import wizard in SSMS?

ojdbc14.jar vs. ojdbc6.jar

Also, from ojdbc14 to ojdbc6, several types (e.g., OracleResultSet, OracleStatement) moved from package oracle.jdbc.driver to oracle.jdbc.

Avoiding NullPointerException in Java

It is possible to define util methods which handles nested null-checks in an almost pretty way with Java 8 lambdas.

void example() {
    Entry entry = new Entry();
    // This is the same as H-MANs solution 
    Person person = getNullsafe(entry, e -> e.getPerson());    
    // Get object in several steps
    String givenName = getNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.getGivenName());
    // Call void methods
    doNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.nameIt());        
}

/** Return result of call to f1 with o1 if it is non-null, otherwise return null. */
public static <R, T1> R getNullsafe(T1 o1, Function<T1, R> f1) {
    if (o1 != null) return f1.apply(o1);
    return null; 
}

public static <R, T0, T1> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, R> f2) {
    return getNullsafe(getNullsafe(o0, f1), f2);
}

public static <R, T0, T1, T2> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Function<T2, R> f3) {
    return getNullsafe(getNullsafe(o0, f1, f2), f3);
}


/** Call consumer f1 with o1 if it is non-null, otherwise do nothing. */
public static <T1> void doNullsafe(T1 o1, Consumer<T1> f1) {
    if (o1 != null) f1.accept(o1);
}

public static <T0, T1> void doNullsafe(T0 o0, Function<T0, T1> f1, Consumer<T1> f2) {
    doNullsafe(getNullsafe(o0, f1), f2);
}

public static <T0, T1, T2> void doNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Consumer<T2> f3) {
    doNullsafe(getNullsafe(o0, f1, f2), f3);
}


class Entry {
    Person getPerson() { return null; }
}

class Person {
    Name getName() { return null; }
}

class Name {
    void nameIt() {}
    String getGivenName() { return null; }
}

(This answer was first posted here.)

Iterate a certain number of times without storing the iteration number anywhere

Well I think the forloop you've provided in the question is about as good as it gets, but I want to point out that unused variables that have to be assigned can be assigned to the variable named _, a convention for "discarding" the value assigned. Though the _ reference will hold the value you gave it, code linters and other developers will understand you aren't using that reference. So here's an example:

for _ in range(2):
    print('Hello')

Count(*) vs Count(1) - SQL Server

There is an article showing that the COUNT(1) on Oracle is just an alias to COUNT(*), with a proof about that.

I will quote some parts:

There is a part of the database software that is called “The Optimizer”, which is defined in the official documentation as “Built-in database software that determines the most efficient way to execute a SQL statement“.

One of the components of the optimizer is called “the transformer”, whose role is to determine whether it is advantageous to rewrite the original SQL statement into a semantically equivalent SQL statement that could be more efficient.

Would you like to see what the optimizer does when you write a query using COUNT(1)?

With a user with ALTER SESSION privilege, you can put a tracefile_identifier, enable the optimizer tracing and run the COUNT(1) select, like: SELECT /* test-1 */ COUNT(1) FROM employees;.

After that, you need to localize the trace files, what can be done with SELECT VALUE FROM V$DIAG_INFO WHERE NAME = 'Diag Trace';. Later on the file, you will find:

SELECT COUNT(*) “COUNT(1)” FROM “COURSE”.”EMPLOYEES” “EMPLOYEES”

As you can see, it's just an alias for COUNT(*).

Another important comment: the COUNT(*) was really faster two decades ago on Oracle, before Oracle 7.3:

Count(1) has been rewritten in count(*) since 7.3 because Oracle like to Auto-tune mythic statements. In earlier Oracle7, oracle had to evaluate (1) for each row, as a function, before DETERMINISTIC and NON-DETERMINISTIC exist.

So two decades ago, count(*) was faster

For another databases as Sql Server, it should be researched individually for each one.

I know that this question is specific for Sql Server, but the other questions on SO about the same subject, without mention the database, was closed and marked as duplicated from this answer.

Change the "From:" address in Unix "mail"

On Debian 7 I was still unable to correctly set the sender address using answers from this question, (would always be the hostname of the server) but resolved it this way.

Install heirloom-mailx

apt-get install heirloom-mailx

ensure it's the default.

update-alternatives --config mailx

Compose a message.

mail -s "Testing from & replyto" -r "sender <[email protected]>" -S replyto="[email protected]" [email protected] < <(echo "Test message")

R: Plotting a 3D surface from x, y, z

You could look at using Lattice. In this example I have defined a grid over which I want to plot z~x,y. It looks something like this. Note that most of the code is just building a 3D shape that I plot using the wireframe function.

The variables "b" and "s" could be x or y.

require(lattice)

# begin generating my 3D shape
b <- seq(from=0, to=20,by=0.5)
s <- seq(from=0, to=20,by=0.5)
payoff <- expand.grid(b=b,s=s)
payoff$payoff <- payoff$b - payoff$s
payoff$payoff[payoff$payoff < -1] <- -1
# end generating my 3D shape


wireframe(payoff ~ s * b, payoff, shade = TRUE, aspect = c(1, 1),
    light.source = c(10,10,10), main = "Study 1",
    scales = list(z.ticks=5,arrows=FALSE, col="black", font=10, tck=0.5),
    screen = list(z = 40, x = -75, y = 0))

Reading output of a command into an array in Bash

Here is an example. Imagine that you are going to put the files and directory names (under the current folder) to an array and count its items. The script would be like;

my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length

Or, you can iterate over this array by adding the following script:

for element in "${my_array[@]}"
do
   echo "${element}"
done

Please note that this is the core concept and the input is considered to be sanitized before, i.e. removing extra characters, handling empty Strings, and etc. (which is out of the topic of this thread).

How can I view the contents of an ElasticSearch index?

You can view any existing index by using the below CURL. Please replace the index-name with your actual name before running and it will run as is.

View the index content

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name?pretty

And the output will include an index(see settings in output) and its mappings too and it will look like below output -

{
  "index_name": {
    "aliases": {},
    "mappings": {
      "collection_name": {
        "properties": {
          "test_field": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
       }
    },
    "settings": {
      "index": {
        "creation_date": "1527377274366",
        "number_of_shards": "5",
        "number_of_replicas": "1",
        "uuid": "6QfKqbbVQ0Gbsqkq7WZJ2g",
        "version": {
          "created": "6020299"
        },
        "provided_name": "index_name"
      }
    }
  }
}

View ALL the data under this index

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name/_search?pretty

How do I install g++ for Fedora?

You should exec:

dnf install gcc-c++

How to make exe files from a node.js app?

Try nexe which creates a single executable out of your node.js apps

https://github.com/nexe/nexe

How I add Headers to http.get or http.post in Typescript and angular 2?

Be sure to declare HttpHeaders without null values.

    this.http.get('url', {headers: new HttpHeaders({'a': a || '', 'b': b || ''}))

Otherwise, if you try to add a null value to HttpHeaders it will give you an error.

How do you append to a file?

You can also do it with print instead of write:

with open('test.txt', 'a') as f:
    print('appended text', file=f)

If test.txt doesn't exist, it will be created...

jquery simple image slideshow tutorial

Here is my adaptation of Michael Soriano's tutorial. See below or in JSBin.

_x000D_
_x000D_
$(function() {_x000D_
  var theImage = $('ul#ss li img');_x000D_
  var theWidth = theImage.width();_x000D_
  //wrap into mother div_x000D_
  $('ul#ss').wrap('<div id="mother" />');_x000D_
  //assign height width and overflow hidden to mother_x000D_
  $('#mother').css({_x000D_
    width: function() {_x000D_
      return theWidth;_x000D_
    },_x000D_
    height: function() {_x000D_
      return theImage.height();_x000D_
    },_x000D_
    position: 'relative',_x000D_
    overflow: 'hidden'_x000D_
  });_x000D_
  //get total of image sizes and set as width for ul _x000D_
  var totalWidth = theImage.length * theWidth;_x000D_
  $('ul').css({_x000D_
    width: function() {_x000D_
      return totalWidth;_x000D_
    }_x000D_
  });_x000D_
_x000D_
  var ss_timer = setInterval(function() {_x000D_
    ss_next();_x000D_
  }, 3000);_x000D_
_x000D_
  function ss_next() {_x000D_
    var a = $(".active");_x000D_
    a.removeClass('active');_x000D_
_x000D_
    if (a.hasClass('last')) {_x000D_
      //last element -- loop_x000D_
      a.parent('ul').animate({_x000D_
        "margin-left": (0)_x000D_
      }, 1000);_x000D_
      a.siblings(":first").addClass('active');_x000D_
    } else {_x000D_
      a.parent('ul').animate({_x000D_
        "margin-left": (-(a.index() + 1) * theWidth)_x000D_
      }, 1000);_x000D_
      a.next().addClass('active');_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Cancel slideshow and move next manually on click_x000D_
  $('ul#ss li img').on('click', function() {_x000D_
    clearInterval(ss_timer);_x000D_
    ss_next();_x000D_
  });_x000D_
_x000D_
});
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
#ss {_x000D_
  list-style: none;_x000D_
}_x000D_
#ss li {_x000D_
  float: left;_x000D_
}_x000D_
#ss img {_x000D_
  width: 200px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<ul id="ss">_x000D_
  <li class="active">_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado-colors.jpg">_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/monte-vista.jpg">_x000D_
  </li>_x000D_
  <li class="last">_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado.jpg">_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How do I resolve ClassNotFoundException?

Your classpath is broken (which is a very common problem in the Java world).

Depending on how you start your application, you need to revise the argument to -cp, your Class-Path entry in MANIFEST.MF or your disk layout.

How to print_r $_POST array?

<?php 

 foreach ($_POST as $key => $value) {
  echo '<p>'.$key.'</p>';
  foreach($value as $k => $v)
  {
  echo '<p>'.$k.'</p>';
  echo '<p>'.$v.'</p>';
  echo '<hr />';
  }

} 

 ?>

this will work, your first solution is trying to print array, because your value is an array.

How to make HTML input tag only accept numerical values?

_x000D_
_x000D_
function AllowOnlyNumbers(e) {_x000D_
_x000D_
e = (e) ? e : window.event;_x000D_
var clipboardData = e.clipboardData ? e.clipboardData : window.clipboardData;_x000D_
var key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;_x000D_
var str = (e.type && e.type == "paste") ? clipboardData.getData('Text') : String.fromCharCode(key);_x000D_
_x000D_
return (/^\d+$/.test(str));_x000D_
}
_x000D_
<h1>Integer Textbox</h1>_x000D_
    <input type="text" autocomplete="off" id="txtIdNum" onkeypress="return AllowOnlyNumbers(event);" />
_x000D_
_x000D_
_x000D_

JSFiddle: https://jsfiddle.net/ug8pvysc/

What does the "__block" keyword mean?

__block is a storage qualifier that can be used in two ways:

  1. Marks that a variable lives in a storage that is shared between the lexical scope of the original variable and any blocks declared within that scope. And clang will generate a struct to represent this variable, and use this struct by reference(not by value).

  2. In MRC, __block can be used to avoid retain object variables a block captures. Careful that this doesn't work for ARC. In ARC, you should use __weak instead.

You can refer to apple doc for detailed information.

How to make phpstorm display line numbers by default?

Just now found where is it on Windows. Its View -> Active Editor -> Show Line Numbers (changes only for current document) and File -> Settings -> Editor -> Appearance -> Show Line Numbers (for all documents)

For Mac Version go to PhpStorm -> Preferences in menu. In the preference window go to IDE settings -> Editor -> Appearance -> Show Line Numbers (To change setting for all documents)

OR if you want to quickly set show line number PER CURRENT WINDOW even easier - right click on the long white column (where breakpoints are set) then select Show Line Numbers.

enter image description here

Red dot on the screenshot is a place where you have to click

How can I find the dimensions of a matrix in Python?

The correct answer is the following:

import numpy 
numpy.shape(a)

Android Studio doesn't recognize my device

In addition to the above configurations, I had to set deployment target to "Open Select Deployment Target Dialog", run once (choosing my device from the options listed), and from then on Android Studio was able to see my device even after changing the deployment setting back to "USB Device". My SWAG is that since Android Studio uses its own internal cache to find your device, it has to be initialized first.

Catching "Maximum request length exceeded"

After tag

<security>
     <requestFiltering>
         <requestLimits maxAllowedContentLength="4500000" />
     </requestFiltering>
</security>

add the following tag

 <httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" subStatusCode="13" />
  <error statusCode="404" subStatusCode="13" prefixLanguageFilePath="" path="http://localhost/ErrorPage.aspx" responseMode="Redirect" />
</httpErrors>

you can add the Url to the error page...

Request string without GET arguments

Edit: @T.Todua provided a newer answer to this question using parse_url.

(please upvote that answer so it can be more visible).

Edit2: Someone has been spamming and editing about extracting scheme, so I've added that at the bottom.

parse_url solution

The simplest solution would be:

echo parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);

Parse_url is a built-in php function, who's sole purpose is to extract specific components from a url, including the PATH (everything before the first ?). As such, it is my new "best" solution to this problem.

strtok solution

Stackoverflow: How to remove the querystring and get only the url?

You can use strtok to get string before first occurence of ?

$url=strtok($_SERVER["REQUEST_URI"],'?');

Performance Note: This problem can also be solved using explode.

  • Explode tends to perform better for cases splitting the sring only on a single delimiter.
  • Strtok tends to perform better for cases utilizing multiple delimiters.

This application of strtok to return everything in a string before the first instance of a character will perform better than any other method in PHP, though WILL leave the querystring in memory.

An aside about Scheme (http/https) and $_SERVER vars

While OP did not ask about it, I suppose it is worth mentioning: parse_url should be used to extract any specific component from the url, please see the documentation for that function:

parse_url($actual_link, PHP_URL_SCHEME); 

Of note here, is that getting the full URL from a request is not a trivial task, and has many security implications. $_SERVER variables are your friend here, but they're a fickle friend, as apache/nginx configs, php environments, and even clients, can omit or alter these variables. All of this is well out of scope for this question, but it has been thoroughly discussed:

https://stackoverflow.com/a/6768831/1589379

It is important to note that these $_SERVER variables are populated at runtime, by whichever engine is doing the execution (/var/run/php/ or /etc/php/[version]/fpm/). These variables are passed from the OS, to the webserver (apache/nginx) to the php engine, and are modified and amended at each step. The only such variables that can be relied on are REQUEST_URI (because it's required by php), and those listed in RFC 3875 (see: PHP: $_SERVER ) because they are required of webservers.

please note: spaming links to your answers across other questions is not in good taste.

Remove duplicated rows using dplyr

When selecting columns in R for a reduced data-set you can often end up with duplicates.

These two lines give the same result. Each outputs a unique data-set with two selected columns only:

distinct(mtcars, cyl, hp);

summarise(group_by(mtcars, cyl, hp));

Gunicorn worker timeout error

Could it be this? http://docs.gunicorn.org/en/latest/settings.html#timeout

Other possibilities could be your response is taking too long or is stuck waiting.

PHPMailer AddAddress()

foreach ($all_address as $aa) {
    $mail->AddAddress($aa); 
}