Programs & Examples On #Delphi.net

How to extract string following a pattern with grep, regex or perl

this could do it:

perl -ne 'if(m/name="(.*?)"/){ print $1 . "\n"; }'

How to create a custom string representation for a class object?

class foo(object):
    def __str__(self):
        return "representation"
    def __unicode__(self):
        return u"representation"

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from somewhere.com. Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

How do I exclude Weekend days in a SQL Server query?

The answer depends on your server's week-start set up, so it's either

SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (7,1)

if Sunday is the first day of the week for your server

or

SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (6,7)

if Monday is the first day of the week for your server

Comment if you've got any questions :-)

Python Remove last 3 characters of a string

>>> foo = 'BS1 1AB'
>>> foo.replace(" ", "").rstrip()[:-3].upper()
'BS1'

Java String declaration

First one will create new String object in heap and str will refer it. In addition literal will also be placed in String pool. It means 2 objects will be created and 1 reference variable.

Second option will create String literal in pool only and str will refer it. So only 1 Object will be created and 1 reference. This option will use the instance from String pool always rather than creating new one each time it is executed.

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

In order for System.loadLibrary() to work, the library (on Windows, a DLL) must be in a directory somewhere on your PATH or on a path listed in the java.library.path system property (so you can launch Java like java -Djava.library.path=/path/to/dir).

Additionally, for loadLibrary(), you specify the base name of the library, without the .dll at the end. So, for /path/to/something.dll, you would just use System.loadLibrary("something").

You also need to look at the exact UnsatisfiedLinkError that you are getting. If it says something like:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no foo in java.library.path

then it can't find the foo library (foo.dll) in your PATH or java.library.path. If it says something like:

Exception in thread "main" java.lang.UnsatisfiedLinkError: com.example.program.ClassName.foo()V

then something is wrong with the library itself in the sense that Java is not able to map a native Java function in your application to its actual native counterpart.

To start with, I would put some logging around your System.loadLibrary() call to see if that executes properly. If it throws an exception or is not in a code path that is actually executed, then you will always get the latter type of UnsatisfiedLinkError explained above.

As a sidenote, most people put their loadLibrary() calls into a static initializer block in the class with the native methods, to ensure that it is always executed exactly once:

class Foo {

    static {
        System.loadLibrary('foo');
    }

    public Foo() {
    }

}

set column width of a gridview in asp.net

This what worked for me. set HeaderStyle-Width="5%", in the footer set textbox width Width="15",also set the width of your gridview to 100%. following is the one of the column of my gridview.

    <asp:TemplateField   HeaderText = "sub" HeaderStyle-ForeColor="White" HeaderStyle-Width="5%">
<ItemTemplate>
    <asp:Label ID="sub" runat="server" Font-Size="small" Text='<%# Eval("sub")%>'></asp:Label>
</ItemTemplate> 
 <EditItemTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Text='<%# Eval("sub")%>'></asp:TextBox>
</EditItemTemplate> 
<FooterTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Width="15"></asp:TextBox>
</FooterTemplate>

How to calculate the number of days between two dates?

Here is a function that does this:

function days_between(date1, date2) {

    // The number of milliseconds in one day
    const ONE_DAY = 1000 * 60 * 60 * 24;

    // Calculate the difference in milliseconds
    const differenceMs = Math.abs(date1 - date2);

    // Convert back to days and return
    return Math.round(differenceMs / ONE_DAY);

}

Using jQuery to see if a div has a child with a certain class

Simple Way

if ($('#text-field > p.filled-text').length != 0)

How to properly validate input values with React.JS?

I recently spent a week studying lot of solutions to validate my forms in an app. I started with all the most stared one but I couldn't find one who was working as I was expected. After few days, I became quite frustrated until i found a very new and amazing plugin: https://github.com/kettanaito/react-advanced-form

The developper is very responsive and his solution, after my research, merit to become the most stared one from my perspective. I hope it could help and you'll appreciate.

HTML.ActionLink vs Url.Action in ASP.NET Razor

I used the code below to create a Button and it worked for me.

<input type="button" value="PDF" onclick="location.href='@Url.Action("Export","tblOrder")'"/>

Class constants in python

You can get to SIZES by means of self.SIZES (in an instance method) or cls.SIZES (in a class method).

In any case, you will have to be explicit about where to find SIZES. An alternative is to put SIZES in the module containing the classes, but then you need to define all classes in a single module.

How can I get a user's media from Instagram without authenticating as a user?

Just want to add to @350D answer, since it was hard for me to understand.

My logic in code is next:

When calling API first time, i'm calling only https://www.instagram.com/_vull_ /media/. When I receive response, I check boolean value of more_available. If its true, I get the last photo from the array, get its id and then call Instagram API again but this time https://www.instagram.com/_vull_/media/?max_id=1400286183132701451_1642962433.

Important thing to know here, this Id is the Id of the last picture in the array. So when asking for maxId with the last id of the picture in the array, you will get next 20 pictures, and so on.

Hope this clarify things.

How to install an apk on the emulator in Android Studio?

enter image description here

When you start Android studio Look for Profile or Debug apk.

After clicking you get the option to browse for the saved apk and you will be bale to later run it using emulator

Add key value pair to all objects in array

_.forEach(arrOfObj,(arrVal,arrIn) => {
             arrVal.isAcitve = true;
            }

How to properly override clone method?

The way your code works is pretty close to the "canonical" way to write it. I'd throw an AssertionError within the catch, though. It signals that that line should never be reached.

catch (CloneNotSupportedException e) {
    throw new AssertionError(e);
}

CORS with POSTMAN

CORS (Cross-Origin Resource Sharing) and SOP (Same-Origin Policy) are server-side configurations that clients decide to enforce or not.

Related to clients

  • Most Browsers do enforce it to prevent issues related to CSRF attack.
  • Most Development tools don't care about it.

C# using streams

To expand a little on other answers here, and help explain a lot of the example code you'll see dotted about, most of the time you don't read and write to a stream directly. Streams are a low-level means to transfer data.

You'll notice that the functions for reading and writing are all byte orientated, e.g. WriteByte(). There are no functions for dealing with integers, strings etc. This makes the stream very general-purpose, but less simple to work with if, say, you just want to transfer text.

However, .NET provides classes that convert between native types and the low-level stream interface, and transfers the data to or from the stream for you. Some notable such classes are:

StreamWriter // Badly named. Should be TextWriter.
StreamReader // Badly named. Should be TextReader.
BinaryWriter
BinaryReader

To use these, first you acquire your stream, then you create one of the above classes and associate it with the stream. E.g.

MemoryStream memoryStream = new MemoryStream();
StreamWriter myStreamWriter = new StreamWriter(memoryStream);

StreamReader and StreamWriter convert between native types and their string representations then transfer the strings to and from the stream as bytes. So

myStreamWriter.Write(123);

will write "123" (three characters '1', '2' then '3') to the stream. If you're dealing with text files (e.g. html), StreamReader and StreamWriter are the classes you would use.

Whereas

myBinaryWriter.Write(123);

will write four bytes representing the 32-bit integer value 123 (0x7B, 0x00, 0x00, 0x00). If you're dealing with binary files or network protocols BinaryReader and BinaryWriter are what you might use. (If you're exchanging data with networks or other systems, you need to be mindful of endianness, but that's another post.)

How can I run a function from a script in command line?

The following command first registers the function in the context, then calls it:

. ./myScript.sh && function_name

Create a table without a header in Markdown

$ cat foo.md
Key 1 | Value 1
Key 2 | Value 2
$ kramdown foo.md
<table>
  <tbody>
    <tr>
      <td>Key 1</td>
      <td>Value 1</td>
    </tr>
    <tr>
      <td>Key 2</td>
      <td>Value 2</td>
    </tr>
  </tbody>
</table>

Getting indices of True values in a boolean list

TL; DR: use np.where as it is the fastest option. Your options are np.where, itertools.compress, and list comprehension.

See the detailed comparison below, where it can be seen np.where outperforms both itertools.compress and also list comprehension.

>>> from itertools import compress
>>> import numpy as np
>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]`
>>> t = 1000*t
  • Method 1: Using list comprehension
>>> %timeit [i for i, x in enumerate(t) if x]
457 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
  • Method 2: Using itertools.compress
>>> %timeit list(compress(range(len(t)), t))
210 µs ± 704 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
  • Method 3 (the fastest method): Using numpy.where
>>> %timeit np.where(t)
179 µs ± 593 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

How to watch and reload ts-node when TypeScript files change

Add "watch": "nodemon --exec ts-node -- ./src/index.ts" to scripts section of your package.json.

Deserialize a json string to an object in python

>>> j = '{"action": "print", "method": "onData", "data": "Madan Mohan"}'
>>> import json
>>> 
>>> class Payload(object):
...     def __init__(self, j):
...         self.__dict__ = json.loads(j)
... 
>>> p = Payload(j)
>>>
>>> p.action
'print'
>>> p.method
'onData'
>>> p.data
'Madan Mohan'

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

How do I parse an ISO 8601-formatted date?

Just use the python-dateutil module:

>>> import dateutil.parser as dp
>>> t = '1984-06-02T19:05:00.000Z'
>>> parsed_t = dp.parse(t)
>>> print(parsed_t)
datetime.datetime(1984, 6, 2, 19, 5, tzinfo=tzutc())

Documentation

Remove stubborn underline from link

As a rule, if your "underline" is not the same color as your text [and the 'color:' is not overridden inline] it is not coming from "text-decoration:" It has to be "border-bottom:"

Don't forget to take the border off your pseudo classes too!

a, a:link, a:visited, a:active, a:hover {border:0!important;}

This snippet assumes its on an anchor, change to it's wrapper accordingly... and use specificity instead of "!important" after you track down the root cause.

Get unicode value of a character

are you picky with using Unicode because with java its more simple if you write your program to use "dec" value or (HTML-Code) then you can simply cast data types between char and int

char a = 98;
char b = 'b';
char c = (char) (b+0002);

System.out.println(a);
System.out.println((int)b);
System.out.println((int)c);
System.out.println(c);

Gives this output

b
98
100
d

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

I had the same warning using the raster package.

> my_mask[my_mask[] != 1] <- NA
Error: cannot allocate vector of size 5.4 Gb

The solution is really simple and consist in increasing the storage capacity of R, here the code line:

##To know the current storage capacity
> memory.limit()
[1] 8103
## To increase the storage capacity
> memory.limit(size=56000)
[1] 56000    
## I did this to increase my storage capacity to 7GB

Hopefully, this will help you to solve the problem Cheers

How to disable right-click context-menu in JavaScript

You can't rely on context menus because the user can deactivate it. Most websites want to use the feature to annoy the visitor.

How can I copy columns from one sheet to another with VBA in Excel?

If you have merged cells,

Sub OneCell()
    Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
End Sub

that doesn't copy cells as they are, where previous code does copy exactly as they look like (merged).

CSS border less than 1px

The minimum width that your screen can display is 1 pixel. So its impossible to display less then 1px. 1 pixels can only have 1 color and cannot be split up.

Permission denied error while writing to a file in Python

I write python script with IDLE3.8(python 3.8.0) I have solved this question: if the path is shelve.open('C:\\database.dat') it will be PermissionError: [Errno 13] Permission denied: 'C:\\database.dat.dat'. But when I test to set the path as shelve.open('E:\\database.dat') That is OK!!! Then I test all the drive(such as C,D,F...) on my computer,Only when the Path set in Disk

C:\\

will get the permission denied error. So I think this is a protect path in windows to avoid python script to change or read files in system Disk(Disk C)

How To: Best way to draw table in console app (C#)

class ArrayPrinter
    {
    #region Declarations

    static bool isLeftAligned = false;
    const string cellLeftTop = "+";
    const string cellRightTop = "+";
    const string cellLeftBottom = "+";
    const string cellRightBottom = "+";
    const string cellHorizontalJointTop = "-";
    const string cellHorizontalJointbottom = "-";
    const string cellVerticalJointLeft = "+";
    const string cellTJoint = "+";
    const string cellVerticalJointRight = "¦";
    const string cellHorizontalLine = "-";
    const string cellVerticalLine = "¦";

    #endregion

    #region Private Methods

    private static int GetMaxCellWidth(string[,] arrValues)
    {
        int maxWidth = 1;

        for (int i = 0; i < arrValues.GetLength(0); i++)
        {
            for (int j = 0; j < arrValues.GetLength(1); j++)
            {
                int length = arrValues[i, j].Length;
                if (length > maxWidth)
                {
                    maxWidth = length;
                }
            }
        }

        return maxWidth;
    }

    private static string GetDataInTableFormat(string[,] arrValues)
    {
        string formattedString = string.Empty;

        if (arrValues == null)
            return formattedString;

        int dimension1Length = arrValues.GetLength(0);
        int dimension2Length = arrValues.GetLength(1);

        int maxCellWidth = GetMaxCellWidth(arrValues);
        int indentLength = (dimension2Length * maxCellWidth) + (dimension2Length - 1);
        //printing top line;
        formattedString = string.Format("{0}{1}{2}{3}", cellLeftTop, Indent(indentLength), cellRightTop, System.Environment.NewLine);

        for (int i = 0; i < dimension1Length; i++)
        {
            string lineWithValues = cellVerticalLine;
            string line = cellVerticalJointLeft;
            for (int j = 0; j < dimension2Length; j++)
            {
                string value = (isLeftAligned) ? arrValues[i, j].PadRight(maxCellWidth, ' ') : arrValues[i, j].PadLeft(maxCellWidth, ' ');
                lineWithValues += string.Format("{0}{1}", value, cellVerticalLine);
                line += Indent(maxCellWidth);
                if (j < (dimension2Length - 1))
                {
                    line += cellTJoint;
                }
            }
            line += cellVerticalJointRight;
            formattedString += string.Format("{0}{1}", lineWithValues, System.Environment.NewLine);
            if (i < (dimension1Length - 1))
            {
                formattedString += string.Format("{0}{1}", line, System.Environment.NewLine);
            }
        }

        //printing bottom line
        formattedString += string.Format("{0}{1}{2}{3}", cellLeftBottom, Indent(indentLength), cellRightBottom, System.Environment.NewLine);
        return formattedString;
    }

    private static string Indent(int count)
    {
        return string.Empty.PadLeft(count, '-');                 
    }

    #endregion

    #region Public Methods

    public static void PrintToStream(string[,] arrValues, StreamWriter writer)
    {
        if (arrValues == null)
            return;

        if (writer == null)
            return;

        writer.Write(GetDataInTableFormat(arrValues));
    }

    public static void PrintToConsole(string[,] arrValues)
    {
        if (arrValues == null)
            return;

        Console.WriteLine(GetDataInTableFormat(arrValues));
    }

    #endregion

    static void Main(string[] args)
    {           
        int value = 997;
        string[,] arrValues = new string[5, 5];
        for (int i = 0; i < arrValues.GetLength(0); i++)
        {
            for (int j = 0; j < arrValues.GetLength(1); j++)
            {
                value++;
                arrValues[i, j] = value.ToString();
            }
        }
        ArrayPrinter.PrintToConsole(arrValues);
        Console.ReadLine();
    }
}

Empty or Null value display in SSRS text boxes

I couldn't get IsNothing() to behave and I didn't want to create dummy rows in my dataset (e.g. for a given list of customers create a dummy order per month displayed) and noticed that null values were displaying as -247192.

Lo and behold using that worked to suppress it (at least until MSFT changes SSRS for the better from 08R2) so forgive me but:

=iif(Fields!Sales_Diff.Value = -247192,"",Fields!Sales_Diff.Value)

How to install pkg config in windows?

Another place where you can get more updated binaries can be found at Fedora Build System site. Direct link to mingw-pkg-config package is: http://koji.fedoraproject.org/koji/buildinfo?buildID=354619

How to increase MySQL connections(max_connections)?

From Increase MySQL connection limit:-

MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:

For MySQL 3.x:

# vi /etc/my.cnf
set-variable = max_connections = 250

For MySQL 4.x and 5.x:

# vi /etc/my.cnf
max_connections = 250

Restart MySQL once you’ve made the changes and verify with:

echo "show variables like 'max_connections';" | mysql

EDIT:-(From comments)

The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs

How to display data from database into textbox, and update it

protected void Page_Load(object sender, EventArgs e)

    {

        DropDownTitle();
    }


protected void DropDownTitle()
{
    if (!Page.IsPostBack)
    {

        string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;

        string selectSQL = "select DISTINCT ForumTitlesID,ForumTitles from ForumTtitle";
        SqlConnection con = new SqlConnection(connection);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader;
        try
        {

            ListItem newItem = new ListItem();
            newItem.Text = "Select";
            newItem.Value = "0";
            ForumTitleList.Items.Add(newItem);
            con.Open();
            reader = cmd.ExecuteReader();



            while (reader.Read())
            {
                ListItem newItem1 = new ListItem();
                newItem1.Text = reader["ForumTitles"].ToString();
                newItem1.Value = reader["ForumTitlesID"].ToString();
                ForumTitleList.Items.Add(newItem1);



            }
            reader.Close();
            reader.Dispose();
            con.Close();
            con.Dispose();
            cmd.Dispose();


        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }
}

LINQ query to return a Dictionary<string, string>

Use the ToDictionary method directly.

var result = 
  // as Jon Skeet pointed out, OrderBy is useless here, I just leave it 
  // show how to use OrderBy in a LINQ query
  myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
                   .ToDictionary(mc => mc.KeyProp.ToString(), 
                                 mc => mc.ValueProp.ToString(), 
                                 StringComparer.OrdinalIgnoreCase);

What is the meaning of "Failed building wheel for X" in pip install?

In my case, update the pip versión after create the venv, this update pip from 9.0.1 to 20.3.1

python3 -m venv env/python
source env/python/bin/activate
pip3 install pip --upgrade

But, the message was...

Using legacy 'setup.py install' for django-avatar, since package 'wheel' is not installed.

Then, I install wheel package after update pip

python3 -m venv env/python
source env/python/bin/activate
pip3 install --upgrade pip
pip3 install wheel

And the message was...

Building wheel for django-avatar (setup.py): started
default:   Building wheel for django-avatar (setup.py): finished with status 'done'

How to change the Jupyter start-up folder

This is what I do for Jupyter/Anaconda on Windows. This method also passes jupyter a python configuration script. I use this to add a path to my project parent folder:

1 Create jnote.bat somewhere:

@echo off
call activate %1
call jupyter notebook "%CD%" %2 %3
pause

In the same folder create a windows shortcut jupyter-notebook

        TARGET: D:\util\jnote.bat py3-jupyter --config=jupyter_notebook_config.py
        START IN: %CD%

jupyter-notebook shortcut

Add the jupyter icon to the shortcut.

2 In your jupyter projects folders(s) do the following:

Create jupyter_notebook_config.py, put what you like in here:

import os
import sys
import inspect

# Add parent folder to sys path

currentdir = os.path.dirname(os.path.abspath(
    inspect.getfile(inspect.currentframe())))

parentdir = os.path.dirname(currentdir)

os.environ['PYTHONPATH'] = parentdir

Then paste the jupyter-notebook shortcut. Double-click the shortcut and your jupyter should light up and the packages in the parent folder will be available.

Working Soap client example

Yes, if you can acquire any WSDL file, then you can use SoapUI to create mock service of that service complete with unit test requests. I created an example of this (using Maven) that you can try out.

Disable sorting for a particular column in jQuery DataTables

This works for me for a single column

 $('#example').dataTable( {
"aoColumns": [
{ "bSortable": false 
 }]});

What is the backslash character (\\)?

It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.

e.g.

System.out.println("printing \"this\" in quotes");

outputs

printing "this" in quotes

How to delete a folder in C++?

My own implementation based off hB0 that also allows you to view the number of files in each folder also with a little performance boost.

#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <windows.h>
#include <conio.h>

union seperated {
  struct {
    unsigned int low;
    unsigned int high;
  } uint;
  unsigned long long ull;
};

unsigned long long num_dirs  = 1;
unsigned long long num_files = 0;
seperated size_files;

int DeleteDirectory( char* refRootDirectory );      //predeclare it

int DeleteDirectory( char* refRootDirectory ) {
    HANDLE      hFile;              // Handle to directory
    std::string strFilePath;            // Filepath
    WIN32_FIND_DATA FileInformation;    // File information
    int     dwError;            // Folder deleting error
    std::string strPattern;         // Pattern

    strPattern = (std::string)(refRootDirectory) + "\\*.*";
    hFile = ::FindFirstFile( strPattern.c_str(), &FileInformation );

    if( hFile != INVALID_HANDLE_VALUE )
    {
        do {
            if( FileInformation.cFileName[0] != '.' ) {
                strFilePath.erase();
                strFilePath = std::string(refRootDirectory) + "\\" + FileInformation.cFileName;

                if( FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
                    DeleteDirectory( (char*)strFilePath.c_str() );

                    dwError = ::GetLastError();
                    if( dwError != ERROR_NO_MORE_FILES ) {
                        std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                        return dwError;
                    } else {
                        // Set directory attributes
                        if( ! ::SetFileAttributes(refRootDirectory,FILE_ATTRIBUTE_NORMAL) ) {
                            std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                            return ::GetLastError();
                        }

                        // Delete directory
                        if( ! ::RemoveDirectory(refRootDirectory) ) {
                            std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                            return ::GetLastError();
                        }
                    }

                    ++num_dirs;
                } else {

                    // Set file attributes
                    if( ! ::SetFileAttributes(strFilePath.c_str(),FILE_ATTRIBUTE_NORMAL) ) {
                        std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                        return ::GetLastError();
                    }

                    // Delete file
                    if ( ! ::DeleteFile(strFilePath.c_str()) ) {
                        std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                        return ::GetLastError();
                    }

                    size_files.ull       += FileInformation.nFileSizeLow;
                    size_files.uint.high += FileInformation.nFileSizeHigh;

                    ++num_files;
                }
            }
        } while( ::FindNextFile(hFile,&FileInformation) );

        // Close handle
        ::FindClose( hFile  );
    }

    return 0;
}

unsigned long long num_files_total=0;
unsigned long long num_dirs_total=0;
unsigned long long total_size_files=0;

void my_del_directory( char* dir_name ) {
    int iRC = DeleteDirectory( dir_name );
    //int iRC=0;

    std::cout << "\"" << dir_name << "\""
             "\n    Folders: " << num_dirs
          << "\n    Files:   " << num_files
          << "\n    Size:    " << size_files.ull << " Bytes";
    if(iRC)
    {
        std::cout << "\n!ERROR!: " << iRC;
    }
    std::cout << "\n\n";

    num_dirs_total   += num_dirs;
    num_files_total  += num_files;
    total_size_files += size_files.ull;
    num_dirs  = 1;
    num_files = 0;
    size_files.ull = 0ULL;
    return;
}

int main( void )
{
    size_files.ull = 0ULL;

    my_del_directory( (char*)"C:\Windows\temp"      );
        // This will clear out the System temporary directory on windows systems

    std::cout << "\n\nResults" << "\nTotal Folders: " << num_dirs_total
                   << "\nTotal Files:   " << num_files_total
                   << "\nTotal Size:    " << total_size_files << " Bytes\n";

    return 0;
}

PHP array() to javascript array()

This may be a easy solution.

var mydate = '<?php implode("##",$youdateArray); ?>';
var ret = mydate.split("##");

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

Strangely, I didn't find anything about legends and labels in the Chart.js documentation. It seems like you can't do it with chart.js alone.

I used https://github.com/bebraw/Chart.js.legend which is extremely light, to generate the legends.

Finding all objects that have a given property inside a collection

You can use lambdaj. Things like these are trivial, the syntax is really smooth:

Person me = new Person("Mario", "Fusco", 35);
Person luca = new Person("Luca", "Marrocco", 29);
Person biagio = new Person("Biagio", "Beatrice", 39);
Person celestino = new Person("Celestino", "Bellone", 29);
List<Person> meAndMyFriends = asList(me, luca, biagio, celestino);
List<Person> oldFriends = filter(having(on(Person.class).getAge(), greaterThan(30)), meAndMyFriends);

and you can do much more complicated things. It uses hamcrest for the Matchers. Some will argue that this is not Java-style, but it's fun how this guy twisted Java to make a bit of functional programming. Have a look at the source code also, it's quite sci-fi.

Which .NET Dependency Injection frameworks are worth looking into?

Spring.Net is quite solid, but the documentation took some time to wade through. Autofac is good, and while .Net 2.0 is supported, you need VS 2008 to compile it, or else use the command line to build your app.

AttributeError: Module Pip has no attribute 'main'

It works well:

 py -m pip install --user --upgrade pip==9.0.3

Sending HTTP POST with System.Net.WebClient

Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:

Using client As New Net.WebClient
    Dim reqparm As New Specialized.NameValueCollection
    reqparm.Add("param1", "somevalue")
    reqparm.Add("param2", "othervalue")
    Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
    Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

The key part is this:

client.UploadValues(someurl, "POST", reqparm)

It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.

sorting dictionary python 3

I don't think you want an OrderedDict. It sounds like you'd prefer a SortedDict, that is a dict that maintains its keys in sorted order. The sortedcontainers module provides just such a data type. It's written in pure-Python, fast-as-C implementations, has 100% coverage and hours of stress.

Installation is easy with pip:

pip install sortedcontainers

Note that if you can't pip install then you can simply pull the source files from the open-source repository.

Then you're code is simply:

from sortedcontainers import SortedDict
myDic = SortedDict({10: 'b', 3:'a', 5:'c'})
sorted_list = list(myDic.keys())

The sortedcontainers module also maintains a performance comparison with other popular implementations.

Fetch: reject promise and catch the error if status is not OK?

For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable

Solution 1: Not throwing an error, handle the error ourselves

  async _fetch(request) {
    const fetchResult = await fetch(request); //Making the req
    const result = await fetchResult.json(); // parsing the response

    if (fetchResult.ok) {
      return result; // return success object
    }


    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    const error = new Error();
    error.info = responseError;

    return (error);
  }

Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:

  const userSaved = await apiCall(data); // calling fetch
  if (userSaved instanceof Error) {
    debug.log('Failed saving user', userSaved); // handle error

    return;
  }
  debug.log('Success saving user', userSaved); // handle success

Solution 2: Throwing an error, using try/catch

async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    let error = new Error();
    error = { ...error, ...responseError };
    throw (error);
  }

Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:

  try {
    const userSaved = await apiCall(data); // calling fetch
    debug.log('Success saving user', userSaved); // handle success
  } catch (e) {
    debug.log('Failed saving user', userSaved); // handle error
  }

Solution 3: Using customer error

  async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    throw new ClassError(result.message, result.data, result.code);
  }

And:

class ClassError extends Error {

  constructor(message = 'Something went wrong', data = '', code = '') {
    super();
    this.message = message;
    this.data = data;
    this.code = code;
  }

}

Hope it helped.

Extract a subset of a dataframe based on a condition involving a field

Here are the two main approaches. I prefer this one for its readability:

bar <- subset(foo, location == "there")

Note that you can string together many conditionals with & and | to create complex subsets.

The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there" returns a vector of T and F values that is the same length as the rows of foo. You can do this to return only rows where the condition returns true.

foo[foo$location == "there", ]

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

Only changing the settings with the following command did not work in my environment:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

I had to also ran the Force Merge API command:

curl -X POST "localhost:9200/my-index-000001/_forcemerge?pretty"

ref: Force Merge API

How to edit hosts file via CMD?

Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.

Examples of using

hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost

...and many others...

Help

Usage:
    hosts - run hosts command interpreter
    hosts <command> <params> - execute hosts command

Commands:
    add  <host> <aliases> <addr> # <comment>   - add new host
    set  <host|mask> <addr> # <comment>        - set ip and comment for host
    rem  <host|mask>   - remove host
    on   <host|mask>   - enable host
    off  <host|mask>   - disable host
    view [all] <mask>  - display enabled and visible, or all hosts
    hide <host|mask>   - hide host from 'hosts view'
    show <host|mask>   - show host in 'hosts view'
    print      - display raw hosts file
    format     - format host rows
    clean      - format and remove all comments
    rollback   - rollback last operation
    backup     - backup hosts file
    restore    - restore hosts file from backup
    recreate   - empty hosts file
    open       - open hosts file in notepad

Download

https://code.google.com/p/hostscmd/downloads/list

How do you easily horizontally center a <div> using CSS?

Here I add proper answer

You can use this snippet code and customize. Here I use 2 child block.This should show center of the page. You can use one or multiple blocks.

<html>
<head>
<style>
#parent {
    width: 100%;
    border: solid 1px #aaa;
    text-align: center;
    font-size: 20px;
    letter-spacing: 35px;
    white-space: nowrap;
    line-height: 12px;
    overflow: hidden;
}

.child {
    width: 100px;
    height: 100px;
    border: solid 1px #ccc;
    display: inline-block;
    vertical-align: middle;
}
</style>
</head>

<body>

<div class="mydiv" id="parent">


<div class="child">
Block 1
</div>
<div class="child">
Block 2
</div>

</div>
</body>
</html>

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

Here's another option, which is less efficient but more concise. It's how I generally handle this sort of problem:

Get-ChildItem -Recurse .\targetdir -Exclude *.log |
  Where-Object { $_.FullName -notmatch '\\excludedir($|\\)' }

The \\excludedir($|\\)' expression allows you to exclude the directory and its contents at the same time.

Update: Please check the excellent answer from msorens for an edge case flaw with this approach, and a much more fleshed out solution overall.

pdftk compression option

Trying to compress a PDF I made with 400ppi tiffs, mostly 8-bit, a few 24-bit, with PackBits compression, using tiff2pdf compressed with Zip/Deflate. One problem I had with every one of these methods: none of the above methods preserved the bookmarks TOC that I painstakingly manually created in Acrobat Pro X. Not even the recommended ebook setting for gs. Sure, I could just open a copy of the original with the TOC intact and do a Replace pages but unfortunately, none of these methods did a satisfactory job to begin with. Either they reduced the size so much that the quality was unacceptably pixellated, or they didn't reduce the size at all and in one case actually increased it despite quality loss.

pdftk compress:

no change in size
bookmarks TOC are gone

gs screen:

takes a ridiculously long time and 100% CPU
errors:
    sfopen: gs_parse_file_name failed.                                 ? 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->10.2MB hideously pixellated
bookmarks TOC are gone

gs printer:

takes a ridiculously long time and 100% CPU
no errors
74.8MB-->66.1MB
light blue background on pages 1-4
bookmarks TOC are gone

gs ebook:

errors:
    sfopen: gs_parse_file_name failed.
      ./base/gsicc_manage.c:1050: gsicc_open_search(): Could not find default_rgb.ic 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->32.2MB
badly pixellated
bookmarks TOC are gone

qpdf --linearize:

very fast, a few seconds
no size change
bookmarks TOC are gone

pdf2ps:

took very long time
output_pdf2ps.ps 74.8MB-->331.6MB

ps2pdf:

pretty fast
74.8MB-->79MB
very slightly degraded with sl. bluish background
bookmarks TOC are gone

Getting value of selected item in list box as string

To retreive the value of all selected item in à listbox you can cast selected item in DataRowView and then select column where your data is:

foreach(object element in listbox.SelectedItems) {
    DataRowView row = (DataRowView)element;
    MessageBox.Show(row[0]);
}

How can I suppress the newline after a print statement?

Because python 3 print() function allows end="" definition, that satisfies the majority of issues.

In my case, I wanted to PrettyPrint and was frustrated that this module wasn't similarly updated. So i made it do what i wanted:

from pprint import PrettyPrinter

class CommaEndingPrettyPrinter(PrettyPrinter):
    def pprint(self, object):
        self._format(object, self._stream, 0, 0, {}, 0)
        # this is where to tell it what you want instead of the default "\n"
        self._stream.write(",\n")

def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
    """Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
    printer = CommaEndingPrettyPrinter(
        stream=stream, indent=indent, width=width, depth=depth)
    printer.pprint(object)

Now, when I do:

comma_ending_prettyprint(row, stream=outfile)

I get what I wanted (substitute what you want -- Your Mileage May Vary)

How to set min-height for bootstrap container

Have you tried height: auto; on your .container div?

Here is a fiddle, if you change img height, container height will adjust to it.

EDIT

So if you "can't" change the inline min-height, you can overwrite the inline style with an !important parameter. It's not the cleanest way, but it solves your problem.

add to your .containerclass this line

min-height:0px !important;

I've updated my fiddle to give you an example.

How to cancel/abort jQuery AJAX request?

Create a function to call your API. Within this function we define request callApiRequest = $.get(... - even though this is a definition of a variable, the request is called immediately, but now we have the request defined as a variable. Before the request is called, we check if our variable is defined typeof(callApiRequest) != 'undefined' and also if it is pending suggestCategoryRequest.state() == 'pending' - if both are true, we .abort() the request which will prevent the success callback from running.

// We need to wrap the call in a function
callApi = function () {

    //check if request is defined, and status pending
    if (typeof(callApiRequest) != 'undefined'
        && suggestCategoryRequest.state() == 'pending') {

        //abort request
        callApiRequest.abort()

    }

    //define and make request
    callApiRequest = $.get("https://example.com", function (data) {

        data = JSON.parse(data); //optional (for JSON data format)
        //success callback

    });
}

Your server/API might not support aborting the request (what if API executed some code already?), but the javascript callback will not fire. This is useful, when for example you are providing input suggestions to a user, such as hashtags input.

You can further extend this function by adding definition of error callback - what should happen if request was aborted.

Common use-case for this snippet would be a text input that fires on keypress event. You can use a timeout, to prevent sending (some of) requests that you will have to cancel .abort().

Getting 404 Not Found error while trying to use ErrorDocument

The ErrorDocument directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot. In your case, this means that the actual path to the ErrorDocument is

ErrorDocument 404 /hellothere/error/404page.html

How to get the size of a JavaScript object?

Having the same problem. I searched on Google and I want to share with stackoverflow community this solution.

Important:

I used the function shared by Yan Qing on github https://gist.github.com/zensh/4975495

_x000D_
_x000D_
function memorySizeOf(obj) {_x000D_
    var bytes = 0;_x000D_
_x000D_
    function sizeOf(obj) {_x000D_
        if(obj !== null && obj !== undefined) {_x000D_
            switch(typeof obj) {_x000D_
            case 'number':_x000D_
                bytes += 8;_x000D_
                break;_x000D_
            case 'string':_x000D_
                bytes += obj.length * 2;_x000D_
                break;_x000D_
            case 'boolean':_x000D_
                bytes += 4;_x000D_
                break;_x000D_
            case 'object':_x000D_
                var objClass = Object.prototype.toString.call(obj).slice(8, -1);_x000D_
                if(objClass === 'Object' || objClass === 'Array') {_x000D_
                    for(var key in obj) {_x000D_
                        if(!obj.hasOwnProperty(key)) continue;_x000D_
                        sizeOf(obj[key]);_x000D_
                    }_x000D_
                } else bytes += obj.toString().length * 2;_x000D_
                break;_x000D_
            }_x000D_
        }_x000D_
        return bytes;_x000D_
    };_x000D_
_x000D_
    function formatByteSize(bytes) {_x000D_
        if(bytes < 1024) return bytes + " bytes";_x000D_
        else if(bytes < 1048576) return(bytes / 1024).toFixed(3) + " KiB";_x000D_
        else if(bytes < 1073741824) return(bytes / 1048576).toFixed(3) + " MiB";_x000D_
        else return(bytes / 1073741824).toFixed(3) + " GiB";_x000D_
    };_x000D_
_x000D_
    return formatByteSize(sizeOf(obj));_x000D_
};_x000D_
_x000D_
_x000D_
var sizeOfStudentObject = memorySizeOf({Student: {firstName: 'firstName', lastName: 'lastName', marks: 10}});_x000D_
console.log(sizeOfStudentObject);
_x000D_
_x000D_
_x000D_

What do you think about it?

Git pull - Please move or remove them before you can merge

I just faced the same issue and solved it using the following.First clear tracked files by using :

git clean -d -f

then try git pull origin master

You can view other git clean options by typing git clean -help

Getting String Value from Json Object Android

Here is the solution I used for me Is works for fetching JSON from string

protected String getJSONFromString(String stringJSONArray) throws JSONException {
        return new StringBuffer(
               new JSONArray(stringJSONArray).getJSONObject(0).getString("cartype"))
                   .append(" ")
                   .append(
               new JSONArray(employeeID).getJSONObject(0).getString("model"))
              .toString();
    }

Mongoose: findOneAndUpdate doesn't return updated document

I know, I am already late but let me add my simple and working answer here

const query = {} //your query here
const update = {} //your update in json here
const option = {new: true} //will return updated document

const user = await User.findOneAndUpdate(query , update, option)

how to delete default values in text field using selenium?

clear() didn't work for me. But this did:

input.sendKeys(Keys.CONTROL, Keys.chord("a")); //select all text in textbox
input.sendKeys(Keys.BACK_SPACE); //delete it
input.sendKeys("new text"); //enter new text

Shorthand if/else statement Javascript

Here is a way to do it that works, but may not be best practise for any language really:

var x,y;
x='something';
y=1;
undefined === y || (x = y);

alternatively

undefined !== y && (x = y);

PivotTable to show values, not sum of values

I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.

Assuming your data is in ColumnA:C and has column labels in Row 1, also that Month is formatted mmm(this last for ease of sorting):

  1. Sort the data by Name then Month
  2. Enter in D2 =IF(AND(A2=A1,C2=C1),D1+1,1) (One way to deal with what is the tricky issue of multiple entries for the same person for the same month).
  3. Create a pivot table from A1:D(last occupied row no.)
  4. Say insert in F1.
  5. Layout as in screenshot.

SO12803305 example

I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.

  1. Copy pivot table and Paste Special/Values to, say, L1.
  2. Delete top row of copied range with shift cells up.
  3. Insert new cell at L1 and shift down.
  4. Key 'Name' into L1.
  5. Filter copied range and for ColumnL, select Row Labels and numeric values.
  6. Delete contents of L2:L(last selected cell)
  7. Delete blank rows in copied range with shift cells up (may best via adding a column that counts all 12 months). Hopefully result should be as highlighted in yellow.

Happy to explain further/try again (I've not really tested this) if does not suit.

EDIT (To avoid second block of steps above and facilitate updating for source data changes)

.0. Before first step 2. add a blank row at the very top and move A2:D2 up.
.2. Adjust cell references accordingly (in D3 =IF(AND(A3=A2,C3=C2),D2+1,1).
.3. Create pivot table from A:D

.6. Overwrite Row Labels with Name.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1, ColumnG and rows and columns that show (blank).

additional example

Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).

Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank) into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.

MongoDB SELECT COUNT GROUP BY

I need some extra operation based on the result of aggregate function. Finally I've found some solution for aggregate function and the operation based on the result in MongoDB. I've a collection Request with field request, source, status, requestDate.

Single Field Group By & Count:

db.Request.aggregate([
    {"$group" : {_id:"$source", count:{$sum:1}}}
])

Multiple Fields Group By & Count:

db.Request.aggregate([
    {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}}
])

Multiple Fields Group By & Count with Sort using Field:

db.Request.aggregate([
    {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
    {$sort:{"_id.source":1}}
])

Multiple Fields Group By & Count with Sort using Count:

db.Request.aggregate([
    {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
    {$sort:{"count":-1}}
])

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

Optional Parameters in Go?

Go does not have optional parameters nor does it support method overloading:

Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.

Select parent element of known element in Selenium

Take a look at the possible XPath axes, you are probably looking for parent. Depending on how you are finding the first element, you could just adjust the xpath for that.

Alternatively you can try the double-dot syntax, .. which selects the parent of the current node.

Why is my Spring @Autowired field null?

I once encountered the same issue when I was not quite used to the life in the IoC world. The @Autowired field of one of my beans is null at runtime.

The root cause is, instead of using the auto-created bean maintained by the Spring IoC container (whose @Autowired field is indeed properly injected), I am newing my own instance of that bean type and using it. Of course this one's @Autowired field is null because Spring has no chance to inject it.

What do $? $0 $1 $2 mean in shell script?

These are positional arguments of the script.

Executing

./script.sh Hello World

Will make

$0 = ./script.sh
$1 = Hello
$2 = World

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.

How do I make WRAP_CONTENT work on a RecyclerView

i suggest you to put the recyclerview in any other layout (Relative layout is preferable). Then change recyclerview's height/width as match parent to that layout and set the parent layout's height/width as wrap content. it works for me

How to load external scripts dynamically in Angular?

Yet another option would be to utilize scriptjs package for that matter which

allows you to load script resources on-demand from any URL

Example

Install the package:

npm i scriptjs

and type definitions for scriptjs:

npm install --save @types/scriptjs

Then import $script.get() method:

import { get } from 'scriptjs';

and finally load script resource, in our case Google Maps library:

export class AppComponent implements OnInit {
  ngOnInit() {
    get("https://maps.googleapis.com/maps/api/js?key=", () => {
        //Google Maps library has been loaded...
    });
  }
}

Demo

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

You have enabled CORS and enabled Access-Control-Allow-Origin : * in the server.If still you get GET method working and POST method is not working then it might be because of the problem of Content-Type and data problem.

First AngularJS transmits data using Content-Type: application/json which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded

Example :-

        $scope.formLoginPost = function () {
            $http({
                url: url,
                method: "POST",
                data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(function (response) {
                // success
                console.log('success');
                console.log("then : " + JSON.stringify(response));
            }, function (response) { // optional
                // failed
                console.log('failed');
                console.log(JSON.stringify(response));
            });
        };

Note : I am using $.params to serialize the data to use Content-Type: x-www-form-urlencoded. Alternatively you can use the following javascript function

function params(obj){
    var str = "";
    for (var key in obj) {
        if (str != "") {
            str += "&";
        }
        str += key + "=" + encodeURIComponent(obj[key]);
    }
    return str;
}

and use params({ 'username': $scope.username, 'Password': $scope.Password }) to serialize it as the Content-Type: x-www-form-urlencoded requests only gets the POST data in username=john&Password=12345 form.

How to assign an action for UIImageView object in Swift

Swift4 Code

Try this some new extension methods:

import UIKit

extension UIView {

    fileprivate struct AssociatedObjectKeys {
        static var tapGestureRecognizer = "MediaViewerAssociatedObjectKey_mediaViewer"
    }

    fileprivate typealias Action = (() -> Void)?


    fileprivate var tapGestureRecognizerAction: Action? {
        set {
            if let newValue = newValue {
                // Computed properties get stored as associated objects
                objc_setAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
            }
        }
        get {
            let tapGestureRecognizerActionInstance = objc_getAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer) as? Action
            return tapGestureRecognizerActionInstance
        }
    }


    public func addTapGestureRecognizer(action: (() -> Void)?) {
        self.isUserInteractionEnabled = true
        self.tapGestureRecognizerAction = action
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
        self.addGestureRecognizer(tapGestureRecognizer)
    }


    @objc fileprivate func handleTapGesture(sender: UITapGestureRecognizer) {
        if let action = self.tapGestureRecognizerAction {
            action?()
        } else {
            print("no action")
        }
    }

}

Now whenever we want to add a UITapGestureRecognizer to a UIView or UIView subclass like UIImageView, we can do so without creating associated functions for selectors!

Usage:

 profile_ImageView.addTapGestureRecognizer {
        print("image tapped")
    }

How to make an AlertDialog in Flutter?

Check out Flutter Dropdown Banner to easily alert users of events and prompt action without having to manage the complexity of presenting, delaying, and dismissing the component.

To set it up:

import 'packages:dropdown_banner/dropdown_banner.dart';
...
class MainApp extends StatelessWidget {
  ...
  @override
  Widget build(BuildContext context) {
    final navigatorKey = GlobalKey<NavigatorState>();
    ...
    return MaterialApp(
        ...
        home: DropdownBanner(
          child: Scaffold(...),
          navigatorKey: navigatorKey,
        ),
    );
  }
}

To use it:

import 'packages:dropdown_banner/dropdown_banner.dart';
...
class SomeClass {
  ...
  void doSomethingThenFail() {
    DropdownBanner.showBanner(
      text: 'Failed to complete network request',
      color: Colors.red,
      textStyle: TextStyle(color: Colors.white),
    );
  }
}
Click here to see an example

How to redirect a url in NGINX

This is the top hit on Google for "nginx redirect". If you got here just wanting to redirect a single location:

location = /content/unique-page-name {
  return 301 /new-name/unique-page-name;
}

How to set IE11 Document mode to edge as default?

try to add this section in your web.config file on web server, sometimes it happens with php pages:

<httpProtocol>
    <customHeaders>
        <clear />
        <add name="X-UA-Compatible" value="IE=edge" />
    </customHeaders>
</httpProtocol>

Log4net rolling daily filename with date in the file name

Using Log4Net 1.2.13 we use the following configuration settings to allow date time in the file name.

<file type="log4net.Util.PatternString" value="E:/logname-%utcdate{yyyy-MM-dd}.txt" />

Which will provide files in the following convention: logname-2015-04-17.txt

With this it's usually best to have the following to ensure you're holding 1 log per day.

<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />

If size of file is a concern the following allows 500 files of 5MB in size until a new day spawns. CountDirection allows Ascending or Descending numbering of files which are no longer current.

 <maxSizeRollBackups value="500" />
 <maximumFileSize value="5MB" />
 <rollingStyle value="Composite" />
 <datePattern value="yyyyMMdd" />
 <CountDirection value="1"/>
 <staticLogFileName value="true" />

Refresh Page and Keep Scroll Position

I modified Sanoj Dushmantha's answer to use sessionStorage instead of localStorage. However, despite the documentation, browsers will still store this data even after the browser is closed. To fix this issue, I am removing the scroll position after it is reset.

<script>
    document.addEventListener("DOMContentLoaded", function (event) {
        var scrollpos = sessionStorage.getItem('scrollpos');
        if (scrollpos) {
            window.scrollTo(0, scrollpos);
            sessionStorage.removeItem('scrollpos');
        }
    });

    window.addEventListener("beforeunload", function (e) {
        sessionStorage.setItem('scrollpos', window.scrollY);
    });
</script>

XAMPP - Error: MySQL shutdown unexpectedly

if you inistalled mysql Independently you can stop mysql service if running no one of these answers are worked for me this work for me

How to check empty DataTable

First make sure that DataTable is not null and than check for the row count

if(dt!=null)
{
  if(dt.Rows.Count>0)
  {
    //do your code 
  }
}

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

So what is the URL that Yii::app()->params['pdfUrl'] gives? You say it should be https, but the log shows it's connecting on port 80... which almost no server is setup to accept https connections on. cURL is smart enough to know https should be on port 443... which would suggest that your URL has something wonky in it like: https://196.41.139.168:80/serve/?r=pdf/generatePdf

That's going to cause the connection to be terminated, when the Apache at the other end cannot do https communication with you on that port.

You realize your first $body definition gets replaced when you set $body to an array two lines later? {Probably just an artifact of you trying to solve the problem} You're also not encoding the client_url and client_id values (the former quite possibly containing characters that need escaping!) Oh and you're appending to $body_str without first initializing it.

From your verbose output we can see cURL is adding a content-length header, but... is it correct? I can see some comments out on the internets of that number being wrong (especially with older versions)... if that number was to small (for example) you'd get a connection-reset before all the data is sent. You can manually insert the header:

curl_setopt ($c, CURLOPT_HTTPHEADER, 
   array("Content-Length: ". strlen($body_str))); 

Oh and there's a handy function http_build_query that'll convert an array of name/value pairs into a URL encoded string for you.

All this rolls up into the final code:

$post=http_build_query(array(
  "client_url"=>Yii::app()->params['pdfClientURL'],
  "client_id"=>Yii::app()->params['pdfClientID'],
  "title"=>$title,
  "content"=>$content));

//Open to URL
$c=curl_init(Yii::app()->params['pdfUrl']);
//Send post
curl_setopt ($c, CURLOPT_POST, true);
//Optional: [try with/without]
curl_setopt ($c, CURLOPT_HTTPHEADER, array("Content-Length: ".strlen($post))); 
curl_setopt ($c, CURLOPT_POSTFIELDS, $post);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($c, CURLOPT_CONNECTTIMEOUT , 0);
curl_setopt ($c, CURLOPT_TIMEOUT  , 20);
//Collect result
$pdf = curl_exec ($c);
$curlInfo = curl_getinfo($c);
curl_close($c);

How to keep environment variables when using sudo

If you have the need to keep the environment variables in a script you can put your command in a here document like this. Especially if you have lots of variables to set things look tidy this way.

# prepare a script e.g. for running maven
runmaven=/tmp/runmaven$$
# create the script with a here document 
cat << EOF > $runmaven
#!/bin/bash
# run the maven clean with environment variables set
export ANT_HOME=/usr/share/ant
export MAKEFLAGS=-j4
mvn clean install
EOF
# make the script executable
chmod +x $runmaven
# run it
sudo $runmaven
# remove it or comment out to keep
rm $runmaven

Setting the default Java character encoding

My team encountered the same issue in machines with Windows.. then managed to resolve it in two ways:

a) Set enviroment variable (even in Windows system preferences)

JAVA_TOOL_OPTIONS
-Dfile.encoding=UTF8

b) Introduce following snippet to your pom.xml:

 -Dfile.encoding=UTF-8 

WITHIN

 <jvmArguments>
 -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8001
 -Dfile.encoding=UTF-8
 </jvmArguments>

How to see if an object is an array without using reflection?

One can access each element of an array separately using the following code:

Object o=...;
if ( o.getClass().isArray() ) {
    for(int i=0; i<Array.getLength(o); i++){
        System.out.println(Array.get(o, i));
    }
}

Notice that it is unnecessary to know what kind of underlying array it is, as this will work for any array.

What is the difference between pull and clone in git?

git clone URL ---> Complete project or repository will be downloaded as a seperate directory. and not just the changes git pull URL ---> fetch + merge --> It will only fetch the changes that have been done and not the entire project

Install sbt on ubuntu

The simplest way of installing SBT on ubuntu is the deb package provided by Typesafe.

Run the following shell commands:

  1. wget http://apt.typesafe.com/repo-deb-build-0002.deb
  2. sudo dpkg -i repo-deb-build-0002.deb
  3. sudo apt-get update
  4. sudo apt-get install sbt

And you're done !

Number of rows affected by an UPDATE in PL/SQL

Use the Count(*) analytic function OVER PARTITION BY NULL This will count the total # of rows

Place cursor at the end of text in EditText

This works

Editable etext = edittext.getText();
Selection.setSelection(etext,edittext.getText().toString().length());

Where to find 64 bit version of chromedriver.exe for Selenium WebDriver?

In the below mentioned link, ChromeDriver.exe for Windows 32 bit exist.

http://chromedriver.storage.googleapis.com/index.html?path=2.24/

It is working for me in Win7 64 bit.

How do I programmatically change file permissions?

Prior to Java 6, there is no support of file permission update at Java level. You have to implement your own native method or call Runtime.exec() to execute OS level command such as chmod.

Starting from Java 6, you can useFile.setReadable()/File.setWritable()/File.setExecutable() to set file permissions. But it doesn't simulate the POSIX file system which allows to set permission for different users. File.setXXX() only allows to set permission for owner and everyone else.

Starting from Java 7, POSIX file permission is introduced. You can set file permissions like what you have done on *nix systems. The syntax is :

File file = new File("file4.txt");
file.createNewFile();

Set<PosixFilePermission> perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);

Files.setPosixFilePermissions(file.toPath(), perms);

This method can only be used on POSIX file system, this means you cannot call it on Windows system.

For details on file permission management, recommend you to read this post.

Line break (like <br>) using only css

It works like this:

h4 {
    display:inline;
}
h4:after {
    content:"\a";
    white-space: pre;
}

Example: http://jsfiddle.net/Bb2d7/

The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

Get string character by index - Java

Like this:

String a ="hh1hhhhhhhh";
char s = a.charAt(3);

How to extract 1 screenshot for a video with ffmpeg at a given time?

Use the -ss option:

ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
  • For JPEG output use -q:v to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.

  • The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.

  • Placing -ss before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg cli tool documentation:

-ss position (input/output)

When used as an input option (before -i), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, so ffmpeg will seek to the closest seek point before position. When transcoding and -accurate_seek is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when -noaccurate_seek is used, it will be preserved.

When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.

position may be either in seconds or in hh:mm:ss[.xxx] form.

Http Basic Authentication in Java using HttpClient?

An easy way to login with a HTTP POST without doing any Base64 specific calls is to use the HTTPClient BasicCredentialsProvider

import java.io.IOException;
import static java.lang.System.out;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;

//code
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password);
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

HttpResponse response = client.execute(new HttpPost("http://address/test/login"));//Replace HttpPost with HttpGet if you need to perform a GET to login
int statusCode = response.getStatusLine().getStatusCode();
out.println("Response Code :"+ statusCode);

How to get all registered routes in Express?

I have adapted an old post that is no longer online for my needs. I've used express.Router() and registered my routes like this:

var questionsRoute = require('./BE/routes/questions');
app.use('/api/questions', questionsRoute);

I renamed the document.js file in apiTable.js and adapted it like this:

module.exports =  function (baseUrl, routes) {
    var Table = require('cli-table');
    var table = new Table({ head: ["", "Path"] });
    console.log('\nAPI for ' + baseUrl);
    console.log('\n********************************************');

    for (var key in routes) {
        if (routes.hasOwnProperty(key)) {
            var val = routes[key];
            if(val.route) {
                val = val.route;
                var _o = {};
                _o[val.stack[0].method]  = [baseUrl + val.path];    
                table.push(_o);
            }       
        }
    }

    console.log(table.toString());
    return table;
};

then i call it in my server.js like this:

var server = app.listen(process.env.PORT || 5000, function () {
    require('./BE/utils/apiTable')('/api/questions', questionsRoute.stack);
});

The result looks like this:

Result example

It's just an example but might be of use.. i hope..

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

This is how you get rid of that notice and be able to open those grid cells for edit

1) click "STRUCTURE"

2) go to the field you want to be a primary key (and this usually is the 1st one ) and then click on the "PRIMARY" and "INDEX" fields for that field and accept the PHPMyadmin's pop-up question "OK".

3) pad yourself in the back.

How to correctly link php-fpm and Nginx Docker containers?

As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).

Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from.

Using compose (1.6.2 in my machine), the docker-compose.yml file would read:

version: "2"
services:
  nginx:
    build:
      context: .
      dockerfile: nginx/Dockerfile
    ports:
      - "80:80"
    links:
      - fpm
    volumes_from:
      - data
  fpm:
    image: php:fpm
    volumes_from:
      - data
  data:
    build:
      context: .
      dockerfile: data/Dockerfile
    volumes:
      - /var/www/html

Note that data publishes a volume that is linked to the nginx and fpm services. Then the Dockerfile for the data service, that contains your source code:

FROM busybox

# content
ADD path/to/source /var/www/html

And the Dockerfile for nginx, that just replaces the default config:

FROM nginx

# config
ADD config/default.conf /etc/nginx/conf.d

For the sake of completion, here's the config file required for the example to work:

server {
    listen 0.0.0.0:80;

    root /var/www/html;

    location / {
        index index.php index.html;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass fpm:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    }
}

which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT, which is fpm:9000 thanks to the hostnames defined by compose, and the SCRIPT_FILENAME).

How to write a multiline Jinja statement

According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    line_statement_prefix='#'
)

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'

ComboBox: Adding Text and Value to an Item (no Binding Source)

Don't know if this will work for the situation given in the original post (never mind the fact that this is two years later), but this example works for me:

Hashtable htImageTypes = new Hashtable();
htImageTypes.Add("JPEG", "*.jpg");
htImageTypes.Add("GIF", "*.gif");
htImageTypes.Add("BMP", "*.bmp");

foreach (DictionaryEntry ImageType in htImageTypes)
{
    cmbImageType.Items.Add(ImageType);
}
cmbImageType.DisplayMember = "key";
cmbImageType.ValueMember = "value";

To read your value back out, you'll have to cast the SelectedItem property to a DictionaryEntry object, and you can then evaluate the Key and Value properties of that. For instance:

DictionaryEntry deImgType = (DictionaryEntry)cmbImageType.SelectedItem;
MessageBox.Show(deImgType.Key + ": " + deImgType.Value);

Difference between String replace() and replaceAll()

replace() method doesn't uses regex pattern whereas replaceAll() method uses regex pattern. So replace() performs faster than replaceAll().

How do I use method overloading in Python?

I write my answer in Python 3.2.1.

def overload(*functions):
    return lambda *args, **kwargs: functions[len(args)](*args, **kwargs)

How it works:

  1. overload takes any amount of callables and stores them in tuple functions, then returns lambda.
  2. The lambda takes any amount of arguments, then returns result of calling function stored in functions[number_of_unnamed_args_passed] called with arguments passed to the lambda.

Usage:

class A:
    stackoverflow=overload(                    \
        None, \ 
        #there is always a self argument, so this should never get called
        lambda self: print('First method'),      \
        lambda self, i: print('Second method', i) \
    )

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

Why not just return the worksheet name with address = cell.Worksheet.Name then you can concatenate the address back on like this address = cell.Worksheet.Name & "!" & cell.Address

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

The quick fix is ??a just restart docker:

  1. sudo service docker stop
  2. sudo service docker start

unique() for more than one variable

This is an addition to Josh's answer.

You can also keep the values of other variables while filtering out duplicated rows in data.table

Example:

library(data.table)

#create data table
dt <- data.table(
  V1=LETTERS[c(1,1,1,1,2,3,3,5,7,1)],
  V2=LETTERS[c(2,3,4,2,1,4,4,6,7,2)],
  V3=c(1),
  V4=c(2) )

> dt
# V1 V2 V3 V4
# A  B  1  2
# A  C  1  2
# A  D  1  2
# A  B  1  2
# B  A  1  2
# C  D  1  2
# C  D  1  2
# E  F  1  2
# G  G  1  2
# A  B  1  2

# set the key to all columns
setkey(dt)

# Get Unique lines in the data table
unique( dt[list(V1, V2), nomatch = 0] ) 

# V1 V2 V3 V4
# A  B  1  2
# A  C  1  2
# A  D  1  2
# B  A  1  2
# C  D  1  2
# E  F  1  2
# G  G  1  2

Alert: If there are different combinations of values in the other variables, then your result will be

unique combination of V1 and V2

how to do file upload using jquery serialization

$(document).on('click', '#submitBtn', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $("#myForm").closest("form");
var formData = new FormData(form[0]);
$.ajax({
    type: "POST",
    data: formData,
    dataType: "json",
    url: form.attr('action'),
    processData: false,
    contentType: false,
    success: function(data) {
         alert('Sucess! Form data posted with file type of input also!');
    }
)};});

By making use of new FormData() and setting processData: false, contentType:false in ajax call submission of form with file input worked for me

Using above code I am able to submit form data with file field also through Ajax

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

When I used the code mysqld_safe --skip-grant-tables & but I get the error:

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.

$ systemctl stop  mysql.service
$ ps -eaf|grep mysql
$ mysqld_safe --skip-grant-tables &

I solved:

$ mkdir -p /var/run/mysqld
$ chown mysql:mysql /var/run/mysqld

Now I use the same code mysqld_safe --skip-grant-tables & and get

mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

If I use $ mysql -u root I'll get :

Server version: 5.7.18-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Now time to change password:

mysql> use mysql
mysql> describe user;

Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

Database changed

mysql> FLUSH PRIVILEGES;
mysql> SET PASSWORD FOR root@'localhost' = PASSWORD('newpwd');

or If you have a mysql root account that can connect from everywhere, you should also do:

UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';

Alternate Method:

   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')
   WHERE Host = 'localhost' AND User = 'root';

And if you have a root account that can access from everywhere:

 USE mysql
 UPDATE user SET Password = PASSWORD('newpwd')
 WHERE Host = '%' AND User = 'root';`enter code here

now need to quit from mysql and stop/start

FLUSH PRIVILEGES;
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

now again ` mysql -u root -p' and use the new password to get

mysql>

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

How to Calculate Jump Target Address and Branch Target Address?

(In the diagrams and text below, PC is the address of the branch instruction itself. PC+4 is the end of the branch instruction itself, and the start of the branch delay slot. Except in the absolute jump diagram.)

1. Branch Address Calculation

In MIPS branch instruction has only 16 bits offset to determine next instruction. We need a register added to this 16 bit value to determine next instruction and this register is actually implied by architecture. It is PC register since PC gets updated (PC+4) during the fetch cycle so that it holds the address of the next instruction.

We also limit the branch distance to -2^15 to +2^15 - 1 instruction from the (instruction after the) branch instruction. However, this is not real issue since most branches are local anyway.

So step by step :

  • Sign extend the 16 bit offset value to preserve its value.
  • Multiply resulting value with 4. The reason behind this is that If we are going to branch some address, and PC is already word aligned, then the immediate value has to be word-aligned as well. However, it makes no sense to make the immediate word-aligned because we would be wasting low two bits by forcing them to be 00.
  • Now we have a 32 bit relative offset. Add this value to PC + 4 and that is your branch address.

Branch address calculation


2. Jump Address Calculation

For Jump instruction MIPS has only 26 bits to determine Jump location. Jumps are relative to PC in MIPS. Like branch, immediate jump value needs to be word-aligned; therefore, we need to multiply 26 bit address with four.

Again step by step:

  • Multiply 26 bit value with 4.
  • Since we are jumping relative to PC+4 value, concatenate first four bits of PC+4 value to left of our jump address.
  • Resulting address is the jump value.

In other words, replace the lower 28 bits of the PC + 4 with the lower 26 bits of the fetched instruction shifted left by 2 bits.

enter image description here

Jumps are region-relative to the branch-delay slot, not necessarily the branch itself. In the diagram above, PC has already advanced to the branch delay slot before the jump calculation. (In a classic-RISC 5 stage pipeline, the BD was fetched in the same cycle the jump is decoded, so that PC+4 next instruction address is already available for jumps as well as branches, and calculating relative to the jump's own address would have required extra work to save that address.)

Source: Bilkent University CS 224 Course Slides

How to open a URL in a new Tab using JavaScript or jQuery?

I know your question does not specify if you are trying to open all a tags in a new window or only the external links.

But in case you only want external links to open in a new tab you can do this:

$( 'a[href^="http://"]' ).attr( 'target','_blank' )
$( 'a[href^="https://"]' ).attr( 'target','_blank' )

twitter bootstrap navbar fixed top overlapping site

I put this before the yield container:

<div id="fix-for-navbar-fixed-top-spacing" style="height: 42px;">&nbsp;</div>

I like this approach because it documents the hack needed to get it work, plus it also works for the mobile nav.

EDIT - this works much better:

@media (min-width: 980px) {
  body {
    padding-top: 60px;
    padding-bottom: 42px;
  }
}

How do you manually execute SQL commands in Ruby On Rails using NuoDB

For me, I couldn't get this to return a hash.

results = ActiveRecord::Base.connection.execute(sql)

But using the exec_query method worked.

results = ActiveRecord::Base.connection.exec_query(sql)

LINQ Joining in C# with multiple conditions

Your and should be a && in the where clause.

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
and epl.ArriveAirportBy > sd.UTCArrivalTime

should be

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
&& epl.ArriveAirportBy > sd.UTCArrivalTime

Renaming columns in Pandas

As documented in Working with text data:

df.columns = df.columns.str.replace('$', '')

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

Android: Creating a Circular TextView?

I was also looking for a solution to this problem and as easy and comfortable I found, was to convert the shape of a rectangular TextView to cirular. With this method will be perfect:

  1. Create a new XML file in the drawable folder called "circle.xml" (for example) and fill it with the following code:

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval">
    
        <solid android:color="#9FE554" />
    
        <size
            android:height="60dp"
            android:width="60dp" />
    
    </shape>
    

With this file you will create the new form of TextView. In this case, I created a circle of green. If you want to add a border, you would have to add the following code to the previous file:

    <stroke
        android:width="2dp"
        android:color="#FFFFFF" />
  1. Create another XML file ( "rounded_textview.xml") in the drawable folder with the following code:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/circle" />
    </selector>
    

This file will serve to change the way the TextView we eligamos.

  1. Finally, in the TextView properties we want to change the way section, we headed to the "background" and select the second XML file created ( "rounded_textview.xml").

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="H"
        android:textSize="30sp"
        android:background="@drawable/rounded_textview"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:id="@+id/mark" />
    

With these steps, instead of having a TextView TextView rectagular have a circular. Just change the shape, not the functionality of the TextView. The result would be the following:

enter image description here

Also I have to say that these steps can be applied to any other component having the option to "background" in the properties.

Luck!!

Convert Char to String in C

I use this to convert char to string (an example) :

char c = 'A';
char str1[2] = {c , '\0'};
char str2[5] = "";
strcpy(str2,str1);

Jquery find nearest matching element

closest() only looks for parents, I'm guessing what you really want is .find()

$(this).closest('.row').children('.column').find('.inputQty').val();

json parsing error syntax error unexpected end of input

This error occurs on an empty JSON file reading.

To avoid this error in NodeJS I'm checking the file's size:

const { size } = fs.statSync(JSON_FILE);
const content = size ? JSON.parse(fs.readFileSync(JSON_FILE)) : DEFAULT_VALUE;

Javascript date regex DD/MM/YYYY

Scape slashes is simply use \ before / and it will be escaped. (\/=> /).

Otherwise you're regex DD/MM/YYYY could be next:

/^[0-9]{2}[\/]{1}[0-9]{2}[\/]{1}[0-9]{4}$/g

Explanation:

  • [0-9]: Just Numbers
  • {2} or {4}: Length 2 or 4. You could do {2,4} as well to length between two numbers (2 and 4 in this case)
  • [\/]: Character /
  • g : Global -- Or m: Multiline (Optional, see your requirements)
  • $: Anchor to end of string. (Optional, see your requirements)
  • ^: Start of string. (Optional, see your requirements)

An example of use:

_x000D_
_x000D_
var regex = /^[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}$/g;

var dates = ["2009-10-09", "2009.10.09", "2009/10/09", "200910-09", "1990/10/09", 
    "2016/0/09", "2017/10/09", "2016/09/09", "20/09/2016", "21/09/2016", "22/09/2016",
    "23/09/2016", "19/09/2016", "18/09/2016", "25/09/2016", "21/09/2018"];

//Iterate array
dates.forEach(
    function(date){
        console.log(date + " matches with regex?");
      console.log(regex.test(date));
    });
_x000D_
_x000D_
_x000D_

Of course you can use as boolean:

if(regex.test(date)){
     //do something
}

What is the purpose of the var keyword and when should I use it (or omit it)?

I see people are confused when declaring variables with or without var and inside or outside the function. Here is a deep example that will walk you through these steps:

See the script below in action here at jsfiddle

a = 1;// Defined outside the function without var
var b = 1;// Defined outside the function with var
alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");

function testVar1(){
    c = 1;// Defined inside the function without var
    var d = 1;// Defined inside the function with var
    alert("Now inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};


testVar1();
alert("Run the 1. function again...");
testVar1();

function testVar2(){
    var d = 1;// Defined inside the function with var
    alert("Now inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};

testVar2();

alert("Now outside of all functions... \n \n Final Values: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n You will not be able to see d here because then the value is requested, console.log would throw error 'Uncaught ReferenceError: d is not defined' and script would stop. \n ");
alert("**************\n Conclusion \n ************** \n \n 1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.\n 2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() \n 3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.");
alert("Now check console.log for the error when value d is requested next:");
alert(d);

Conclusion

  1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.
  2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2()
  3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.

How to convert a char to a String?

  char vIn = 'A';
  String vOut = Character.toString(vIn);

For these types of conversion, I have site bookmarked called https://www.converttypes.com/ It helps me quickly get the conversion code for most of the languages I use.

How do I set a program to launch at startup

    /// <summary>
    /// Add application to Startup of windows
    /// </summary>
    /// <param name="appName"></param>
    /// <param name="path"></param>
    public static void AddStartup(string appName, string path)
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.SetValue(appName, "\"" + path + "\"");
        }
    }

    /// <summary>
    /// Remove application from Startup of windows
    /// </summary>
    /// <param name="appName"></param>
    public static void RemoveStartup(string appName)
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.DeleteValue(appName, false);
        }
    }

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

Typos are a possible reason for this error.

Be sure to check you wrote spring-boot and not e.g. springboot or sprint-boot or springbok or whatever.

Also check the ordering : use spring-boot:run and not run:spring-boot.

How do you use window.postMessage across domains?

Here is an example that works on Chrome 5.0.375.125.

The page B (iframe content):

<html>
    <head></head>
    <body>
        <script>
            top.postMessage('hello', 'A');
        </script>
    </body>
</html>

Note the use of top.postMessage or parent.postMessage not window.postMessage here

The page A:

<html>
<head></head>
<body>
    <iframe src="B"></iframe>
    <script>
        window.addEventListener( "message",
          function (e) {
                if(e.origin !== 'B'){ return; } 
                alert(e.data);
          },
          false);
    </script>
</body>
</html>

A and B must be something like http://domain.com

EDIT:

From another question, it looks the domains(A and B here) must have a / for the postMessage to work properly.

Improving bulk insert performance in Entity framework

 Use : db.Set<tale>.AddRange(list); 
Ref :
TESTEntities db = new TESTEntities();
List<Person> persons = new List<Person> { 
new  Person{Name="p1",Place="palce"},
new  Person{Name="p2",Place="palce"},
new  Person{Name="p3",Place="palce"},
new  Person{Name="p4",Place="palce"},
new  Person{Name="p5",Place="palce"}
};
db.Set<Person>().AddRange(persons);
db.SaveChanges();

how to open .mat file without using MATLAB?

A .mat-file is a compressed binary file. It is not possible to open it with a text editor (except you have a special plugin as Dennis Jaheruddin says). Otherwise you will have to convert it into a text file (csv for example) with a script. This could be done by python for example: Read .mat files in Python.

Jenkins pipeline if else not working

        if ( params.build_deploy == '1' ) {
            println "build_deploy ? ${params.build_deploy}"
              jobB = build job: 'k8s-core-user_deploy', propagate: false, wait: true, parameters: [
                         string(name:'environment', value: "${params.environment}"),
                         string(name:'branch_name', value: "${params.branch_name}"),
                         string(name:'service_name', value: "${params.service_name}"),                      
                     ]
            println jobB.getResult()
        }

How to write a multidimensional array to a text file?

You can simply traverse the array in three nested loops and write their values to your file. For reading, you simply use the same exact loop construction. You will get the values in exactly the right order to fill your arrays correctly again.

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.

How much faster is C++ than C#?

There is no strict reason why a bytecode based language like C# or Java that has a JIT cannot be as fast as C++ code. However C++ code used to be significantly faster for a long time, and also today still is in many cases. This is mainly due to the more advanced JIT optimizations being complicated to implement, and the really cool ones are only arriving just now.

So C++ is faster, in many cases. But this is only part of the answer. The cases where C++ is actually faster, are highly optimized programs, where expert programmers thoroughly optimized the hell out of the code. This is not only very time consuming (and thus expensive), but also commonly leads to errors due to over-optimizations.

On the other hand, code in interpreted languages gets faster in later versions of the runtime (.NET CLR or Java VM), without you doing anything. And there are a lot of useful optimizations JIT compilers can do that are simply impossible in languages with pointers. Also, some argue that garbage collection should generally be as fast or faster as manual memory management, and in many cases it is. You can generally implement and achieve all of this in C++ or C, but it's going to be much more complicated and error prone.

As Donald Knuth said, "premature optimization is the root of all evil". If you really know for sure that your application will mostly consist of very performance critical arithmetic, and that it will be the bottleneck, and it's certainly going to be faster in C++, and you're sure that C++ won't conflict with your other requirements, go for C++. In any other case, concentrate on first implementing your application correctly in whatever language suits you best, then find performance bottlenecks if it runs too slow, and then think about how to optimize the code. In the worst case, you might need to call out to C code through a foreign function interface, so you'll still have the ability to write critical parts in lower level language.

Keep in mind that it's relatively easy to optimize a correct program, but much harder to correct an optimized program.

Giving actual percentages of speed advantages is impossible, it largely depends on your code. In many cases, the programming language implementation isn't even the bottleneck. Take the benchmarks at http://benchmarksgame.alioth.debian.org/ with a great deal of scepticism, as these largely test arithmetic code, which is most likely not similar to your code at all.

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

How to remove stop words using nltk or python

Although the question is a bit old, here is a new library, which is worth mentioning, that can do extra tasks.

In some cases, you don't want only to remove stop words. Rather, you would want to find the stopwords in the text data and store it in a list so that you can find the noise in the data and make it more interactive.

The library is called 'textfeatures'. You can use it as follows:

! pip install textfeatures
import textfeatures as tf
import pandas as pd

For example, suppose you have the following set of strings:

texts = [
    "blue car and blue window",
    "black crow in the window",
    "i see my reflection in the window"]

df = pd.DataFrame(texts) # Convert to a dataframe
df.columns = ['text'] # give a name to the column
df

Now, call the stopwords() function and pass the parameters you want:

tf.stopwords(df,"text","stopwords") # extract stop words
df[["text","stopwords"]].head() # give names to columns

The result is going to be:

    text                                 stopwords
0   blue car and blue window             [and]
1   black crow in the window             [in, the]
2   i see my reflection in the window    [i, my, in, the]

As you can see, the last column has the stop words included in that docoument (record).

Wrapping text inside input type="text" element HTML/CSS

To create a text input in which the value under the hood is a single line string but is presented to the user in a word-wrapped format you can use the contenteditable attribute on a <div> or other element:

_x000D_
_x000D_
const el = document.querySelector('div[contenteditable]');_x000D_
_x000D_
// Get value from element on input events_x000D_
el.addEventListener('input', () => console.log(el.textContent));_x000D_
_x000D_
// Set some value_x000D_
el.textContent = 'Lorem ipsum curae magna venenatis mattis, purus luctus cubilia quisque in et, leo enim aliquam consequat.'
_x000D_
div[contenteditable] {_x000D_
  border: 1px solid black;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div contenteditable></div>
_x000D_
_x000D_
_x000D_

How to get system time in Java without creating a new Date

Use System.currentTimeMillis() or System.nanoTime().

javac: file not found: first.java Usage: javac <options> <source files>

If this is the problem then go to the place where the javac is present and then type

  1. notepad Yourfilename.java
  2. it will ask for creation of the file
  3. say yes and copy the code from your previous source file to this file
  4. now execute the cmd------>javac Yourfilename.java

It will work for sure.

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

How to commit changes to a new branch

git checkout -b your-new-branch

git add <files>

git commit -m <message>

First, checkout your new branch. Then add all the files you want to commit to staging. Lastly, commit all the files you just added. You might want to do a git push origin your-new-branch afterward so your changes show up on the remote.

CSS Div stretch 100% page height

* {
margin: 0;
}
html, body {
height: 90%;
}
.content {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto ;
}

django admin - add custom form fields that are not part of the model

It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin.

Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them.

For example:

class MyModel(models.model):

    field1 = models.CharField(max_length=10)
    field2 = models.CharField(max_length=10)

    def combined_fields(self):
        return '{} {}'.format(self.field1, self.field2)

Then in the admin you can add the combined_fields() as a readonly field:

class MyModelAdmin(models.ModelAdmin):

    list_display = ('field1', 'field2', 'combined_fields')
    readonly_fields = ('combined_fields',)

    def combined_fields(self, obj):
        return obj.combined_fields()

If you want to store the combined_fields in the database you could also save it when you save the model:

def save(self, *args, **kwargs):
    self.field3 = self.combined_fields()
    super(MyModel, self).save(*args, **kwargs)

Open Google Chrome from VBA/Excel

You can use the following vba code and input them into standard module in excel. A list of websites can be entered and should be entered like this on cell A1 in Excel - www.stackoverflow.com

ActiveSheet.Cells(1,2).Value merely takes the number of website links that you have on cell B1 in Excel and will loop the code again and again based on number of website links you have placed on the sheet. Therefore Chrome will open up a new tab for each website link.

I hope this helps with the dynamic website you have got.

Sub multiplechrome()

    Dim WebUrl As String
    Dim i As Integer

    For i = 1 To ActiveSheet.Cells(1, 2).Value
        WebUrl = "http://" & Cells(i, 1).Value & """"
        Shell ("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl)

    Next
End Sub

How do I clone a generic List in Java?

List<String> shallowClonedList = new ArrayList<>(listOfStrings);

Keep in mind that this is only a shallow not a deep copy, ie. you get a new list, but the entries are the same. This is no problem for simply strings. Get's more tricky when the list entries are objects themself.

Not showing placeholder for input type="date" field

If you're only concerned with mobile:

input[type="date"]:invalid:before{
    color: rgb(117, 117, 117);
    content: attr(placeholder);
}

How to call an action after click() in Jquery?

you can write events on elements like chain,

$(element).on('click',function(){
   //action on click
}).on('mouseup',function(){
   //action on mouseup (just before click event)
});

i've used it for removing cart items. same object, doing some action, after another action

What JSON library to use in Scala?

You should check Genson. It just works and is much easier to use than most of the existing alternatives in Scala. It is fast, has many features and integrations with some other libs (jodatime, json4s DOM api...).

All that without any fancy unecessary code like implicits, custom readers/writers for basic cases, ilisible API due to operator overload...

Using it is as easy as:

import com.owlike.genson.defaultGenson_

val json = toJson(Person(Some("foo"), 99))
val person = fromJson[Person]("""{"name": "foo", "age": 99}""")

case class Person(name: Option[String], age: Int)

Disclaimer: I am Gensons author, but that doesn't meen I am not objective :)

When should an Excel VBA variable be killed or set to Nothing?

VBA uses a garbage collector which is implemented by reference counting.

There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.

Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)

how to check confirm password field in form without reloading page

The code proposed by #Chandrahasa Rai works almost perfectly good, with one exception!

When triggering function checkPass(), i changed onkeypress to onkeyup so the last key pressed can be processed too. Otherwise when You type a password, for example: "1234", when You type the last key "4", the script triggers checkPass() before processing "4", so it actually checks "123" instead of "1234". You have to give it a chance by letting key go up :) Now everything should be working fine!

#Chandrahasa Rai, HTML code:

<input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>

<input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>

#my modification:

<input type="text" onkeyup="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>

<input type="text" onkeyup="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>

Using wire or reg with input or output in Verilog

The Verilog code compiler you use will dictate what you have to do. If you use illegal syntax, you will get a compile error.

An output must also be declared as a reg only if it is assigned using a "procedural assignment". For example:

output reg a;
always @* a = b;

There is no need to declare an output as a wire.

There is no need to declare an input as a wire or reg.

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

    public static IEnumerable<T> GetAllControls<T>(this Control control) where T : Control
    {
        foreach (Control c in control.Controls)
        {
            if (c is T)
                yield return (T)c;
            foreach (T c1 in c.GetAllControls<T>())
                yield return c1;
        }
    }

Python error "ImportError: No module named"

Yup. You need the directory to contain the __init__.py file, which is the file that initializes the package. Here, have a look at this.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

How to manage local vs production settings in Django?

Making multiple versions of settings.py is an anti pattern for 12 Factor App methodology. use python-decouple or django-environ instead.

Spring @Autowired and @Qualifier

You can use @Qualifier along with @Autowired. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier

For Example in following case it is necessary provide a qualifier

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

EDIT:

In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
@RequiredArgsConstructor
public Payroll {
   @Qualifier("employee") private final Person person;
}

provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):

# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier

This was recently introduced in latest lombok 1.18.4.

NOTE

If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)

public Payroll {
   @Autowired @Qualifier("employee") private final Person person;
}

or

public Payroll {
   private final Person person;
   @Autowired
   @Qualifier("employee")
   public void setPerson(Person person) {
     this.person = person;
   } 
}

If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -

public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

How to get the width of a react element

Actually, would be better to isolate this resize logic in a custom hook. You can create a custom hook like this:

const useResize = (myRef) => {
  const [width, setWidth] = useState(0)
  const [height, setHeight] = useState(0)

  useEffect(() => {
    const handleResize = () => {
      setWidth(myRef.current.offsetWidth)
      setHeight(myRef.current.offsetHeight)
    }

    window.addEventListener('resize', handleResize)

    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [myRef])

  return { width, height }
}

and then you can use it like:

const MyComponent = () => {
  const componentRef = useRef()
  const { width, height } = useResize(componentRef)

  return (
    <div ref={myRef}>
      <p>width: {width}px</p>
      <p>height: {height}px</p>
    <div/>
  )
}

Does C# have a String Tokenizer like Java's?

If you are using C# 3.5 you could write an extension method to System.String that does the splitting you need. You then can then use syntax:

string.SplitByMyTokens();

More info and a useful example from MS here http://msdn.microsoft.com/en-us/library/bb383977.aspx

How to SUM and SUBTRACT using SQL?

I have tried this kind of technique. Multiply the subtract from data by (-1) and then sum() the both amount then you will get subtracted amount.

-- Loan Outstanding
    select  'Loan Outstanding' as Particular, sum(Unit), sum(UptoLastYear), sum(ThisYear), sum(UptoThisYear)
    from
    (
        select 
            sum(laod.dr) as Unit,
            sum(if(lao.created_at <= '2014-01-01',laod.dr,0)) as UptoLastYear,
            sum(if(lao.created_at between '2014-01-01' and '2015-07-14',laod.dr,0)) as ThisYear,
            sum(if(lao.created_at <= '2015-07-14',laod.dr,0)) as UptoThisYear
        from loan_account_opening as lao
        inner join loan_account_opening_detail as laod on lao.id=laod.loan_account_opening_id
        where lao.organization = 3
        union
        select
            sum(lr.installment)*-1 as Unit,
            sum(if(lr.created_at <= '2014-01-01',lr.installment,0))*-1 as UptoLastYear,
            sum(if(lr.created_at between '2014-01-01' and '2015-07-14',lr.installment,0))*-1 as ThisYear,
            sum(if(lr.created_at <= '2015-07-14',lr.installment,0))*-1 as UptoThisYear
        from loan_recovery as lr
        inner join loan_account_opening as lo on lr.loan_account_opening_id=lo.id
        where lo.organization = 3
    ) as t3

String Pattern Matching In Java

That's just a matter of String.contains:

if (input.contains("{item}"))

If you need to know where it occurs, you can use indexOf:

int index = input.indexOf("{item}");
if (index != -1) // -1 means "not found"
{
    ...
}

That's fine for matching exact strings - if you need real patterns (e.g. "three digits followed by at most 2 letters A-C") then you should look into regular expressions.

EDIT: Okay, it sounds like you do want regular expressions. You might want something like this:

private static final Pattern URL_PATTERN =
    Pattern.compile("/\\{[a-zA-Z0-9]+\\}/");

...

if (URL_PATTERN.matches(input).find())

Execute a shell function with timeout

if you just want to add timeout as an additional option for the entire existing script, you can make it test for the timeout-option, and then make it call it self recursively without that option.

example.sh:

#!/bin/bash
if [ "$1" == "-t" ]; then
  timeout 1m $0 $2
else
  #the original script
  echo $1
  sleep 2m
  echo YAWN...
fi

running this script without timeout:

$./example.sh -other_option # -other_option
                            # YAWN...

running it with a one minute timeout:

$./example.sh -t -other_option # -other_option

What's the difference between %s and %d in Python string formatting?

Here is the basic example to demonstrate the Python string formatting and a new way to do it.

my_word = 'epic'
my_number = 1

print('The %s number is %d.' % (my_word, my_number))  # traditional substitution with % operator

//The epic number is 1.

print(f'The {my_word} number is {my_number}.')  # newer format string style

//The epic number is 1.

Both prints the same.

Return rows in random order

Here's an example (source):

SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);

Linux : Search for a Particular word in a List of files under a directory

You could club find with exec as follows to get the list of the files as well as the occurrence of the word/string that you are looking for

find . -exec grep "my word" '{}' \; -print

How to get row number from selected rows in Oracle

The below query helps to get the row number in oracle,

SELECT ROWNUM AS SNO,ID,NAME,EMAIL,BRANCH FROM student WHERE NAME LIKE '%ram%';

changing default x range in histogram matplotlib

the following code is for making the same y axis limit on two subplots

f ,ax = plt.subplots(1,2,figsize = (30, 13),gridspec_kw={'width_ratios': [5, 1]})
df.plot(ax = ax[0], linewidth = 2.5)
ylim = [lower_limit,upper_limit]
ax[0].set_ylim(ylim)
ax[1].hist(data,normed =1, bins = num_bin, color = 'yellow' ,alpha = 1) 
ax[1].set_ylim(ylim)

just a reminder, plt.hist(range=[low, high]) the histogram auto crops the range if the specified range is larger than the max&min of the data points. So if you want to specify the y-axis range number, i prefer to use set_ylim

Visual studio code terminal, how to run a command with administrator rights?

Here's what I get.

I'm using Visual Studio Code and its Terminal to execute the 'npm' commands.

Visual Studio Code (not as administrator)
PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator)
Run this command after I've run something like 'ng serve'

PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator - closing and opening the IDE)
If I have already executed other commands that would impact node modules I decided to try closing Visual Studio Code first, opening it up as Administrator then running the command:

PS g:\labs\myproject> npm install bootstrap@3

Result I get then is: + [email protected]
added 115 packages and updated 1 package in 24.685s

This is not a permanent solution since I don't want to continue closing down VS Code every time I want to execute an npm command, but it did resolve the issue to a point.

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

This is an old question with valuable answers, but I was still a bit confused until I found a real life example that shows the issue with 3NF. Maybe not suitable for an 8-year old child but hope it helps.

Tomorrow I'll meet the teachers of my eldest daughter in one of those quarterly parent/teachers meetings. Here's what my diary looks like (names and rooms have been changed):

Teacher   | Date             | Room
----------|------------------|-----
Mr Smith  | 2018-12-18 18:15 | A12 
Mr Jones  | 2018-12-18 18:30 | B10 
Ms Doe    | 2018-12-18 18:45 | C21 
Ms Rogers | 2018-12-18 19:00 | A08 

There's only one teacher per room and they never move. If you have a look, you'll see that: (1) for every attribute Teacher, Date, Room, we have only one value per row. (2) super-keys are: (Teacher, Date, Room), (Teacher, Date) and (Date, Room) and candidate keys are obviously (Teacher, Date) and (Date, Room).

(Teacher, Room) is not a superkey because I will complete the table next quarter and I may have a row like this one (Mr Smith did not move!):

Teacher  | Date             | Room
---------|------------------| ----
Mr Smith | 2019-03-19 18:15 | A12

What can we conclude? (1) is an informal but correct formulation of 1NF. From (2) we see that there is no "non prime attribute": 2NF and 3NF are given for free.

My diary is 3NF. Good! No. Not really because no data modeler would accept this in a DB schema. The Room attribute is dependant on the Teacher attribute (again: teachers do not move!) but the schema does not reflect this fact. What would a sane data modeler do? Split the table in two:

Teacher   | Date
----------|-----------------
Mr Smith  | 2018-12-18 18:15
Mr Jones  | 2018-12-18 18:30
Ms Doe    | 2018-12-18 18:45
Ms Rogers | 2018-12-18 19:00

And

Teacher   | Room
----------|-----
Mr Smith  | A12
Mr Jones  | B10
Ms Doe    | C21
Ms Rogers | A08

But 3NF does not deal with prime attributes dependencies. This is the issue: 3NF compliance is not enough to ensure a sound table schema design under some circumstances.

With BCNF, you don't care if the attribute is a prime attribute or not in 2NF and 3NF rules. For every non trivial dependency (subsets are obviously determined by their supersets), the determinant is a complete super key. In other words, nothing is determined by something else than a complete super key (excluding trivial FDs). (See other answers for formal definition).

As soon as Room depends on Teacher, Room must be a subset of Teacher (that's not the case) or Teacher must be a super key (that's not the case in my diary, but thats the case when you split the table).

To summarize: BNCF is more strict, but in my opinion easier to grasp, than 3NF:

  • in most of cases, BCNF is identical to 3NF;
  • in other cases, BCNF is what you think/hope 3NF is.

Change button text from Xcode?

Yes. There is a method on UIButton -setTitle:forState: use that.

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

The answer was simply moving the PLSQL Developer folder from the "Program Files (x86) into the "Program Files" folder - weird!

Can you animate a height change on a UITableViewCell when selected?

I just resolved this problem with a little hack:

static int s_CellHeight = 30;
static int s_CellHeightEditing = 60;

- (void)onTimer {
    cellHeight++;
    [tableView reloadData];
    if (cellHeight < s_CellHeightEditing)
        heightAnimationTimer = [[NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(onTimer) userInfo:nil repeats:NO] retain];
}

- (CGFloat)tableView:(UITableView *)_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        if (isInEdit) {
            return cellHeight;
        }
        cellHeight = s_CellHeight;
        return s_CellHeight;
}

When I need to expand the cell height I set isInEdit = YES and call the method [self onTimer] and it animates the cell growth until it reach the s_CellHeightEditing value :-)

how to print json data in console.log

This is an old post but I'm chiming in because (as Narem briefly mentioned) a few of the printf-like features are available with the console.log formatters. In the case of the question, you can benefit from the string, number or json formatters for your data.

Examples:

console.log("Quantity %s, Price: %d", data.quantity-row_122, data.price-row_122);
console.log("Quantity and Price Data %j", data);

Maven Install on Mac OS X

Two Method

  • (use homebrew) Auto install:
    • Command:
      • brew install maven
    • Pros and cons
      • Pros: easy
      • Cons: (probably) not latest version
  • Manually install (for latest version):
    • Pros and cons
      • Pros: use your expected any (or latest) version
      • Cons: need self to do it
    • Steps
      • download latest binary (apache-maven-3.6.3-bin.zip) version from Maven offical download
      • uncompress it (apache-maven-3.6.3-bin.zip) and added maven path into environment variable PATH
        • normally is edit and add:
          • export PATH=/path_to_your_maven/apache-maven-3.6.3/bin:$PATH
        • into your startup script( ~/.bashrc or ~/.zshrc etc.)

Extra Note

how to take effect immediately and check installed correctly?

A:

source ~/.bashrc
echo $PATH
which mvn
mvn --version

here output:

?  bin pwd
/Users/crifan/dev/dev_tool/java/maven/apache-maven-3.6.3/bin
?  bin ll
total 64
-rw-r--r--@ 1 crifan  staff   228B 11  7 12:32 m2.conf
-rwxr-xr-x@ 1 crifan  staff   5.6K 11  7 12:32 mvn
-rw-r--r--@ 1 crifan  staff   6.2K 11  7 12:32 mvn.cmd
-rwxr-xr-x@ 1 crifan  staff   1.5K 11  7 12:32 mvnDebug
-rw-r--r--@ 1 crifan  staff   1.6K 11  7 12:32 mvnDebug.cmd
-rwxr-xr-x@ 1 crifan  staff   1.5K 11  7 12:32 mvnyjp
?  bin vi ~/.bashrc
?  bin source ~/.bashrc
?  ~ echo $PATH
/Users/crifan/dev/dev_tool/java/maven/apache-maven-3.6.3/bin:xxx
?  bin which mvn
/Users/crifan/dev/dev_tool/java/maven/apache-maven-3.6.3/bin/mvn
?  bin mvn --version
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /Users/crifan/dev/dev_tool/java/maven/apache-maven-3.6.3
Java version: 1.8.0_112, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: "mac os x", version: "10.14.6", arch: "x86_64", family: "mac"

for full detail please refer my (Chinese) post: ?????Mac???Gradle

Html.DropdownListFor selected value not being set

I know this is not really an answer to the question, but I was looking for a way to initialize the DropDownList from a list on the fly in the view when I kept stumbling upon this post.

My mistake was that I tried to create a SelectList from dictionary like this:

//wrong!
@Html.DropDownListFor(m => m.Locality, new SelectList(new Dictionary<string, string>() { { Model.Locality, Model.Locality_text } }, Model.Locality, ...

I then went digging in the official msdn doc, and found that DropDownListFor doesn't necessarily require a SelectList, but rather an IEnumerable<SelectListItem>:

//right
@Html.DropDownListFor(m => m.Locality, new List<SelectListItem>() { new SelectListItem() { Value = Model.Locality, Text = Model.Locality_text, Selected = true } }, Model.Locality, new { @class = "form-control select2ddl" })

In my case I can probably also omit the Model.Locality as selected item, since its a) the only item and b) it already says it in the SelectListItem.Selected property.

Just in case you're wondering, the datasource is an AJAX page, that gets dynamically loaded using the SelectWoo/Select2 control.

Get filename in batch for loop

I am a little late but I used this:

dir /B *.* > dir_file.txt

then you can make a simple FOR loop to extract the file name and use them. e.g:

for /f "tokens=* delims= " %%a in (dir_file.txt) do (
gawk -f awk_script_file.awk %%a
)

or store them into Vars (!N1!, !N2!..!Nn!) for later use. e.g:

set /a N=0
for /f "tokens=* delims= " %%a in (dir_file.txt) do (
set /a N+=1
set v[!N!]=%%a
)

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

https://fettblog.eu/gulp-4-parallel-and-series/

Because gulp.task(name, deps, func) was replaced by gulp.task(name, gulp.{series|parallel}(deps, func)).

You are using the latest version of gulp but older code. Modify the code or downgrade.

How to use jQuery to get the current value of a file input field

Jquery works differently in IE and other browsers. You can access the last file name by using

alert($('input').attr('value'));

In IE the above alert will give the complete path but in other browsers it will give only the file name.

Get the latest date from grouped MySQL data

This should work:

SELECT model, date FROM doc GROUP BY model ORDER BY date DESC

It just sort the dates from last to first and by grouping it only grabs the first one.

SQL grammar for SELECT MIN(DATE)

SELECT  MIN(Date)  AS Date  FROM tbl_Employee /*To get First date Of Employee*/

Show a div with Fancybox

As far as I know, an input element may not have a href attribute, which is where Fancybox gets its information about the content. The following code uses an a element instead of the input element. Also, this is what I would call the "standard way".

<html>
<head>
  <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script type="text/javascript" src="http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js?v=2.0.5"></script>
  <link rel="stylesheet" type="text/css" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css?v=2.0.5" media="screen" />
</head>
<body>

<a href="#divForm" id="btnForm">Load Form</a>

<div id="divForm" style="display:none">
  <form action="tbd">
    File: <input type="file" /><br /><br />
    <input type="submit" />
  </form>
</div>

<script type="text/javascript">
  $(function(){
    $("#btnForm").fancybox();
  });
</script>

</body>
</html>

See it in action on JSBin

Disable a link in Bootstrap

It seems that Bootstrap doesn't support disabled links. Instead of trying to add a Bootstrap class, you could add a class by your own and add some styling to it, just like this:

_x000D_
_x000D_
a.disabled {_x000D_
  /* Make the disabled links grayish*/_x000D_
  color: gray;_x000D_
  /* And disable the pointer events */_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<!-- Make the disabled links unfocusable as well -->_x000D_
<a href="#" class="disabled" tabindex="-1">Link to disable</a><br/>_x000D_
<a href="#">Non-disabled Link</a>
_x000D_
_x000D_
_x000D_

How to find the width of a div using vanilla JavaScript?

All Answers are right, but i still want to give some other alternatives that may work.

If you are looking for the assigned width (ignoring padding, margin and so on) you could use.

getComputedStyle(element).width; //returns value in px like "727.7px"

getComputedStyle allows you to access all styles of that elements. For example: padding, paddingLeft, margin, border-top-left-radius and so on.

How do I 'foreach' through a two-dimensional array?

Using LINQ you can do it like this:

var table_enum = table

    // Convert to IEnumerable<string>
    .OfType<string>()

    // Create anonymous type where Index1 and Index2
    // reflect the indices of the 2-dim. array
    .Select((_string, _index) => new {
        Index1 = (_index / 2),
        Index2 = (_index % 2), // ? I added this only for completeness
        Value = _string
    })

    // Group by Index1, which generates IEnmurable<string> for all Index1 values
    .GroupBy(v => v.Index1)

    // Convert all Groups of anonymous type to String-Arrays
    .Select(group => group.Select(v => v.Value).ToArray());

// Now you can use the foreach-Loop as you planned
foreach(string[] str_arr in table_enum) {
    // …
}

This way it is also possible to use the foreach for looping through the columns instead of the rows by using Index2 in the GroupBy instead of Index 1. If you don't know the dimension of your array then you have to use the GetLength() method to determine the dimension and use that value in the quotient.

filtering a list using LINQ

Based on http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b,

EqualAll is the approach that best meets your needs.

public void Linq96() 
{ 
    var wordsA = new string[] { "cherry", "apple", "blueberry" }; 
    var wordsB = new string[] { "cherry", "apple", "blueberry" }; 

    bool match = wordsA.SequenceEqual(wordsB); 

    Console.WriteLine("The sequences match: {0}", match); 
} 

Node.js on multi-core machines

You may run your node.js application on multiple cores by using the cluster module on combination with os module which may be used to detect how many CPUs you have.

For example let's imagine that you have a server module that runs simple http server on the backend and you want to run it for several CPUs:

_x000D_
_x000D_
// Dependencies._x000D_
const server = require('./lib/server'); // This is our custom server module._x000D_
const cluster = require('cluster');_x000D_
const os = require('os');_x000D_
_x000D_
 // If we're on the master thread start the forks._x000D_
if (cluster.isMaster) {_x000D_
  // Fork the process._x000D_
  for (let i = 0; i < os.cpus().length; i++) {_x000D_
    cluster.fork();_x000D_
  }_x000D_
} else {_x000D_
  // If we're not on the master thread start the server._x000D_
  server.init();_x000D_
}
_x000D_
_x000D_
_x000D_