Programs & Examples On #Packet mangling

How to find files recursively by file type and copy them to a directory while in ssh?

Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to

find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;

Just to sum up!

No internet on Android emulator - why and how to fix?

Allow the ADB to access the network by opening it on the firewall

If you are using winvista and above, go to Windows Advance Firewall under Administrative tool in Control Panel and enable it from there

Managing large binary files with Git

The solution I'd like to propose is based on orphan branches and a slight abuse of the tag mechanism, henceforth referred to as *Orphan Tags Binary Storage (OTABS)

TL;DR 12-01-2017 If you can use github's LFS or some other 3rd party, by all means you should. If you can't, then read on. Be warned, this solution is a hack and should be treated as such.

Desirable properties of OTABS

  • it is a pure git and git only solution -- it gets the job done without any 3rd party software (like git-annex) or 3rd party infrastructure (like github's LFS).
  • it stores the binary files efficiently, i.e. it doesn't bloat the history of your repository.
  • git pull and git fetch, including git fetch --all are still bandwidth efficient, i.e. not all large binaries are pulled from the remote by default.
  • it works on Windows.
  • it stores everything in a single git repository.
  • it allows for deletion of outdated binaries (unlike bup).

Undesirable properties of OTABS

  • it makes git clone potentially inefficient (but not necessarily, depending on your usage). If you deploy this solution you might have to advice your colleagues to use git clone -b master --single-branch <url> instead of git clone. This is because git clone by default literally clones entire repository, including things you wouldn't normally want to waste your bandwidth on, like unreferenced commits. Taken from SO 4811434.
  • it makes git fetch <remote> --tags bandwidth inefficient, but not necessarily storage inefficient. You can can always advise your colleagues not to use it.
  • you'll have to periodically use a git gc trick to clean your repository from any files you don't want any more.
  • it is not as efficient as bup or git-bigfiles. But it's respectively more suitable for what you're trying to do and more off-the-shelf. You are likely to run into trouble with hundreds of thousands of small files or with files in range of gigabytes, but read on for workarounds.

Adding the Binary Files

Before you start make sure that you've committed all your changes, your working tree is up to date and your index doesn't contain any uncommitted changes. It might be a good idea to push all your local branches to your remote (github etc.) in case any disaster should happen.

  1. Create a new orphan branch. git checkout --orphan binaryStuff will do the trick. This produces a branch that is entirely disconnected from any other branch, and the first commit you'll make in this branch will have no parent, which will make it a root commit.
  2. Clean your index using git rm --cached * .gitignore.
  3. Take a deep breath and delete entire working tree using rm -fr * .gitignore. Internal .git directory will stay untouched, because the * wildcard doesn't match it.
  4. Copy in your VeryBigBinary.exe, or your VeryHeavyDirectory/.
  5. Add it && commit it.
  6. Now it becomes tricky -- if you push it into the remote as a branch all your developers will download it the next time they invoke git fetch clogging their connection. You can avoid this by pushing a tag instead of a branch. This can still impact your colleague's bandwidth and filesystem storage if they have a habit of typing git fetch <remote> --tags, but read on for a workaround. Go ahead and git tag 1.0.0bin
  7. Push your orphan tag git push <remote> 1.0.0bin.
  8. Just so you never push your binary branch by accident, you can delete it git branch -D binaryStuff. Your commit will not be marked for garbage collection, because an orphan tag pointing on it 1.0.0bin is enough to keep it alive.

Checking out the Binary File

  1. How do I (or my colleagues) get the VeryBigBinary.exe checked out into the current working tree? If your current working branch is for example master you can simply git checkout 1.0.0bin -- VeryBigBinary.exe.
  2. This will fail if you don't have the orphan tag 1.0.0bin downloaded, in which case you'll have to git fetch <remote> 1.0.0bin beforehand.
  3. You can add the VeryBigBinary.exe into your master's .gitignore, so that no-one on your team will pollute the main history of the project with the binary by accident.

Completely Deleting the Binary File

If you decide to completely purge VeryBigBinary.exe from your local repository, your remote repository and your colleague's repositories you can just:

  1. Delete the orphan tag on the remote git push <remote> :refs/tags/1.0.0bin
  2. Delete the orphan tag locally (deletes all other unreferenced tags) git tag -l | xargs git tag -d && git fetch --tags. Taken from SO 1841341 with slight modification.
  3. Use a git gc trick to delete your now unreferenced commit locally. git -c gc.reflogExpire=0 -c gc.reflogExpireUnreachable=0 -c gc.rerereresolved=0 -c gc.rerereunresolved=0 -c gc.pruneExpire=now gc "$@". It will also delete all other unreferenced commits. Taken from SO 1904860
  4. If possible, repeat the git gc trick on the remote. It is possible if you're self-hosting your repository and might not be possible with some git providers, like github or in some corporate environments. If you're hosting with a provider that doesn't give you ssh access to the remote just let it be. It is possible that your provider's infrastructure will clean your unreferenced commit in their own sweet time. If you're in a corporate environment you can advice your IT to run a cron job garbage collecting your remote once per week or so. Whether they do or don't will not have any impact on your team in terms of bandwidth and storage, as long as you advise your colleagues to always git clone -b master --single-branch <url> instead of git clone.
  5. All your colleagues who want to get rid of outdated orphan tags need only to apply steps 2-3.
  6. You can then repeat the steps 1-8 of Adding the Binary Files to create a new orphan tag 2.0.0bin. If you're worried about your colleagues typing git fetch <remote> --tags you can actually name it again 1.0.0bin. This will make sure that the next time they fetch all the tags the old 1.0.0bin will be unreferenced and marked for subsequent garbage collection (using step 3). When you try to overwrite a tag on the remote you have to use -f like this: git push -f <remote> <tagname>

Afterword

  • OTABS doesn't touch your master or any other source code/development branches. The commit hashes, all of the history, and small size of these branches is unaffected. If you've already bloated your source code history with binary files you'll have to clean it up as a separate piece of work. This script might be useful.

  • Confirmed to work on Windows with git-bash.

  • It is a good idea to apply a set of standard trics to make storage of binary files more efficient. Frequent running of git gc (without any additional arguments) makes git optimise underlying storage of your files by using binary deltas. However, if your files are unlikely to stay similar from commit to commit you can switch off binary deltas altogether. Additionally, because it makes no sense to compress already compressed or encrypted files, like .zip, .jpg or .crypt, git allows you to switch off compression of the underlying storage. Unfortunately it's an all-or-nothing setting affecting your source code as well.

  • You might want to script up parts of OTABS to allow for quicker usage. In particular, scripting steps 2-3 from Completely Deleting Binary Files into an update git hook could give a compelling but perhaps dangerous semantics to git fetch ("fetch and delete everything that is out of date").

  • You might want to skip the step 4 of Completely Deleting Binary Files to keep a full history of all binary changes on the remote at the cost of the central repository bloat. Local repositories will stay lean over time.

  • In Java world it is possible to combine this solution with maven --offline to create a reproducible offline build stored entirely in your version control (it's easier with maven than with gradle). In Golang world it is feasible to build on this solution to manage your GOPATH instead of go get. In python world it is possible to combine this with virtualenv to produce a self-contained development environment without relying on PyPi servers for every build from scratch.

  • If your binary files change very often, like build artifacts, it might be a good idea to script a solution which stores 5 most recent versions of the artifacts in the orphan tags monday_bin, tuesday_bin, ..., friday_bin, and also an orphan tag for each release 1.7.8bin 2.0.0bin, etc. You can rotate the weekday_bin and delete old binaries daily. This way you get the best of two worlds: you keep the entire history of your source code but only the relevant history of your binary dependencies. It is also very easy to get the binary files for a given tag without getting entire source code with all its history: git init && git remote add <name> <url> && git fetch <name> <tag> should do it for you.

DataAdapter.Fill(Dataset)

it works for me, just change: Provider=Microsoft.Jet.OLEDB.4.0 (VS2013)

OleDbConnection connection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Z:\\GENERAL\\OFMPTP_PD_SG.MDB");
DataSet DS = new DataSet();
connection.Open();

string query =
@"SELECT * from MONTHLYPROD";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection);
DBAdapter.Fill(DS);

Luis Montoya

In Python, can I call the main() of an imported module?

It depends. If the main code is protected by an if as in:

if __name__ == '__main__':
    ...main code...

then no, you can't make Python execute that because you can't influence the automatic variable __name__.

But when all the code is in a function, then might be able to. Try

import myModule

myModule.main()

This works even when the module protects itself with a __all__.

from myModule import * might not make main visible to you, so you really need to import the module itself.

Create unique constraint with null columns

You could create a unique index with a coalesce on the MenuId:

CREATE UNIQUE INDEX
Favorites_UniqueFavorite ON Favorites
(UserId, COALESCE(MenuId, '00000000-0000-0000-0000-000000000000'), RecipeId);

You'd just need to pick a UUID for the COALESCE that will never occur in "real life". You'd probably never see a zero UUID in real life but you could add a CHECK constraint if you are paranoid (and since they really are out to get you...):

alter table Favorites
add constraint check
(MenuId <> '00000000-0000-0000-0000-000000000000')

SQL Server : converting varchar to INT

I would try triming the number to see what you get:

select len(rtrim(ltrim(userid))) from audit

if that return the correct value then just do:

select convert(int, rtrim(ltrim(userid))) from audit

if that doesn't return the correct value then I would do a replace to remove the empty space:

 select convert(int, replace(userid, char(0), '')) from audit

How to set the title of UIButton as left alignment?

Swift 4+

button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

How to remove leading zeros from alphanumeric text?

I think that it is so easy to do that. You can just loop over the string from the start and removing zeros until you found a not zero char.

int lastLeadZeroIndex = 0;
for (int i = 0; i < str.length(); i++) {
  char c = str.charAt(i);
  if (c == '0') {
    lastLeadZeroIndex = i;
  } else {
    break;
  }
}

str = str.subString(lastLeadZeroIndex+1, str.length());

Select element by exact match of its content

An one-liner that works with alternative libraries to jQuery:

$('p').filter((i, p) => $(p).text().trim() === "hello").css('font-weight', 'bold');

And this is the equivalent to a jQuery's a:contains("pattern") selector:

var res = $('a').filter((i, a) => $(a).text().match(/pattern/));

Concatenating Files And Insert New Line In Between Files

If you have few enough files that you can list each one, then you can use process substitution in Bash, inserting a newline between each pair of files:

cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt

Convert Base64 string to an image file?

if($_SERVER['REQUEST_METHOD']=='POST'){
$image_no="5";//or Anything You Need
$image = $_POST['image'];
$path = "uploads/".$image_no.".png";

$status = file_put_contents($path,base64_decode($image));
if($status){
 echo "Successfully Uploaded";
}else{
 echo "Upload failed";
}
}

How to know the version of pip itself

First, open a command prompt After type a bellow commands.

check a version itself Easily :

Form Windows:

pip installation :

pip install pip

pip Version check:

pip --version 

Best /Fastest way to read an Excel Sheet into a DataTable?

''' <summary>
''' ReadToDataTable reads the given Excel file to a datatable.
''' </summary>
''' <param name="table">The table to be populated.</param>
''' <param name="incomingFileName">The file to attempt to read to.</param>
''' <returns>TRUE if success, FALSE otherwise.</returns>
''' <remarks></remarks>
Public Function ReadToDataTable(ByRef table As DataTable,
                                incomingFileName As String) As Boolean
    Dim returnValue As Boolean = False
    Try

        Dim sheetName As String = ""
        Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & incomingFileName & ";Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
        Dim tablesInFile As DataTable
        Dim oleExcelCommand As OleDbCommand
        Dim oleExcelReader As OleDbDataReader
        Dim oleExcelConnection As OleDbConnection

        oleExcelConnection = New OleDbConnection(connectionString)
        oleExcelConnection.Open()

        tablesInFile = oleExcelConnection.GetSchema("Tables")

        If tablesInFile.Rows.Count > 0 Then
            sheetName = tablesInFile.Rows(0)("TABLE_NAME").ToString
        End If

        If sheetName <> "" Then

            oleExcelCommand = oleExcelConnection.CreateCommand()
            oleExcelCommand.CommandText = "Select * From [" & sheetName & "]"
            oleExcelCommand.CommandType = CommandType.Text

            oleExcelReader = oleExcelCommand.ExecuteReader

            'Determine what row of the Excel file we are on
            Dim currentRowIndex As Integer = 0

            While oleExcelReader.Read
                'If we are on the First Row, then add the item as Columns in the DataTable
                If currentRowIndex = 0 Then
                    For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
                        Dim currentColumnName As String = oleExcelReader.Item(currentFieldIndex).ToString
                        table.Columns.Add(currentColumnName, GetType(String))
                        table.AcceptChanges()
                    Next
                End If
                'If we are on a Row with Data, add the data to the SheetTable
                If currentRowIndex > 0 Then
                    Dim newRow As DataRow = table.NewRow
                    For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
                        Dim currentColumnName As String = table.Columns(currentFieldIndex).ColumnName
                        newRow(currentColumnName) = oleExcelReader.Item(currentFieldIndex)
                        If IsDBNull(newRow(currentFieldIndex)) Then
                            newRow(currentFieldIndex) = ""
                        End If
                    Next
                    table.Rows.Add(newRow)
                    table.AcceptChanges()
                End If

                'Increment the CurrentRowIndex
                currentRowIndex += 1
            End While

            oleExcelReader.Close()

        End If

        oleExcelConnection.Close()
        returnValue = True
    Catch ex As Exception
        'LastError = ex.ToString
        Return False
    End Try


    Return returnValue
End Function

How to unstage large number of files without deleting the content

git reset

If all you want is to undo an overzealous "git add" run:

git reset

Your changes will be unstaged and ready for you to re-add as you please.


DO NOT RUN git reset --hard.

It will not only unstage your added files, but will revert any changes you made in your working directory. If you created any new files in working directory, it will not delete them though.

MySQL compare now() (only date, not time) with a datetime field

Compare date only instead of date + time (NOW) with:

CURDATE()

How can I comment a single line in XML?

No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.

XML has only one definition for a comment:

'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'

XML forbids -- in comments to maintain compatibility with SGML.

javac option to compile all java files under a given directory recursively

javac command does not follow a recursive compilation process, so you have either specify each directory when running command, or provide a text file with directories you want to include:

javac -classpath "${CLASSPATH}" @java_sources.txt

How to convert a string to lower case in Bash?

To store the transformed string into a variable. Following worked for me - $SOURCE_NAME to $TARGET_NAME

TARGET_NAME="`echo $SOURCE_NAME | tr '[:upper:]' '[:lower:]'`"

How to convert POJO to JSON and vice versa?

We can also make use of below given dependency and plugin in your pom file - I make use of maven. With the use of these you can generate POJO's as per your JSON Schema and then make use of code given below to populate request JSON object via src object specified as parameter to gson.toJson(Object src) or vice-versa. Look at the code below:

Gson gson = new GsonBuilder().create();
String payloadStr = gson.toJson(data.getMerchant().getStakeholder_list());

Gson gson2 = new Gson();
Error expectederr = gson2.fromJson(payloadStr, Error.class);

And the Maven settings:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>1.7.1</version>
</dependency>

<plugin>
    <groupId>com.googlecode.jsonschema2pojo</groupId>
    <artifactId>jsonschema2pojo-maven-plugin</artifactId>
    <version>0.3.7</version>
    <configuration>
        <sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
        <targetPackage>com.example.types</targetPackage>
    </configuration>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Duplicate Entire MySQL Database

Create a mysqldump file in the system which has the datas and use pipe to give this mysqldump file as an input to the new system. The new system can be connected using ssh command.

mysqldump -u user -p'password' db-name | ssh user@some_far_place.com mysql -u user -p'password' db-name

no space between -p[password]

how to make password textbox value visible when hover an icon

Its simple javascript. Done using toggling the type attribute of the input. Check this http://jsfiddle.net/RZm5y/16/

What is the difference between Cygwin and MinGW?

Cygwin uses a compatibility layer, while MinGW is native. That is one of the main differences.

Node.js: How to send headers with form data using request module?

This should work.

var url = 'http://<your_url_here>';
var headers = { 
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
    'Content-Type' : 'application/x-www-form-urlencoded' 
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};

request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
    // your callback body
});

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

One option seems to be using CSS to style the textarea

.multi-line { height:5em; width:5em; }

See this entry on SO or this one.

Amurra's accepted answer seems to imply this class is added automatically when using EditorFor but you'd have to verify this.

EDIT: Confirmed, it does. So yes, if you want to use EditorFor, using this CSS style does what you're looking for.

<textarea class="text-box multi-line" id="StoreSearchCriteria_Location" name="StoreSearchCriteria.Location">

What is the difference between UTF-8 and ISO-8859-1?

ISO-8859-1 is a legacy standards from back in 1980s. It can only represent 256 characters so only suitable for some languages in western world. Even for many supported languages, some characters are missing. If you create a text file in this encoding and try copy/paste some Chinese characters, you will see weird results. So in other words, don't use it. Unicode has taken over the world and UTF-8 is pretty much the standards these days unless you have some legacy reasons (like HTTP headers which needs to compatible with everything).

How to use a dot "." to access members of dictionary?

The language itself doesn't support this, but sometimes this is still a useful requirement. Besides the Bunch recipe, you can also write a little method which can access a dictionary using a dotted string:

def get_var(input_dict, accessor_string):
    """Gets data from a dictionary using a dotted accessor-string"""
    current_data = input_dict
    for chunk in accessor_string.split('.'):
        current_data = current_data.get(chunk, {})
    return current_data

which would support something like this:

>> test_dict = {'thing': {'spam': 12, 'foo': {'cheeze': 'bar'}}}
>> output = get_var(test_dict, 'thing.spam.foo.cheeze')
>> print output
'bar'
>>

How do I fit an image (img) inside a div and keep the aspect ratio?

Using CSS only:

div > img {
  width: auto;
  height : auto;
  max-height: 100%;
  max-width: 100%;
}

Authentication issue when debugging in VS2013 - iis express

VS 2015 changes this. It added a .vs folder to my web project and the applicationhost.config was in there. I made the changes suggested (window authentication = true, anon=false) and it started delivering a username instead of a blank.

Best practices for adding .gitignore file for Python projects?

When using buildout I have following in .gitignore (along with *.pyo and *.pyc):

.installed.cfg
bin
develop-eggs
dist
downloads
eggs
parts
src/*.egg-info
lib
lib64

Thanks to Jacob Kaplan-Moss

Also I tend to put .svn in since we use several SCM-s where I work.

how to convert String into Date time format in JAVA?

Using this,

        String s = "03/24/2013 21:54";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
        try
        {
            Date date = simpleDateFormat.parse(s);

            System.out.println("date : "+simpleDateFormat.format(date));
        }
        catch (ParseException ex)
        {
            System.out.println("Exception "+ex);
        }

How to shuffle an ArrayList

Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.

What is a tracking branch?

TL;DR Remember, all git branches are themselves used for tracking the history of a set of files. Therefore, isn't every branch actually a "tracking branch", because that's what these branches are used for: to track the history of files over time. Thus we should probably be calling normal git "branches", "tracking-branches", but we don't. Instead we shorten their name to just "branches".

So that's partly why the term "tracking-branches" is so terribly confusing: to the uninitiated it can easily mean 2 different things.

In git the term "Tracking-branch" is a short name for the more complete term: "Remote-tracking-branch".

It's probably better at first if you substitute the more formal terms until you get more comfortable with these concepts.

Let's rephrase your question to this:

What is a "Remote-tracking-branch?"

The key word here is 'Remote', so skip down to where you get confused and I'll describe what a Remote Tracking branch is and how it's used.


To better understand git terminology, including branches and tracking, which can initially be very confusing, I think it's easiest if you first get crystal clear on what git is and the basic structure of how it works. Without a solid understand like this I promise you'll get lost in the many details, as git has lots of complexity; (translation: lots of people use it for very important things).

The following is an introduction/overview, but you might find this excellent article also informative.


WHAT GIT IS, AND WHAT IT'S FOR

A git repository is like a family photo album: It holds historical snapshots showing how things were in past times. A "snapshot" being a recording of something, at a given moment in time.

A git repository is not limited to holding human family photos. It, rather can be used to record and organize anything that is evolving or changing over time.

The basic idea is to create a book so we can easily look backwards in time,

  • to compare past times, with now, or other moments in time, and
  • to re-create the past.

When you get mired down in the complexity and terminology, try to remember that a git repository is first and foremost, a repository of snapshots, and just like a photo album, it's used to both store and organize these snapshots.


SNAPSHOTS AND TRACKING

tracked - to follow a person or animal by looking for proof that they have been somewhere (dictionary.cambridge.org)

In git, "your project" refers to a directory tree of files (one or more, possibly organized into a tree structure using sub-directories), which you wish to keep a history of.

Git, via a 3 step process, records a "snapshot" of your project's directory tree at a given moment in time.

Each git snapshot of your project, is then organized by "links" pointing to previous snapshots of your project.

One by one, link-by-link, we can look backwards in time to find any previous snapshot of you, or your heritage.

For example, we can start with today's most recent snapshot of you, and then using a link, seek backwards in time, for a photo of you taken perhaps yesterday or last week, or when you were a baby, or even who your mother was, etc.

This is refereed to as "tracking; in this example it is tracking your life, or seeing where you have left a footprint, and where you have come from.


COMMITS

A commit is similar to one page in your photo album with a single snapshot, in that its not just the snapshot contained there, but also has the associated meta information about that snapshot. It includes:

  • an address or fixed place where we can find this commit, similar to its page number,
  • one snapshot of your project (of your file directory tree) at a given moment in time,
  • a caption or comment saying what the snapshot is of, or for,
  • the date and time of that snapshot,
  • who took the snapshot, and finally,
  • one, or more, links backwards in time to previous, related snapshots like to yesterday's snapshot, or to our parent or parents. In other words "links" are similar to pointers to the page numbers of other, older photos of myself, or when I am born to my immediate parents.

A commit is the most important part of a well organized photo album.


THE FAMILY TREE OVER TIME, WITH BRANCHES AND MERGES

Disambiguation: "Tree" here refers not to a file directory tree, as used above, but rather to a family tree of related parent and child commits over time.

The git family tree structure is modeled on our own, human family trees.

In what follows to help understand links in a simple way, I'll refer to:

  • a parent-commit as simply a "parent", and
  • a child-commit as simply a "child" or "children" if plural.

You should understand this instinctively, as it is based on the tree of life:

  • A parent might have one or more children pointing back in time at them, and
  • children always have one or more parents they point to.

Thus all commits except brand new commits, (you could say "juvenile commits"), have one or more children pointing back at them.

  • With no children are pointing to a parent, then this commit is only a "growing tip", or where the next child will be born from.

  • With just one child pointing at a parent, this is just a simple, single parent <-- child relationship.

Line diagram of a simple, single parent chain linking backwards in time:

(older) ... <--link1-- Commit1 <--link2-- Commit2 <--link3-- Commit3 (newest)

BRANCHES

branch - A "branch" is an active line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch. A single Git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the "current" or "checked out" branch), and HEAD points to that branch. (gitglossary)

A git branch also refers to two things:

  • a name given to a growing tip, (an identifier), and
  • the actual branch in the graph of links between commits.

More than one child pointing --at a--> parent, is what git calls "branching".

NOTE: In reality any child, of any parent, weather first, second, or third, etc., can be seen as their own little branch, with their own growing tip. So a branch is not necessarily a long thing with many nodes, rather it is a little thing, created with just one or more commits from a given parent.

The first child of a parent might be said to be part of that same branch, whereas the successive children of that parent are what are normally called "branches".

In actuality, all children (not just the first) branch from it's parent, or you could say link, but I would argue that each link is actually the core part of a branch.

Formally, a git "branch" is just a name, like 'foo' for example, given to a specific growing tip of a family hierarchy. It's one type of what they call a "ref". (Tags and remotes which I'll explain later are also refs.)

ref - A name that begins with refs/ (e.g. refs/heads/master) that points to an object name or another ref (the latter is called a symbolic ref). For convenience, a ref can sometimes be abbreviated when used as an argument to a Git command; see gitrevisions(7) for details. Refs are stored in the repository.

The ref namespace is hierarchical. Different subhierarchies are used for different purposes (e.g. the refs/heads/ hierarchy is used to represent local branches). There are a few special-purpose refs that do not begin with refs/. The most notable example is HEAD. (gitglossary)

(You should take a look at the file tree inside your .git directory. It's where the structure of git is saved.)

So for example, if your name is Tom, then commits linked together that only include snapshots of you, might be the branch we name "Tom".

So while you might think of a tree branch as all of it's wood, in git a branch is just a name given to it's growing tips, not to the whole stick of wood leading up to it.

The special growing tip and it's branch which an arborist (a guy who prunes fruit trees) would call the "central leader" is what git calls "master".

The master branch always exists.

Line diagram of: Commit1 with 2 children (or what we call a git "branch"):

                parent      children

                        +-- Commit <-- Commit <-- Commit (Branch named 'Tom')
                       /
                      v
(older) ... <-- Commit1 <-- Commit                       (Branch named 'master')    

Remember, a link only points from child to parent. There is no link pointing the other way, i.e. from old to new, that is from parent to child.

So a parent-commit has no direct way to list it's children-commits, or in other words, what was derived from it.


MERGING

Children have one or more parents.

  • With just one parent this is just a simple parent <-- child commit.

  • With more than one parent this is what git calls "merging". Each child can point back to more than one parent at the same time, just as in having both a mother AND father, not just a mother.

Line diagram of: Commit2 with 2 parents (or what we call a git "merge", i.e. Procreation from multiple parents):

                parents     child

           ... <-- Commit
                        v
                         \
(older) ... <-- Commit1 <-- Commit2  

REMOTE

This word is also used to mean 2 different things:

  • a remote repository, and
  • the local alias name for a remote repository, i.e. a name which points using a URL to a remote repository.

remote repository - A repository which is used to track the same project but resides somewhere else. To communicate with remotes, see fetch or push. (gitglossary)

(The remote repository can even be another git repository on our own computer.) Actually there are two URLS for each remote name, one for pushing (i.e. uploading commits) and one for pulling (i.e. downloading commits) from that remote git repository.

A "remote" is a name (an identifier) which has an associated URL which points to a remote git repository. (It's been described as an alias for a URL, although it's more than that.)

You can setup multiple remotes if you want to pull or push to multiple remote repositories.

Though often you have just one, and it's default name is "origin" (meaning the upstream origin from where you cloned).

origin - The default upstream repository. Most projects have at least one upstream project which they track. By default origin is used for that purpose. New upstream updates will be fetched into remote-tracking branches named origin/name-of-upstream-branch, which you can see using git branch -r. (gitglossary)

Origin represents where you cloned the repository from.
That remote repository is called the "upstream" repository, and your cloned repository is called the "downstream" repository.

upstream - In software development, upstream refers to a direction toward the original authors or maintainers of software that is distributed as source code wikipedia

upstream branch - The default branch that is merged into the branch in question (or the branch in question is rebased onto). It is configured via branch..remote and branch..merge. If the upstream branch of A is origin/B sometimes we say "A is tracking origin/B". (gitglossary)

This is because most of the water generally flows down to you.
From time to time you might push some software back up to the upstream repository, so it can then flow down to all who have cloned it.

REMOTE TRACKING BRANCH

A remote-tracking-branch is first, just a branch name, like any other branch name.

It points at a local growing tip, i.e. a recent commit in your local git repository.

But note that it effectively also points to the same commit in the remote repository that you cloned the commit from.

remote-tracking branch - A ref that is used to follow changes from another repository. It typically looks like refs/remotes/foo/bar (indicating that it tracks a branch named bar in a remote named foo), and matches the right-hand-side of a configured fetch refspec. A remote-tracking branch should not contain direct modifications or have local commits made to it. (gitglossary)

Say the remote you cloned just has 2 commits, like this: parent42 <== child-of-4, and you clone it and now your local git repository has the same exact two commits: parent4 <== child-of-4.
Your remote tracking branch named origin now points to child-of-4.

Now say that a commit is added to the remote, so it looks like this: parent42 <== child-of-4 <== new-baby. To update your local, downstream repository you'll need to fetch new-baby, and add it to your local git repository. Now your local remote-tracking-branch points to new-baby. You get the idea, the concept of a remote-tracking-branch is simply to keep track of what had previously been the tip of a remote branch that you care about.


TRACKING IN ACTION

First we begin tracking a file with git.

enter image description here

Here are the basic commands involved with file tracking:

$ mkdir mydir &&  cd mydir &&  git init             # create a new git repository

$ git branch                                        # this initially reports no branches
                                                    #  (IMHO this is a bug!)

$ git status -bs       # -b = branch; -s = short    # master branch is empty
## No commits yet on master

# ...
$ touch foo                                         # create a new file

$ vim foo                                           # modify it (OPTIONAL)


$ git add         foo; commit -m 'your description'  # start tracking foo 
$ git rm  --index foo; commit -m 'your description'  # stop  tracking foo 
$ git rm          foo; commit -m 'your description'  # stop  tracking foo & also delete foo

REMOTE TRACKING IN ACTION

$ git pull    # Essentially does:  get fetch; git merge    # to update our clone

There is much more to learn about fetch, merge, etc, but this should get you off in the right direction I hope.

PHP - Notice: Undefined index:

For starters,

mysql_connect() should not have a $ accompanying it; it is not a variable, it is a predefined function. Remove the $ to properly connect to the database.

Why do you have an XML tag at the top of this document? This is HTML/PHP - a HTML doctype should suffice.

From line 215, update:

if (isset($_POST)) {
    $Name = $_POST['Name'];
    $Surname = $_POST['Surname'];

    $Username = $_POST['Username'];

    $Email = $_POST['Email'];
    $C_Email = $_POST['C_Email'];

    $Password = $_POST['password'];
    $C_Password = $_POST['c_password'];

    $SecQ = $_POST['SecQ'];
    $SecA = $_POST['SecA'];
}

POST variables are coming from your form, and you have to check whether they exist or not, else PHP will give you a NOTICE error. You can disable these notices by placing error_reporting(0); at the top of your document. It's best to keep these visible for development purposes.

You should only be interacting with the database (inserting, checking) under the condition that the form has been submitted. If you do not, PHP will run all of these operations without any input from the user. Its best to use an IF statement, like so:

if (isset($_POST['submit']) {
// blah blah
// check if user exists, check if fields are blank
// insert the user if all of this stuff checks out..
} else {
// just display the form
}

Awesome form tutorial: http://php.about.com/od/learnphp/ss/php_forms.htm

How to have comments in IntelliSense for function in Visual Studio?

Solmead has the correct answer. For more info you can look at XML Comments.

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

A completely alternative solution is to not use the MVC HandleErrorAttribute, and instead rely on ASP.Net error handling, which Elmah is designed to work with.

You need to remove the default global HandleErrorAttribute from App_Start\FilterConfig (or Global.asax), and then set up an error page in your Web.config:

<customErrors mode="RemoteOnly" defaultRedirect="~/error/" />

Note, this can be an MVC routed URL, so the above would redirect to the ErrorController.Index action when an error occurs.

explode string in jquery

What is row?

Either of these could be correct.

1) I assume that you capture your ajax response in a javascript variable 'row'. If that is the case, this would hold true.

var result=row.split('|');
    alert(result[2]);

otherwise

2) Use this where $(row) is a jQuery object.

var result=$(row).val().split('|');
    alert(result[2]);

[As mentioned in the other answer, you may have to use $(row).val() or $(row).text() or $(row).html() etc. depending on what $(row) is.]

Android checkbox style

The correct way to do it for Material design is :

Style :

<style name="MyCheckBox" parent="Theme.AppCompat.Light">  
    <item name="colorControlNormal">@color/foo</item>
    <item name="colorControlActivated">@color/bar</item>
</style>  

Layout :

<CheckBox  
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Check Box"
    android:theme="@style/MyCheckBox"/>

It will preserve Material animations on Lollipop+.

How to count frequency of characters in a string?

There is one more option and it looks quite nice. Since java 8 there is new method merge java doc

  public static void main(String[] args) {
    String s = "aaabbbcca";

    Map<Character, Integer> freqMap = new HashMap<>();
    for (int i = 0; i < s.length(); i++) {
        Character c = s.charAt(i);
        freqMap.merge(c, 1, (a, b) -> a + b);
    }
    freqMap.forEach((k, v) -> System.out.println(k + " and " + v));
}

Or even cleaner with ForEach

       for (Character c : s.toCharArray()) {
            freqMapSecond.merge(c, 1, Integer::sum);
           }

How do you programmatically set an attribute?

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

Server unable to read htaccess file, denying access to be safe

"Server unable to read htaccess file" means just that. Make sure that the permissions on your .htaccess file are world-readable.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

Just to complete the other answers, I would like to quote Effective Java, 2nd Edition, by Joshua Bloch, chapter 10, Item 68 :

"Choosing the executor service for a particular application can be tricky. If you’re writing a small program, or a lightly loaded server, using Executors.new- CachedThreadPool is generally a good choice, as it demands no configuration and generally “does the right thing.” But a cached thread pool is not a good choice for a heavily loaded production server!

In a cached thread pool, submitted tasks are not queued but immediately handed off to a thread for execution. If no threads are available, a new one is created. If a server is so heavily loaded that all of its CPUs are fully utilized, and more tasks arrive, more threads will be created, which will only make matters worse.

Therefore, in a heavily loaded production server, you are much better off using Executors.newFixedThreadPool, which gives you a pool with a fixed number of threads, or using the ThreadPoolExecutor class directly, for maximum control."

How do you create a Spring MVC project in Eclipse?

Download Spring STS (SpringSource Tool Suite) and choose Spring Template Project from the Dashboard. This is the easiest way to get a preconfigured spring mvc project, ready to go.

How to deep merge instead of shallow merge?

There is a lodash package which specifically deals only with deep cloning a object. The advantage is that you don't have to include the entire lodash library.

Its called lodash.clonedeep

In nodejs the usage is like this

var cloneDeep = require('lodash.clonedeep');
 
const newObject = cloneDeep(oldObject);

In ReactJS the usage is

import cloneDeep from 'lodash/cloneDeep';

const newObject = cloneDeep(oldObject);

Check the docs here . If you are interested in how it works take a look at the source file here

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

Found one more way of doing it

 if let parameters = route.parameters {

                    for (key, value) in parameters {
                         if value is String {
                            if let temp = value as? String {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if value is NSArray {
                            if let temp = value as? [Double]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                            else if let temp = value as? [Int]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                            else if let temp = value as? [String]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if CFGetTypeID(value as CFTypeRef) == CFNumberGetTypeID() {
                            if let temp = value as? Int {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID(){
                            if let temp = value as? Bool {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                    }
                }

                if let items: [MultipartData] = route.multipartData{
                    for item in items {
                        if let value = item.value{
                            multipartFormData.append(value, withName: item.key, fileName: item.fileName, mimeType: item.mimeType)
                        }
                    }
                }

Multiline strings in VB.NET

If you need an XML literal in VB.Net with an line code variable, this is how you would do it:

<Tag><%= New XCData(T.Property) %></Tag>

java.util.zip.ZipException: error in opening zip file

Make sure your jar file is not corrupted. If it's corrupted or not able to unzip, this error will occur.

How do I get the IP address into a batch-file variable?

This work even if you have a virtual network adapters or VPN connections:

FOR /F "tokens=4 delims= " %%i in ('route print ^| find " 0.0.0.0"') do set localIp=%%i
echo Your IP Address is: %localIp%

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

Can I use Twitter Bootstrap and jQuery UI at the same time?

Although this question specifically mentions jQuery-UI autosuggest feature, the question title is more general: does bootstrap 3 work with jQuery UI? I was having trouble with the jQUI datepicker (pop-up calendar) feature. I solved the datepicker problem and hope the solution will help with other jQUI/BS issues.

I had a difficult time today getting the latest jQueryUI (ver 1.12.1) datepicker to work with bootstrap 3.3.7. What was happening is that the calendar would display but it would not close.

Turned out to be a version problem with jQUI and BS. I was using the latest version of Bootstrap, and found that I had to downgrade to these versions of jQUI and jQuery:

jQueryUI - 1.9.2 (tested - works)
jQuery - 1.9.1 or 2.1.4 (tested - both work. Other vers may work, but these work.)
Bootstrap 3.3.7 (tested - works)

Because I wanted to use a custom theme, I also built a custom download of jQUI (removed a few things like all the interactions, dialog, progressbar and a few effects I don't use) -- and made sure to select "Cupertino" at the bottom as my theme.

I installed them thus:

<head>
...etc...
<link rel="stylesheet" href="css/font-awesome.min.css">
<link rel="stylesheet" href="css/cupertino/jquery-ui-1.9.2.custom.min.css">
<link rel="stylesheet" href="css/bootstrap-3.3.7.min.css">

<!-- <script src="js/jquery-1.9.1.min.js"></script> -->
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/jquery-ui-1.9.2.custom.min.js"></script>
<script src="js/bootstrap-3.3.7.min.js"></script>
...etc...
</head>

For those interested, the CSS folder looks like this:

[css]
  - bootstrap-3.3.7.min.css
  - font-awesome.min.css
  - style.css
  - [cupertino]
      - jquery-ui-1.9.2.custom.min.css
      [images]
          - ui-bg_diagonals-thick_90_eeeeee_40x40.png
          - ui-bg_glass_100_e4f1fb_1x400.png
          - ui-bg_glass_50_3baae3_1x400.png
          - ui-bg_glass_80_d7ebf9_1x400.png
          - ui-bg_highlight-hard_100_f2f5f7_1x100.png
          - etc (8 more files that were in the downloaded jQUI zip file)

How do I connect to a specific Wi-Fi network in Android programmatically?

I broke my head to understand why your answers for WPA/WPA2 don't work...after hours of tries I found what you are missing:

conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

is REQUIRED for WPA networks!!!!

Now, it works :)

Error in Process.Start() -- The system cannot find the file specified

I had the same problem, but none of the solutions worked for me, because the message The system cannot find the file specified can be misleading in some special cases.

In my case, I use Notepad++ in combination with the registry redirect for notepad.exe. Unfortunately my path to Notepad++ in the registry was wrong.

So in fact the message The system cannot find the file specified was telling me, that it cannot find the application (Notepad++) associated with the file type(*.txt), not the file itself.

Global Variable from a different file Python

When you write

from file2 import *

it actually copies the names defined in file2 into the namespace of file1. So if you reassign those names in file1, by writing

foo = "bar"

for example, it will only make that change in file1, not file2. Note that if you were to change an attribute of foo, say by doing

foo.blah = "bar"

then that change would be reflected in file2, because you are modifying the existing object referred to by the name foo, not replacing it with a new object.

You can get the effect you want by doing this in file1.py:

import file2
file2.foo = "bar"
test = SomeClass()

(note that you should delete from foo import *) although I would suggest thinking carefully about whether you really need to do this. It's not very common that changing one module's variables from within another module is really justified.

creating a random number using MYSQL

You could create a random number using FLOOR(RAND() * n) as randnum (n is an integer), however if you do not need the same random number to be repeated then you will have to somewhat store in a temp table. So you can check it against with where randnum not in (select * from temptable)...

Fill username and password using selenium in python

In some cases when the element is not interactable, sendKeys() doesn't work and you're likely to encounter an ElementNotInteractableException.

In such cases, you can opt to execute javascript that sets the values and then can post back.

Example:

url = 'https://www.your_url.com/'

driver = Chrome(executable_path="./chromedriver")
driver.get(url)

username = 'your_username'
password = 'your_password'

#Setting the value of email input field
driver.execute_script(f'var element = document.getElementById("email"); element.value = "{username}";')

#Setting the value of password input field
driver.execute_script(f'var element = document.getElementById("password"); element.value = "{password}";')

#Submitting the form or click the login button also
driver.execute_script(f'document.getElementsByClassName("login_form")[0].submit();')

print(driver.page_source)

Reference:

https://www.quora.com/How-do-I-resolve-the-ElementNotInteractableException-in-Selenium-WebDriver

Insert multiple values using INSERT INTO (SQL Server 2005)

In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.

 INSERT INTO TableName ( Column1, Column2 ) VALUES
    ( Value1, Value2 ), ( Value1, Value2 )

Another way

INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2

How to center images on a web page for all screen sizes

In your specific case, you can set the containing a element to be:

a {
    display: block;
    text-align: center;
}

JS Bin demo.

How do I query between two dates using MySQL?

Might be a problem with date configuration on server side or on client side. I've found this to be a common problem on multiple databases when the host is configured in spanish, french or whatever... that could affect the format dd/mm/yyyy or mm/dd/yyyy.

Create dynamic variable name

C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuickTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> names = new Dictionary<string,int>();


            for (int i = 0; i < 10; i++)
            {
                names.Add(String.Format("name{0}", i.ToString()), i);
            }

            var xx1 = names["name1"];
            var xx2 = names["name2"];
            var xx3 = names["name3"];
        }
    }
}

How to hide a View programmatically?

You can call view.setVisibility(View.GONE) if you want to remove it from the layout.

Or view.setVisibility(View.INVISIBLE) if you just want to hide it.

From Android Docs:

INVISIBLE

This view is invisible, but it still takes up space for layout purposes. Use with setVisibility(int) and android:visibility.

GONE

This view is invisible, and it doesn't take any space for layout purposes. Use with setVisibility(int) and android:visibility.

Matching special characters and letters in regex

let pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*]{6,16}$/;

//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format

let reee =pattern .test("helLo123@");   //true as it contains all the above

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

Adjust the sequence of your environment variable %path% to make sure jre 1.7 is the default one.

What is a 'multi-part identifier' and why can't it be bound?

I was getting this error and just could not see where the problem was. I double checked all of my aliases and syntax and nothing looked out of place. The query was similar to ones I write all the time.

I decided to just re-write the query (I originally had copied it from a report .rdl file) below, over again, and it ran fine. Looking at the queries now, they look the same to me, but my re-written one works.

Just wanted to say that it might be worth a shot if nothing else works.

Checking if any elements in one list are in another

You could solve this many ways. One that is pretty simple to understand is to just use a loop.

def comp(list1, list2):
    for val in list1:
        if val in list2:
            return True
    return False

A more compact way you can do it is to use map and reduce:

reduce(lambda v1,v2: v1 or v2, map(lambda v: v in list2, list1))

Even better, the reduce can be replaced with any:

any(map(lambda v: v in list2, list1))

You could also use sets:

len(set(list1).intersection(list2)) > 0

Git push requires username and password

If you are using Git (for example, Git Bash) under Windows (and if you don't want to switch from HTTPS to SSH), you could also use Git Credential Manager for Windows

This application will keep the username and password for you...

CSS vertical alignment of inline/inline-block elements

Simply floating both elements left achieves the same result.

div {
background:yellow;
vertical-align:middle;
margin:10px;
}

a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
float:left;
}

span {
background:red;
display:inline-block;
float:left;
}

Corrupt jar file

This regularly occurs when you change the extension on the JAR for ZIP, extract the zip content and make some modifications on files such as changing the MANIFEST.MF file which is a very common case, many times Eclipse doesn't generate the MANIFEST file as we want, or maybe we would like to modify the CLASS-PATH or the MAIN-CLASS values of it.

The problem occurs when you zip back the folder.

A valid Runnable/Executable JAR has the next structure:

myJAR (Main-Directory)
    |-META-INF (Mandatory)
             |-MANIFEST.MF (Mandatory Main-class: com.MainClass)
    |-com 
         |-MainClass.class (must to implement the main method, mandatory)
    |-properties files (optional)
    |-etc (optional)

If your JAR complies with these rules it will work doesn't matter if you build it manually by using a ZIP tool and then you changed the extension back to .jar

Once you're done try execute it on the command line using:

java -jar myJAR.jar 

When you use a zip tool to unpack, change files and zip again, normally the JAR structure changes to this structure which is incorrect, since another directory level is added on the top of the file system making it a corrupted file as is shown below:

**myJAR (Main-Directory)
    |-myJAR (creates another directory making the file corrupted)**
          |-META-INF (Mandatory)
                   |-MANIFEST.MF (Mandatory Main-class: com.MainClass)
          |-com 
              |-MainClass.class (must to implement the main method, mandatory)
          |-properties files (optional)
          |-etc (optional)

:)

add new row in gridview after binding C#, ASP.net

try using the cloning technique.

{
    DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
    // then for each of the values use a loop like below.
    int cc = yourdatagrid.Columns.Count;
    for (int i2 = 0; i < cc; i2++)
    {
        row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
    }
    yourdatagrid.Rows.Add(row);
    i++;
    }
}

This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.

AES Encrypt and Decrypt

Update Swift 4.2

Here, for instance, we encrypt a string to base64encoded string. And then we decrypt the same to a readable string. (That would be same as our input string).

In my case, I use this to encrypt a string and embed that to QR Code. Then another party scan that and decrypt the same. So intermediate won't understand the QR codes.

Step 1: Encrypt a string "Encrypt My Message 123"

Step 2: Encrypted base64Encoded string : +yvNjiD7F9/JKmqHTc/Mjg== (The same printed on QR code)

Step 3: Scan and decrypt the string "+yvNjiD7F9/JKmqHTc/Mjg=="

Step 4: It comes final result - "Encrypt My Message 123"

Functions for Encrypt & Decrypt

func encryption(stringToEncrypt: String) -> String{
    let key = "MySecretPKey"
    //let iv = "92c9d2c07a9f2e0a"
    let data = stringToEncrypt.data(using: .utf8)
    let keyD = key.data(using: .utf8)
    let encr = (data as NSData?)!.aes128EncryptedData(withKey: keyD)
    let base64String: String = (encr as NSData?)!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
    print(base64String)
    return base64String
}

func decryption(encryptedString:String) -> String{
    let key = "MySecretPKey"
    //let iv = "92c9d2c07a9f2e0a"
    let keyD = key.data(using: .utf8)
    let decrpStr = NSData(base64Encoded: encryptedString, options: NSData.Base64DecodingOptions(rawValue: 0))
    let dec = (decrpStr)!.aes128DecryptedData(withKey: keyD)
    let backToString = String(data: dec!, encoding: String.Encoding.utf8)
    print(backToString!)
    return backToString!
}

Usage:

    let enc = encryption(stringToEncrypt: "Encrypt My Message 123")
    let decryptedString = decryption(encryptedString: enc)
    print(decryptedString) 

Classes for supporting AES encrypting functions, these are written in Objective-C. So for swift, you need to use bridge header to support these.

Class Name: NSData+AES.h

#import <Foundation/Foundation.h>

@interface NSData (AES)

- (NSData *)AES128EncryptedDataWithKey:(NSData *)key;
- (NSData *)AES128DecryptedDataWithKey:(NSData *)key;
- (NSData *)AES128EncryptedDataWithKey:(NSData *)key iv:(NSData *)iv;
- (NSData *)AES128DecryptedDataWithKey:(NSData *)key iv:(NSData *)iv;

@end

Class Name: NSData+AES.m

#import "NSData+AES.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation NSData (AES)

- (NSData *)AES128EncryptedDataWithKey:(NSData *)key
{
    return [self AES128EncryptedDataWithKey:key iv:nil];
}

- (NSData *)AES128DecryptedDataWithKey:(NSData *)key
{
    return [self AES128DecryptedDataWithKey:key iv:nil];
}

- (NSData *)AES128EncryptedDataWithKey:(NSData *)key iv:(NSData *)iv
{
    return [self AES128Operation:kCCEncrypt key:key iv:iv];
}

- (NSData *)AES128DecryptedDataWithKey:(NSData *)key iv:(NSData *)iv
{
    return [self AES128Operation:kCCDecrypt key:key iv:iv];
}

- (NSData *)AES128Operation:(CCOperation)operation key:(NSData *)key iv:(NSData *)iv
{

    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          key.bytes,
                                          kCCBlockSizeAES128,
                                          iv.bytes,
                                          [self bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
}

@end

I hope that helps.

Thanks!!!

Using port number in Windows host file

  1. Install Redirector
  2. Click Edit redirects -> Create New Redirect

enter image description here

How set the android:gravity to TextView from Java side in Android

We can set layout gravity on any view like below way-

myView = findViewById(R.id.myView);
myView.setGravity(Gravity.CENTER_VERTICAL|Gravity.RIGHT);
 or
myView.setGravity(Gravity.BOTTOM);

This is equilent to below xml code

<...
 android:gravity="center_vertical|right"
 ...
 .../>

Sublime Text 3, convert spaces to tabs

Use the following command to get it solved :

autopep8 -i <filename>.py

Java random numbers using a seed

Several of the examples here create a new Random instance, but this is unnecessary. There is also no reason to use synchronized as one solution does. Instead, take advantage of the methods on the ThreadLocalRandom class:

double randomGenerator() {
    return ThreadLocalRandom.current().nextDouble(0.5);
}

Why do I need to configure the SQL dialect of a data source?

The dialect in the Hibernate context, will take care of database data type, like in orace it is integer however in SQL it is int, so this will by known in hibernate by this property, how to map the fields internally.

DataTable, How to conditionally delete rows

Here's a one-liner using LINQ and avoiding any run-time evaluation of select strings:

someDataTable.Rows.Cast<DataRow>().Where(
    r => r.ItemArray[0] == someValue).ToList().ForEach(r => r.Delete());

Get first key in a (possibly) associative array?

This could also be a solution:

$yourArray = array('first_key'=> 'First', 2, 3, 4, 5);
$first_key = current(array_flip($yourArray));
echo $first_key;

I have tested it and it works.

Working Code.

How do I uninstall a Windows service if the files do not exist anymore?

1st Step : Move to the Directory where your service is present

Command : cd c:\xxx\yyy\service

2nd Step : Enter the below command

Command : C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe service.exe \u

Here service.exe is your service exe and \u will uninstall the service. you'll see "The uninstall has completed" message.

If you wanna install a service, Remove \u in the above command which will install your service

Calling C/C++ from Python?

There is also pybind11, which is like a lightweight version of Boost.Python and compatible with all modern C++ compilers:

https://pybind11.readthedocs.io/en/latest/

JSTL if tag for equal strings

<c:if test="${ansokanInfo.pSystem eq 'NAT'}">

Pass a data.frame column name to a function

As an extra thought, if is needed to pass the column name unquoted to the custom function, perhaps match.call() could be useful as well in this case, as an alternative to deparse(substitute()):

df <- data.frame(A = 1:10, B = 2:11)

fun <- function(x, column){
  arg <- match.call()
  max(x[[arg$column]])
}

fun(df, A)
#> [1] 10

fun(df, B)
#> [1] 11

If there is a typo in the column name, then would be safer to stop with an error:

fun <- function(x, column) max(x[[match.call()$column]])
fun(df, typo)
#> Warning in max(x[[match.call()$column]]): no non-missing arguments to max;
#> returning -Inf
#> [1] -Inf

# Stop with error in case of typo
fun <- function(x, column){
  arg <- match.call()
  if (is.null(x[[arg$column]])) stop("Wrong column name")
  max(x[[arg$column]])
}

fun(df, typo)
#> Error in fun(df, typo): Wrong column name
fun(df, A)
#> [1] 10

Created on 2019-01-11 by the reprex package (v0.2.1)

I do not think I would use this approach since there is extra typing and complexity than just passing the quoted column name as pointed in the above answers, but well, is an approach.

MySQL compare DATE string with string from DATETIME field

You can cast the DATETIME field into DATE as:

SELECT * FROM `calendar` WHERE CAST(startTime AS DATE) = '2010-04-29'

This is very much efficient.

Overlay a background-image with an rgba background-color

I've gotten the following to work:

html {
  background:
      linear-gradient(rgba(0,184,255,0.45),rgba(0,184,255,0.45)),
      url('bgimage.jpg') no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

The above will produce a nice opaque blue overlay.

How to check if the request is an AJAX request with PHP

This function is using in yii framework for ajax call check.

public function isAjax() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}

How to convert a JSON string to a Map<String, String> with Jackson JSON

Here is the generic solution to this problem.

public static <K extends Object, V extends Object> Map<K, V> getJsonAsMap(String json, K key, V value) {
    try {
      ObjectMapper mapper = new ObjectMapper();
      TypeReference<Map<K, V>> typeRef = new TypeReference<Map<K, V>>() {
      };
      return mapper.readValue(json, typeRef);
    } catch (Exception e) {
      throw new RuntimeException("Couldnt parse json:" + json, e);
    }
  }

Hope someday somebody would think to create a util method to convert to any Key/value type of Map hence this answer :)

How to listen for a WebView finishing loading a URL?

The renderer will not finish rendering when the OnPageFinshed method is called or the progress reaches 100% so both methods don't guarantee you that the view was completely rendered.

But you can figure out from OnLoadResource method what has been already rendered and what is still rendering. And this method gets called several times.

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
           // Log and see all the urls and know exactly what is being rendered and visible. If you wanna know when the entire page is completely rendered, find the last url from log and check it with if clause and implement your logic there.
            if (url.contains("assets/loginpage/img/ui/forms/")) {
                // loginpage is rendered and visible now.
               // your logic here.

            }
        }

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Setting format and value in input type="date"

new Date().toISOString().split('T')[0];

How to start and stop android service from a adb shell?

You may get an error "*Error: app is in background *" while using

adb shell am startservice 

in Oreo (26+). This requires services in the foreground. Use the following.

adb shell am start-foreground-service com.some.package.name/.YourServiceSubClassName

Convert Pandas DataFrame to JSON format

Try this one:

json.dumps(json.loads(df.to_json(orient="records")))

How to display a "busy" indicator with jQuery?

I did it in my project:

Global Events in application.js:

$(document).bind("ajaxSend", function(){
   $("#loading").show();
 }).bind("ajaxComplete", function(){
   $("#loading").hide();
 });

"loading" is the element to show and hide!

References: http://api.jquery.com/Ajax_Events/

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

jQuery get specific option tag text

You can get one of following ways

$("#list").find('option').filter('[value=2]').text()

$("#list").find('option[value=2]').text()

$("#list").children('option[value=2]').text()

$("#list option[value='2']").text()

_x000D_
_x000D_
$(function(){    _x000D_
    _x000D_
    console.log($("#list").find('option').filter('[value=2]').text());_x000D_
    console.log($("#list").find('option[value=2]').text());_x000D_
    console.log($("#list").children('option[value=2]').text());_x000D_
    console.log($("#list option[value='2']").text());_x000D_
    _x000D_
});
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<select id='list'>_x000D_
    <option value='1'>Option A</option>_x000D_
    <option value='2'>Option B</option>_x000D_
    <option value='3'>Option C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

VBA to copy a file from one directory to another

This method is even easier if you're ok with fewer options:

FileCopy source, destination

How do I send a cross-domain POST request via JavaScript?

  1. Create an iFrame,
  2. put a form in it with Hidden inputs,
  3. set the form's action to the URL,
  4. Add iframe to document
  5. submit the form

Pseudocode

 var ifr = document.createElement('iframe');
 var frm = document.createElement('form');
 frm.setAttribute("action", "yoururl");
 frm.setAttribute("method", "post");

 // create hidden inputs, add them
 // not shown, but similar (create, setAttribute, appendChild)

 ifr.appendChild(frm);
 document.body.appendChild(ifr);
 frm.submit();

You probably want to style the iframe, to be hidden and absolutely positioned. Not sure cross site posting will be allowed by the browser, but if so, this is how to do it.

Counting array elements in Perl

Maybe you want a hash instead (or in addition). Arrays are an ordered set of elements; if you create $foo[23], you implicitly create $foo[0] through $foo[22].

LEFT function in Oracle

LEFT is not a function in Oracle. This probably came from someone familiar with SQL Server:

Returns the left part of a character string with the specified number of characters.

-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse  
LEFT ( character_expression , integer_expression )  

How to convert an array to object in PHP?

I would definitly go with a clean way like this :

<?php

class Person {

  private $name;
  private $age;
  private $sexe;

  function __construct ($payload)
  {
     if (is_array($payload))
          $this->from_array($payload);
  }


  public function from_array($array)
  {
     foreach(get_object_vars($this) as $attrName => $attrValue)
        $this->{$attrName} = $array[$attrName];
  }

  public function say_hi ()
  {
     print "hi my name is {$this->name}";
  }
}

print_r($_POST);
$mike = new Person($_POST);
$mike->say_hi();

?>

if you submit:

formulaire

you will get this:

mike

I found this more logical comparing the above answers from Objects should be used for the purpose they've been made for (encapsulated cute little objects).

Also using get_object_vars ensure that no extra attributes are created in the manipulated Object (you don't want a car having a family name, nor a person behaving 4 wheels).

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

Try using anaconda. I had the same error. One lone option was to build tensorflow from source which took long time. I tried using conda and it worked.

  1. Create a new environment in anaconda.
  2. conda -c conda-forge tensorflow

Then, it worked.

PHP preg replace only allow numbers

You could also use T-Regx library:

pattern('\D')->remove($c)

T-Regx also:

  • Throws exceptions on fail (not false, null or warnings)
  • Has automatic delimiters (delimiters are not required!)
  • Has a lot cleaner api

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

If you use cell.imageView?.translatesAutoresizingMaskIntoConstraints = false you can set constraints on the imageView. Here's a working example I used in a project. I avoided subclassing and didn't need to create storyboard with prototype cells but did take me quite a while to get running, so probably best to only use if there isn't a simpler or more concise way available to you.

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 80
}



    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: String(describing: ChangesRequiringApprovalTableViewController.self))

    let record = records[indexPath.row]

    cell.textLabel?.text = "Title text"

    if let thumb = record["thumbnail"] as? CKAsset, let image = UIImage(contentsOfFile: thumb.fileURL.path) {
        cell.imageView?.contentMode = .scaleAspectFill
        cell.imageView?.image = image
        cell.imageView?.translatesAutoresizingMaskIntoConstraints = false
        cell.imageView?.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor).isActive = true
        cell.imageView?.widthAnchor.constraint(equalToConstant: 80).rowHeight).isActive = true
        cell.imageView?.heightAnchor.constraint(equalToConstant: 80).isActive = true
        if let textLabel = cell.textLabel {
            let margins = cell.contentView.layoutMarginsGuide
            textLabel.translatesAutoresizingMaskIntoConstraints = false
            cell.imageView?.trailingAnchor.constraint(equalTo: textLabel.leadingAnchor, constant: -8).isActive = true
            textLabel.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
            textLabel.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
            let bottomConstraint = textLabel.bottomAnchor.constraint(equalTo: margins.bottomAnchor)
            bottomConstraint.priority = UILayoutPriorityDefaultHigh
            bottomConstraint.isActive = true
            if let description = cell.detailTextLabel {
                description.translatesAutoresizingMaskIntoConstraints = false
                description.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
                description.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
                cell.imageView?.trailingAnchor.constraint(equalTo: description.leadingAnchor, constant: -8).isActive = true
                textLabel.bottomAnchor.constraint(equalTo: description.topAnchor).isActive = true
            }
        }
        cell.imageView?.clipsToBounds = true
    }

    cell.detailTextLabel?.text = "Detail Text"

    return cell
}

Add support library to Android Studio project

In Android Studio 1.0, this worked for me :-
Open the build.gradle (Module : app) file and paste this (at the end) :-

dependencies {
    compile "com.android.support:appcompat-v7:21.0.+"
}

Note that this dependencies is different from the dependencies inside buildscript in build.gradle (Project)
When you edit the gradle file, a message shows that you must sync the file. Press "Sync now"

Source : https://developer.android.com/tools/support-library/setup.html#add-library

How do I print colored output with Python 3?

Since Python is interpreted and run in C, it is possible to set colors without a module.

You can define a class for colors like this:

class color:
   PURPLE = '\033[1;35;48m'
   CYAN = '\033[1;36;48m'
   BOLD = '\033[1;37;48m'
   BLUE = '\033[1;34;48m'
   GREEN = '\033[1;32;48m'
   YELLOW = '\033[1;33;48m'
   RED = '\033[1;31;48m'
   BLACK = '\033[1;30;48m'
   UNDERLINE = '\033[4;37;48m'
   END = '\033[1;37;0m'

When writing code, you can simply write:

print(color.BLUE + "hello friends" + color.END)

Note that the color you choose will have to be capitalized like your class definition, and that these are color choices that I personally find satisfying. For a fuller array of color choices and, indeed, background choices as well, please see: https://gist.github.com/RabaDabaDoba/145049536f815903c79944599c6f952a.

This is code for C, but can easily be adapted to Python once you realize how the code is written.

Take BLUE for example, since that is what you are wanting to display.

BLUE = '033[1;37;48m'

\033 tells Python to break and pay attention to the following formatting.

1 informs the code to be bold. (I prefer 1 to 0 because it pops more.)

34 is the actual color code. It chooses blue.

48m is the background color. 48m is the same shade as the console window, so it seems there is no background.

Center Triangle at Bottom of Div

You could also use a CSS "calc" to get the same effect instead of using the negative margin or transform properties (in case you want to use those properties for anything else).

.hero:after,
.hero:after {
    z-index: -1;
    position: absolute;
    top: 98.1%;
    left: calc(50% - 25px);
    content: '';
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

R Markdown - changing font size and font type in html output

To change the font size, you don't need to know a lot of html for this. Open the html output with notepad ++. Control F search for "font-size". You should see a section with font sizes for the headers (h1, h2, h3,...).

Add the following somewhere in this section.

body {
  font-size: 16px;
}

The font size above is 16 pt font. You can change the number to whatever you want.

How can I create a dynamically sized array of structs?

If you want to dynamically allocate arrays, you can use malloc from stdlib.h.

If you want to allocate an array of 100 elements using your words struct, try the following:

words* array = (words*)malloc(sizeof(words) * 100);

The size of the memory that you want to allocate is passed into malloc and then it will return a pointer of type void (void*). In most cases you'll probably want to cast it to the pointer type you desire, which in this case is words*.

The sizeof keyword is used here to find out the size of the words struct, then that size is multiplied by the number of elements you want to allocate.

Once you are done, be sure to use free() to free up the heap memory you used in order to prevent memory leaks:

free(array);

If you want to change the size of the allocated array, you can try to use realloc as others have mentioned, but keep in mind that if you do many reallocs you may end up fragmenting the memory. If you want to dynamically resize the array in order to keep a low memory footprint for your program, it may be better to not do too many reallocs.

How to convert int to NSString?

NSString *string = [NSString stringWithFormat:@"%d", theinteger];

How to create a generic array?

You should not mix-up arrays and generics. They don't go well together. There are differences in how arrays and generic types enforce the type check. We say that arrays are reified, but generics are not. As a result of this, you see these differences working with arrays and generics.

Arrays are covariant, Generics are not:

What that means? You must be knowing by now that the following assignment is valid:

Object[] arr = new String[10];

Basically, an Object[] is a super type of String[], because Object is a super type of String. This is not true with generics. So, the following declaration is not valid, and won't compile:

List<Object> list = new ArrayList<String>(); // Will not compile.

Reason being, generics are invariant.

Enforcing Type Check:

Generics were introduced in Java to enforce stronger type check at compile time. As such, generic types don't have any type information at runtime due to type erasure. So, a List<String> has a static type of List<String> but a dynamic type of List.

However, arrays carry with them the runtime type information of the component type. At runtime, arrays use Array Store check to check whether you are inserting elements compatible with actual array type. So, the following code:

Object[] arr = new String[10];
arr[0] = new Integer(10);

will compile fine, but will fail at runtime, as a result of ArrayStoreCheck. With generics, this is not possible, as the compiler will try to prevent the runtime exception by providing compile time check, by avoiding creation of reference like this, as shown above.

So, what's the issue with Generic Array Creation?

Creation of array whose component type is either a type parameter, a concrete parameterized type or a bounded wildcard parameterized type, is type-unsafe.

Consider the code as below:

public <T> T[] getArray(int size) {
    T[] arr = new T[size];  // Suppose this was allowed for the time being.
    return arr;
}

Since the type of T is not known at runtime, the array created is actually an Object[]. So the above method at runtime will look like:

public Object[] getArray(int size) {
    Object[] arr = new Object[size];
    return arr;
}

Now, suppose you call this method as:

Integer[] arr = getArray(10);

Here's the problem. You have just assigned an Object[] to a reference of Integer[]. The above code will compile fine, but will fail at runtime.

That is why generic array creation is forbidden.

Why typecasting new Object[10] to E[] works?

Now your last doubt, why the below code works:

E[] elements = (E[]) new Object[10];

The above code have the same implications as explained above. If you notice, the compiler would be giving you an Unchecked Cast Warning there, as you are typecasting to an array of unknown component type. That means, the cast may fail at runtime. For e.g, if you have that code in the above method:

public <T> T[] getArray(int size) {
    T[] arr = (T[])new Object[size];        
    return arr;
}

and you call invoke it like this:

String[] arr = getArray(10);

this will fail at runtime with a ClassCastException. So, no this way will not work always.

What about creating an array of type List<String>[]?

The issue is the same. Due to type erasure, a List<String>[] is nothing but a List[]. So, had the creation of such arrays allowed, let's see what could happen:

List<String>[] strlistarr = new List<String>[10];  // Won't compile. but just consider it
Object[] objarr = strlistarr;    // this will be fine
objarr[0] = new ArrayList<Integer>(); // This should fail but succeeds.

Now the ArrayStoreCheck in the above case will succeed at runtime although that should have thrown an ArrayStoreException. That's because both List<String>[] and List<Integer>[] are compiled to List[] at runtime.

So can we create array of unbounded wildcard parameterized types?

Yes. The reason being, a List<?> is a reifiable type. And that makes sense, as there is no type associated at all. So there is nothing to loose as a result of type erasure. So, it is perfectly type-safe to create an array of such type.

List<?>[] listArr = new List<?>[10];
listArr[0] = new ArrayList<String>();  // Fine.
listArr[1] = new ArrayList<Integer>(); // Fine

Both the above case is fine, because List<?> is super type of all the instantiation of the generic type List<E>. So, it won't issue an ArrayStoreException at runtime. The case is same with raw types array. As raw types are also reifiable types, you can create an array List[].

So, it goes like, you can only create an array of reifiable types, but not non-reifiable types. Note that, in all the above cases, declaration of array is fine, it's the creation of array with new operator, which gives issues. But, there is no point in declaring an array of those reference types, as they can't point to anything but null (Ignoring the unbounded types).

Is there any workaround for E[]?

Yes, you can create the array using Array#newInstance() method:

public <E> E[] getArray(Class<E> clazz, int size) {
    @SuppressWarnings("unchecked")
    E[] arr = (E[]) Array.newInstance(clazz, size);

    return arr;
}

Typecast is needed because that method returns an Object. But you can be sure that it's a safe cast. So, you can even use @SuppressWarnings on that variable.

CREATE TABLE LIKE A1 as A2

CREATE TABLE new_table LIKE old_table;

or u can use this

CREATE TABLE new_table as SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by];

How to get old Value with onchange() event in text box

Maybe you can store the previous value of the textbox into a hidden textbox. Then you can get the first value from hidden and the last value from textbox itself. An alternative related to this, at onfocus event of your textbox set the value of your textbox to an hidden field and at onchange event read the previous value.

SQL Server: Importing database from .mdf?

To perform this operation see the next images:

enter image description here

and next step is add *.mdf file,

very important, the .mdf file must be located in C:......\MSSQL12.SQLEXPRESS\MSSQL\DATA

enter image description here

Now remove the log file

enter image description here

Check if the number is integer

I am not sure what you are trying to accomplish. But here are some thoughts:
1. Convert to integer:
num = as.integer(123.2342)
2. Check if a variable is an integer:
is.integer(num)
typeof(num)=="integer"

Select top 2 rows in Hive

select * from employee_list order by salary desc limit 2;

How to get default gateway in Mac OSX

For getting the list of ip addresses associated, you can use netstat command

netstat -rn 

This gives a long list of ip addresses and it is not easy to find the required field. The sample result is as following:

Routing tables
Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            192.168.195.1      UGSc           17        0     en2
127                127.0.0.1          UCS             0        0     lo0
127.0.0.1          127.0.0.1          UH              1   254107     lo0
169.254            link#7             UCS             0        0     en2
192.168.195        link#7             UCS             3        0     en2
192.168.195.1      0:27:22:67:35:ee   UHLWIi         22      397     en2   1193
192.168.195.5      127.0.0.1          UHS             0        0     lo0

More result is truncated.......

The ip address of gateway is in the first line; one with default at its first column.

To display only the selected lines of result, we can use grep command along with netstat

netstat -rn | grep 'default'

This command filters and displays those lines of result having default. In this case, you can see result like following:

default            192.168.195.1      UGSc           14        0     en2

If you are interested in finding only the ip address of gateway and nothing else you can further filter the result using awk. The awk command matches pattern in the input result and displays the output. This can be useful when you are using your result directly in some program or batch job.

netstat -rn | grep 'default' | awk '{print $2}'

The awk command tells to match and print the second column of the result in the text. The final result thus looks like this:

192.168.195.1

In this case, netstat displays all result, grep only selects the line with 'default' in it, and awk further matches the pattern to display the second column in the text.

You can similarly use route -n get default command to get the required result. The full command is

route -n get default | grep 'gateway' | awk '{print $2}'

These commands work well in linux as well as unix systems and MAC OS.

ValidateRequest="false" doesn't work in Asp.Net 4

This works without changing the validation mode.

You have to use a System.Web.Helpers.Validation.Unvalidated helper from System.Web.WebPages.dll. It is going to return a UnvalidatedRequestValues object which allows to access the form and QueryString without validation.

For example,

var queryValue = Server.UrlDecode(Request.Unvalidated("MyQueryKey"));

Works for me for MVC3 and .NET 4.

What does "both" mean in <div style="clear:both">

Clear:both gives you that space between them.

For example your code:

  <div style="float:left">Hello</div>
  <div style="float:right">Howdy dere pardner</div>

Will currently display as :

Hello  ...................   Howdy dere pardner

If you add the following to above snippet,

  <div style="clear:both"></div>

In between them it will display as:

Hello ................ 
                       Howdy dere pardner

giving you that space between hello and Howdy dere pardner.

Js fiiddle http://jsfiddle.net/Qk5vR/1/

Override devise registrations controller

In your form are you passing in any other attributes, via mass assignment that don't belong to your user model, or any of the nested models?

If so, I believe the ActiveRecord::UnknownAttributeError is triggered in this instance.

Otherwise, I think you can just create your own controller, by generating something like this:

# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def new
    super
  end

  def create
    # add custom create logic here
  end

  def update
    super
  end
end 

And then tell devise to use that controller instead of the default with:

# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}

How to use XPath preceding-sibling correctly

You don't need to go level up and use .. since all buttons are on the same level:

//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']

SELECT last id, without INSERT

I have different solution:

SELECT AUTO_INCREMENT - 1 as CurrentId FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbname' AND TABLE_NAME = 'tablename'

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

This line seems to sum up the crux of your problem:

The issue with this is that now you can't call any new methods (only overrides) on the implementing class, as your object reference variable has the interface type.

You are pretty stuck in your current implementation, as not only do you have to attempt a cast, you also need the definition of the method(s) that you want to call on this subclass. I see two options:

1. As stated elsewhere, you cannot use the String representation of the Class name to cast your reflected instance to a known type. You can, however, use a String equals() test to determine whether your class is of the type that you want, and then perform a hard-coded cast:

try {
   String className = "com.path.to.ImplementationType";// really passed in from config
   Class c = Class.forName(className);
   InterfaceType interfaceType = (InterfaceType)c.newInstance();
   if (className.equals("com.path.to.ImplementationType") {
      ((ImplementationType)interfaceType).doSomethingOnlyICanDo();
   } 
} catch (Exception e) {
   e.printStackTrace();
}

This looks pretty ugly, and it ruins the nice config-driven process that you have. I dont suggest you do this, it is just an example.

2. Another option you have is to extend your reflection from just Class/Object creation to include Method reflection. If you can create the Class from a String passed in from a config file, you can also pass in a method name from that config file and, via reflection, get an instance of the Method itself from your Class object. You can then call invoke(http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object, java.lang.Object...)) on the Method, passing in the instance of your class that you created. I think this will help you get what you are after.

Here is some code to serve as an example. Note that I have taken the liberty of hard coding the params for the methods. You could specify them in a config as well, and would need to reflect on their class names to define their Class obejcts and instances.

public class Foo {

    public void printAMessage() {
    System.out.println(toString()+":a message");
    }
    public void printAnotherMessage(String theString) {
        System.out.println(toString()+":another message:" + theString);
    }

    public static void main(String[] args) {
        Class c = null;
        try {
            c = Class.forName("Foo");
            Method method1 = c.getDeclaredMethod("printAMessage", new Class[]{});
            Method method2 = c.getDeclaredMethod("printAnotherMessage", new Class[]{String.class});
            Object o = c.newInstance();
            System.out.println("this is my instance:" + o.toString());
            method1.invoke(o);
            method2.invoke(o, "this is my message, from a config file, of course");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException nsme){
            nsme.printStackTrace();
        } catch (IllegalAccessException iae) {
            iae.printStackTrace();
        } catch (InstantiationException ie) {
            ie.printStackTrace();
        } catch (InvocationTargetException ite) {
            ite.printStackTrace();
        }
    }
}

and my output:

this is my instance:Foo@e0cf70
Foo@e0cf70:a message
Foo@e0cf70:another message:this is my message, from a config file, of course

Docker-Compose can't connect to Docker Daemon

From the output of "ps aux | grep docker", it looks like docker daemon is not running. Try using below methods to see what is wrong and why docker is not starting

  1. Check the docker logs

$ sudo tail -f /var/log/upstart/docker.log

  1. Try starting docker in debug mode

$ sudo docker -d -D

Excluding files/directories from Gulp task

Quick answer

On src, you can always specify files to ignore using "!".

Example (you want to exclude all *.min.js files on your js folder and subfolder:

gulp.src(['js/**/*.js', '!js/**/*.min.js'])

You can do it as well for individual files.

Expanded answer:

Extracted from gulp documentation:

gulp.src(globs[, options])

Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.

glob refers to node-glob syntax or it can be a direct file path.

So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.

On minimatch documentation, they point out the following:

if the pattern starts with a ! character, then it is negated.

And that is why using ! symbol will exclude files / directories from a gulp task

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

Considering that in most cases you don't want your entire data contract to have types supplied, but only those which are containing an abstract or interface, or list thereof; and also considering these instances are very rare and easily identifiable within your data entities, the easiest and least verbose way is to use

[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Objects)]
public IEnumerable<ISomeInterface> Items { get; set; }

as attribute on your property containing the enumerable/list/collection. This will target only that list, and only append type information for the contained objects, like this:

{
  "Items": [
    {
      "$type": "Namespace.ClassA, Assembly",
      "Property": "Value"
    },
    {
      "$type": "Namespace.ClassB, Assembly",
      "Property": "Value",
      "Additional_ClassB_Property": 3
    }
  ]
}

Clean, simple, and located where the complexity of your data model is introduced, instead of hidden away in some converter.

Hunk #1 FAILED at 1. What's that mean?

Debugging Tips

  1. Add crlf to the end of the patch file and test if it works
  2. try the --ignore-whitespace command like in: markus@ubuntu:~$ patch -Np1 --ignore-whitespace -d software-1.0 < fix-bug.patch see tutorial by markus

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

Below command worked for me docker build -t docker-whale -f Dockerfile.txt .

Random color generator

var color = "#";
for (k = 0; k < 3; k++) {
    color += ("0" + (Math.random()*256|0).toString(16)).substr(-2);
}

A breakdown of how this works:

Math.random()*256 gets a random (floating point) number from 0 to 256 (0 to 255 inclusive)
Example result: 116.15200161933899

Adding the |0 strips off everything after the decimal point.
Ex: 116.15200161933899 -> 116

Using .toString(16) converts this number to hexadecimal (base 16).
Ex: 116 -> 74
Another ex: 228 -> e4

Adding "0" pads it with a zero. This will be important when we get the substring, since our final result must have two characters for each color.
Ex: 74 -> 074
Another ex: 8 -> 08

.substr(-2) gets just the last two characters.
Ex: 074 -> 74
Another ex: 08 -> 08 (if we hadn't added the "0", this would have produced "8" instead of "08")

The for loop runs this loop three times, adding each result to the color string, producing something like this:
#7408e4

Bootstrap onClick button event

There is no show event in js - you need to bind your button either to the click event:

$('#id').on('click', function (e) {

     //your awesome code here

})

Mind that if your button is inside a form, you may prefer to bind the whole form to the submit event.

URL encoding in Android

you can use below methods

public static String parseUrl(String surl) throws Exception
{
    URL u = new URL(surl);
    return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}

or

public String parseURL(String url, Map<String, String> params)
{
    Builder builder = Uri.parse(url).buildUpon();
    for (String key : params.keySet())
    {
        builder.appendQueryParameter(key, params.get(key));
    }
    return builder.build().toString();
}

the second one is better than first.

How to display HTML in TextView?

Simply use:

String variable="StackOverflow";
textView.setText(Html.fromHtml("<b>Hello : </b>"+ variable));

Shell command to tar directory excluding certain files/folders

Use the find command in conjunction with the tar append (-r) option. This way you can add files to an existing tar in a single step, instead of a two pass solution (create list of files, create tar).

find /dir/dir -prune ... -o etc etc.... -exec tar rvf ~/tarfile.tar {} \;

How to extract filename.tar.gz file

As far as I can tell, the command is correct, ASSUMING your input file is a valid gzipped tar file. Your output says that it isn't. If you downloaded the file from the internet, you probably didn't get the entire file, try again.

Without more knowledge of the source of your file, nobody here is going to be able to give you a concrete solution, just educated guesses.

Java NIO FileChannel versus FileOutputstream performance / usefulness

My experience is, that NIO is much faster with small files. But when it comes to large files FileInputStream/FileOutputStream is much faster.

CSS content property: is it possible to insert HTML instead of Text?

It is not possible prolly cuz it would be so easy to XSS. Also , current HTML sanitizers that are available don't disallow content property.

(Definitely not the greatest answer here but I just wanted to share an insight other than the "according to spec... ")

Is it valid to have a html form inside another html form?

In case someone find this post here is a great solution without the need of JS. Use two submit buttons with different name attributes check in your server language which submit button was pressed cause only one of them will be sent to the server.

<form method="post" action="ServerFileToExecute.php">
    <input type="submit" name="save" value="Click here to save" />
    <input type="submit" name="delete" value="Click here to delete" />
</form>

The server side could look something like this if you use php:

<?php
    if(isset($_POST['save']))
        echo "Stored!";
    else if(isset($_POST['delete']))
        echo "Deleted!";
    else
        echo "Action is missing!";
?>

How can I get the IP address from NIC in Python?

This will gather all IPs on the host and filter out loopback/link-local and IPv6. This can also be edited to allow for IPv6 only, or both IPv4 and IPv6, as well as allowing loopback/link-local in IP list.

from socket import getaddrinfo, gethostname
import ipaddress

def get_ip(ip_addr_proto="ipv4", ignore_local_ips=True):
    # By default, this method only returns non-local IPv4 Addresses
    # To return IPv6 only, call get_ip('ipv6')
    # To return both IPv4 and IPv6, call get_ip('both')
    # To return local IPs, call get_ip(None, False)
    # Can combime options like so get_ip('both', False)

    af_inet = 2
    if ip_addr_proto == "ipv6":
        af_inet = 30
    elif ip_addr_proto == "both":
        af_inet = 0

    system_ip_list = getaddrinfo(gethostname(), None, af_inet, 1, 0)
    ip_list = []

    for ip in system_ip_list:
        ip = ip[4][0]

        try:
            ipaddress.ip_address(str(ip))
            ip_address_valid = True
        except ValueError:
            ip_address_valid = False
        else:
            if ipaddress.ip_address(ip).is_loopback and ignore_local_ips or ipaddress.ip_address(ip).is_link_local and ignore_local_ips:
                pass
            elif ip_address_valid:
                ip_list.append(ip)

    return ip_list

print(f"Your IP Address is: {get_ip()}")

Returns Your IP Address is: ['192.168.1.118']

If I run get_ip('both', False), it returns

Your IP Address is: ['::1', 'fe80::1', '127.0.0.1', '192.168.1.118', 'fe80::cb9:d2dd:a505:423a']

How to set Spring profile from system variable?

I normally configure the applicationContext using Annotation based configuration rather than XML based configuration. Anyway, I believe both of them have the same priority.

*Answering your question, system variable has higher priority *


Getting profile based beans from applicationContext

  • Use @Profile on a Bean

@Component
@Profile("dev")
public class DatasourceConfigForDev

Now, the profile is dev

Note : if the Profile is given as @Profile("!dev") then the profile will exclude dev and be for all others.

  • Use profiles attribute in XML

<beans profile="dev">
    <bean id="DatasourceConfigForDev" class="org.skoolguy.profiles.DatasourceConfigForDev"/>
</beans>

Set the value for profile:

  • Programmatically via WebApplicationInitializer interface

    In web applications, WebApplicationInitializer can be used to configure the ServletContext programmatically
@Configuration
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
            servletContext.setInitParameter("spring.profiles.active", "dev");
    }
}
  • Programmatically via ConfigurableEnvironment

    You can also set profiles directly on the environment:
    @Autowired
    private ConfigurableEnvironment env;

    // ...

    env.setActiveProfiles("dev");
  • Context Parameter in web.xml

    profiles can be activated in the web.xml of the web application as well, using a context parameter:
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-config.xml</param-value>
    </context-param>
    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>dev</param-value>
    </context-param>
  • JVM System Parameter

    The profile names passed as the parameter will be activated during application start-up:

    -Dspring.profiles.active=dev
    

    In IDEs, you can set the environment variables and values to use when an application runs. The following is the Run Configuration in Eclipse:

Eclipse Run Configuration - screenshot is unavailable

  • Environment Variable

    to set via command line : export spring_profiles_active=dev

Any bean that does not specify a profile belongs to “default” profile.


The priority order is :

  1. Context parameter in web.xml
  2. WebApplicationInitializer
  3. JVM System parameter
  4. Environment variable

unexpected T_VARIABLE, expecting T_FUNCTION

You can not put

$connection = sqlite_open("[path]/data/users.sqlite", 0666);

outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.

How to delete or add column in SQLITE?

http://www.sqlite.org/lang_altertable.html

As you can see in the diagram, only ADD COLUMN is supported. There is a (kinda heavy) workaround, though: http://www.sqlite.org/faq.html#q11

Best practices for copying files with Maven

A generic way to copy arbitrary files is to utilize Maven Wagon transport abstraction. It can handle various destinations via protocols like file, HTTP, FTP, SCP or WebDAV.

There are a few plugins that provide facilities to copy files through the use of Wagon. Most notable are:

  • Out-of-the-box Maven Deploy Plugin

    There is the deploy-file goal. It it quite inflexible but can get the job done:

    mvn deploy:deploy-file -Dfile=/path/to/your/file.ext -DgroupId=foo 
    -DartifactId=bar -Dversion=1.0 -Durl=<url> -DgeneratePom=false
    

    Significant disadvantage to using Maven Deploy Plugin is that it is designated to work with Maven repositories. It assumes particular structure and metadata. You can see that the file is placed under foo/bar/1.0/file-1.0.ext and checksum files are created. There is no way around this.

  • Wagon Maven Plugin

    Use the upload-single goal:

    mvn org.codehaus.mojo:wagon-maven-plugin:upload-single
    -Dwagon.fromFile=/path/to/your/file.ext -Dwagon.url=<url>
    

    The use of Wagon Maven Plugin for copying is straightforward and seems to be the most versatile.


In the examples above <url> can be of any supported protocol. See the list of existing Wagon Providers. For example

  • copying file locally: file:///copy/to
  • copying file to remote host running SSH: scp://host:22/copy/to


The examples above pass plugin parameters in the command line. Alternatively, plugins can be configured directly in POM. Then the invocation will simply be like mvn deploy:deploy-file@configured-execution-id. Or it can be bound to particular build phase.


Please note that for protocols like SCP to work you will need to define an extension in your POM:

<build>
  [...]
  <extensions>
    <extension>
      <groupId>org.apache.maven.wagon</groupId>
      <artifactId>wagon-ssh</artifactId>
      <version>2.12</version>
    </extension>
  </extensions>


If the destination you are copying to requires authentication, credentials can be provided via Server settings. repositoryId/serverId passed to the plugins must match the server defined in the settings.

Count lines in large files

Hadoop is essentially providing a mechanism to perform something similar to what @Ivella is suggesting.

Hadoop's HDFS (Distributed file system) is going to take your 20GB file and save it across the cluster in blocks of a fixed size. Lets say you configure the block size to be 128MB, the file would be split into 20x8x128MB blocks.

You would then run a map reduce program over this data, essentially counting the lines for each block (in the map stage) and then reducing these block line counts into a final line count for the entire file.

As for performance, in general the bigger your cluster, the better the performance (more wc's running in parallel, over more independent disks), but there is some overhead in job orchestration that means that running the job on smaller files will not actually yield quicker throughput than running a local wc

Code snippet or shortcut to create a constructor in Visual Studio

Type the name of any code snippet and press TAB.

To get code for properties you need to choose the correct option and press TAB twice because Visual Studio has more than one option which starts with 'prop', like 'prop', 'propa', and 'propdp'.

How to grant permission to users for a directory using command line in Windows?

in windows 10 working without "c:>" and ">"

For example:

F = Full Control
/e : Edit permission and kept old permission
/p : Set new permission

cacls "file or folder path" /e /p UserName:F

(also this fixes error 2502 and 2503)

cacls "C:\Windows\Temp" /e /p UserName:F

How to remove all non-alpha numeric characters from a string in MySQL?

Straight and battletested solution for latin and cyrillic characters:

DELIMITER //

CREATE FUNCTION `remove_non_numeric_and_letters`(input TEXT)
  RETURNS TEXT
  BEGIN
    DECLARE output TEXT DEFAULT '';
    DECLARE iterator INT DEFAULT 1;
    WHILE iterator < (LENGTH(input) + 1) DO
      IF SUBSTRING(input, iterator, 1) IN
         ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')
      THEN
        SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
      END IF;
      SET iterator = iterator + 1;
    END WHILE;
    RETURN output;
  END //

DELIMITER ;

Usage:

-- outputs "hello12356"
SELECT remove_non_numeric_and_letters('hello - 12356-?????? ""]')

System.Drawing.Image to stream C#

Try the following:

public static Stream ToStream(this Image image, ImageFormat format) {
  var stream = new System.IO.MemoryStream();
  image.Save(stream, format);
  stream.Position = 0;
  return stream;
}

Then you can use the following:

var stream = myImage.ToStream(ImageFormat.Gif);

Replace GIF with whatever format is appropriate for your scenario.

What does a bitwise shift (left or right) do and what is it used for?

The bit shift operators are more efficient as compared to the / or * operators.

In computer architecture, divide(/) or multiply(*) take more than one time unit and register to compute result, while, bit shift operator, is just one one register and one time unit computation.

Mysql Compare two datetime fields

Do you want to order it?

Select * From temp where mydate > '2009-06-29 04:00:44' ORDER BY mydate;

Letsencrypt add domain to existing certificate

You need to specify all of the names, including those already registered.

I used the following command originally to register some certificates:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--email [email protected] \
--expand -d example.com,www.example.com

... and just now I successfully used the following command to expand my registration to include a new subdomain as a SAN:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--expand -d example.com,www.example.com,click.example.com

From the documentation:

--expand "If an existing cert covers some subset of the requested names, always expand and replace it with the additional names."

Don't forget to restart the server to load the new certificates if you are running nginx.

How to Disable GUI Button in Java

Is there a reason you are not doing something like:

public class IPGUI extends JFrame implements ActionListener 
{
    private static JPanel contentPane;

    private JButton btnConvertDocuments;
    private JButton btnExtractImages;
    private JButton btnParseRIDValues;
    private JButton btnParseImageInfo;

    public IPGUI() 
    {
        ...

        btnConvertDocuments = new JButton("1. Convert Documents");

        ...

        btnExtractImages = new JButton("2. Extract Images");

        ...

        //etc.
    }

    public void actionPerformed(ActionEvent event) 
    {
        String command = event.getActionCommand();

        if (command.equals("w"))
        {
            FileConverter fc = new FileConverter();
            btnConvertDocuments.setEnabled( false );
        }
        else if (command.equals("x"))
        {
            ImageExtractor ie = new ImageExtractor();
            btnExtractImages.setEnabled( false );
        }

        // etc.
    }    
}

The if statement with your disabling code won't get called unless you keep calling the IPGUI constructor.

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

I suppose your dictMap is of type HashMap, which makes it default to HashMap<Object, Object>. If you want it to be more specific, declare it as HashMap<String, ArrayList>, or even better, as HashMap<String, ArrayList<T>>

how to create a cookie and add to http response from inside my service layer?

To add a new cookie, use HttpServletResponse.addCookie(Cookie). The Cookie is pretty much a key value pair taking a name and value as strings on construction.

Images can't contain alpha channels or transparencies

it so easy...

Open image in Preview app click File -> Export and uncheck alpha

The network path was not found

check your Connection String Properly. Check that the connection is open.

String CS=ConfigurationManager.COnnectionStrings["DBCS"].connectionString;
  if(!IsPostBack)
    {enter code here
   SqlConnection con = new SqlConnection(CS);
        con.Open();
    SqlCommand cmd = new SqlCommand("select * from tblCountry", con);
     SqlDataAdapter da = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
da.Fill(dt);
//Bind data
}

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

I had this problem recently, my project didn't include local.properties file.

Check local.properties file if it includes sdk.dir with correct path to sdk

MongoDB not equal to

If there is a null in an array and you want to avoid it:

db.test.find({"contain" : {$ne :[] }}).pretty()

Material Design not styling alert dialogs

You could use

Material Design Library

Material Design Library made for pretty alert dialogs, buttons, and other things like snack bars. Currently it's heavily developed.

Guide, code, example - https://github.com/navasmdc/MaterialDesignLibrary

Guide how to add library to Android Studio 1.0 - How do I import material design library to Android Studio?

.

Happy coding ;)

Spring Boot yaml configuration for a list of strings

In my case this was a syntax issue in the .yml file. I had:

@Value("${spring.kafka.bootstrap-servers}")
public List<String> BOOTSTRAP_SERVERS_LIST;

and the list in my .yml file:

bootstrap-servers:
  - s1.company.com:9092
  - s2.company.com:9092
  - s3.company.com:9092

was not reading into the @Value-annotated field. When I changed the syntax in the .yml file to:

bootstrap-servers >
  s1.company.com:9092
  s2.company.com:9092
  s3.company.com:9092

it worked fine.

Convert regular Python string to raw string

With a little bit correcting @Jolly1234's Answer: here is the code:

raw_string=path.encode('unicode_escape').decode()

Convert date from String to Date format in Dataframes

Use to_date with Java SimpleDateFormat.

TO_DATE(CAST(UNIX_TIMESTAMP(date, 'MM/dd/yyyy') AS TIMESTAMP))

Example:

spark.sql("""
  SELECT TO_DATE(CAST(UNIX_TIMESTAMP('08/26/2016', 'MM/dd/yyyy') AS TIMESTAMP)) AS newdate"""
).show()

+----------+
|        dt|
+----------+
|2016-08-26|
+----------+

Identify if a string is a number

Use these extension methods to clearly distinguish between a check if the string is numerical and if the string only contains 0-9 digits

public static class ExtensionMethods
{
    /// <summary>
    /// Returns true if string could represent a valid number, including decimals and local culture symbols
    /// </summary>
    public static bool IsNumeric(this string s)
    {
        decimal d;
        return decimal.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out d);
    }

    /// <summary>
    /// Returns true only if string is wholy comprised of numerical digits
    /// </summary>
    public static bool IsNumbersOnly(this string s)
    {
        if (s == null || s == string.Empty)
            return false;

        foreach (char c in s)
        {
            if (c < '0' || c > '9') // Avoid using .IsDigit or .IsNumeric as they will return true for other characters
                return false;
        }

        return true;
    }
}

Keep SSH session alive

I wanted a one-time solution:

ssh -o ServerAliveInterval=60 [email protected]

Stored it in an alias:

alias sshprod='ssh -v -o ServerAliveInterval=60 [email protected]'

Now can connect like this:

me@MyMachine:~$ sshprod

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

I've noticed that sometimes eclipse somehow picks up some of the jars and keeps a lock on them (in Windows only) and when you try to do mvn clean it says:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.2:clean (default-clean) on project

The only solution so far is to close eclipse and run the mvn build again.

And these are random jars - it can pick up anything it wants... Why that happens is a mystery to me. Probably eclipse opens the jars when you do Type Search or Resource Search and forgets to close them / release the file handlers..

Check div is hidden using jquery

Did you notice your typo, $car2 instead of #car2 ?

Anyway, :hidden seems to be working as expected, try it here.

babel-loader jsx SyntaxError: Unexpected token

Add "babel-preset-react"

npm install babel-preset-react

and add "presets" option to babel-loader in your webpack.config.js

(or you can add it to your .babelrc or package.js: http://babeljs.io/docs/usage/babelrc/)

Here is an example webpack.config.js:

{ 
    test: /\.jsx?$/,         // Match both .js and .jsx files
    exclude: /node_modules/, 
    loader: "babel", 
    query:
      {
        presets:['react']
      }
}

Recently Babel 6 was released and there was a major change: https://babeljs.io/blog/2015/10/29/6.0.0

If you are using react 0.14, you should use ReactDOM.render() (from require('react-dom')) instead of React.render(): https://facebook.github.io/react/blog/#changelog

UPDATE 2018

Rule.query has already been deprecated in favour of Rule.options. Usage in webpack 4 is as follows:

npm install babel-loader babel-preset-react

Then in your webpack configuration (as an entry in the module.rules array in the module.exports object)

{
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: [
      {
        loader: 'babel-loader',
        options: {
          presets: ['react']
        }
      }
    ],
  }

How to decide when to use Node.js?

My piece: nodejs is great for making real time systems like analytics, chat-apps, apis, ad servers, etc. Hell, I made my first chat app using nodejs and socket.io under 2 hours and that too during exam week!

Edit

Its been several years since I have started using nodejs and I have used it in making many different things including static file servers, simple analytics, chat apps and much more. This is my take on when to use nodejs

When to use

When making system which put emphasis on concurrency and speed.

  • Sockets only servers like chat apps, irc apps, etc.
  • Social networks which put emphasis on realtime resources like geolocation, video stream, audio stream, etc.
  • Handling small chunks of data really fast like an analytics webapp.
  • As exposing a REST only api.

When not to use

Its a very versatile webserver so you can use it wherever you want but probably not these places.

  • Simple blogs and static sites.
  • Just as a static file server.

Keep in mind that I am just nitpicking. For static file servers, apache is better mainly because it is widely available. The nodejs community has grown larger and more mature over the years and it is safe to say nodejs can be used just about everywhere if you have your own choice of hosting.

Is there an equivalent for var_dump (PHP) in Javascript?

If you are using firefox then the firebug plug-in console is an excellent way of examining objects

console.debug(myObject);

Alternatively you can loop through the properties (including methods) like this:

for (property in object) {
    // do what you want with property, object[property].value
}

Detect iPad users using jQuery?

iPad Detection

You should be able to detect an iPad user by taking a look at the userAgent property:

var is_iPad = navigator.userAgent.match(/iPad/i) != null;

iPhone/iPod Detection

Similarly, the platform property to check for devices like iPhones or iPods:

function is_iPhone_or_iPod(){
     return navigator.platform.match(/i(Phone|Pod))/i)
}

Notes

While it works, you should generally avoid performing browser-specific detection as it can often be unreliable (and can be spoofed). It's preferred to use actual feature-detection in most cases, which can be done through a library like Modernizr.

As pointed out in Brennen's answer, issues can arise when performing this detection within the Facebook app. Please see his answer for handling this scenario.

Related Resources

How to create a .NET DateTime from ISO 8601 format

Here is one that works better for me (LINQPad version):

DateTime d;
DateTime.TryParseExact(
    "2010-08-20T15:00:00Z",
    @"yyyy-MM-dd\THH:mm:ss\Z",
    CultureInfo.InvariantCulture,
    DateTimeStyles.AssumeUniversal, 
    out d);
d.ToString()

produces

true
8/20/2010 8:00:00 AM

What is the default boolean value in C#?

Basically local variables aren't automatically initialized. Hence using them without initializing would result in an exception.

Only the following variables are automatically initialized to their default values:

  • Static variables
  • Instance variables of class and struct instances
  • Array elements

The default values are as follows (assigned in default constructor of a class):

  • The default value of a variable of reference type is null.
  • For integer types, the default value is 0
  • For char, the default value is `\u0000'
  • For float, the default value is 0.0f
  • For double, the default value is 0.0d
  • For decimal, the default value is 0.0m
  • For bool, the default value is false
  • For an enum type, the default value is 0
  • For a struct type, the default value is obtained by setting all value type fields to their default values

As far as later parts of your question are conerned:

  • The reason why all variables which are not automatically initialized to default values should be initialized is a restriction imposed by compiler.
  • private bool foo = false; This is indeed redundant since this is an instance variable of a class. Hence this would be initialized to false in the default constructor. Hence no need to set this to false yourself.

How to order events bound with jQuery

function bindFirst(owner, event, handler) {
    owner.unbind(event, handler);
    owner.bind(event, handler);

    var events = owner.data('events')[event];
    events.unshift(events.pop());

    owner.data('events')[event] = events;
}

Getting Data from Android Play Store

The Google Play Store doesn't provide this data, so the sites must just be scraping it.

Add a prefix string to beginning of each line

SETLOCAL ENABLEDELAYEDEXPANSION

YourPrefix=blabla

YourPath=C:\path

for /f "tokens=*" %%a in (!YourPath!\longfile.csv)     do (echo !YourPrefix!%%a) >> !YourPath!\Archive\output.csv

How to use environment variables in docker compose

I have a simple bash script I created for this it just means running it on your file before use: https://github.com/antonosmond/subber

Basically just create your compose file using double curly braces to denote environment variables e.g:

app:
    build: "{{APP_PATH}}"
ports:
    - "{{APP_PORT_MAP}}"

Anything in double curly braces will be replaced with the environment variable of the same name so if I had the following environment variables set:

APP_PATH=~/my_app/build
APP_PORT_MAP=5000:5000

on running subber docker-compose.yml the resulting file would look like:

app:
    build: "~/my_app/build"
ports:
    - "5000:5000"

Notepad++: Multiple words search in a file (may be in different lines)?

<shameless-plug>

Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here

Feel free to post any issues/suggestions here.

</shameless-plug>

Press TAB and then ENTER key in Selenium WebDriver

In python this work for me

self.set_your_value = "your value"

def your_method_name(self):      
    self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`

How to set default value for form field in Symfony2?

As Brian asked:

empty_data appears to only set the field to 1 when it is submitted with no value. What about when you want the form to default to displaying 1 in the input when no value is present?

you can set the default value with empty_value

$builder->add('myField', 'number', ['empty_value' => 'Default value'])

Check if date is a valid one

Was able to find the solution. Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.

var date = moment("2016-10-19");

And then date.isValid() gives desired result.

T-SQL datetime rounded to nearest minute and nearest hours with using functions

Select convert(char(8), DATEADD(MINUTE, DATEDIFF(MINUTE, 0, getdate), 0), 108) as Time

will round down seconds to 00

Array of structs example

Given an instance of the struct, you set the values.

    student thisStudent;
    Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
    thisStudent.s_id = int.Parse(Console.ReadLine());
    thisStudent.s_name = Console.ReadLine();
    thisStudent.c_name = Console.ReadLine();
    thisStudent.s_dob = Console.ReadLine();

Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.

CSS/HTML: Create a glowing border around an Input Field

_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').focus(function() {_x000D_
    $(this).parent().addClass('open');_x000D_
});_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').blur(function() {_x000D_
    $(this).parent().removeClass('open');_x000D_
});
_x000D_
.open {_x000D_
  color:red;   _x000D_
}_x000D_
.form-fild {_x000D_
 position: relative;_x000D_
 margin: 30px 0;_x000D_
}_x000D_
.form-fild label {_x000D_
 position: absolute;_x000D_
 top: 5px;_x000D_
 left: 10px;_x000D_
 padding:5px;_x000D_
}_x000D_
_x000D_
.form-fild.open label {_x000D_
 top: -25px;_x000D_
 left: 10px;_x000D_
 /*background: #ffffff;*/_x000D_
}_x000D_
.form-fild input[type="text"] {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild textarea {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild.open textarea, _x000D_
.form-fild.open input[type="text"] {_x000D_
 padding-left: 10px;_x000D_
}_x000D_
textarea,_x000D_
input[type="text"] {_x000D_
 padding: 10px;_x000D_
 width: 100%;_x000D_
}_x000D_
textarea,_x000D_
input,_x000D_
.form-fild.open label,_x000D_
.form-fild label {_x000D_
 -webkit-transition: all 0.2s ease-in-out;_x000D_
       -moz-transition: all 0.2s ease-in-out;_x000D_
         -o-transition: all 0.2s ease-in-out;_x000D_
            transition: all 0.2s ease-in-out;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
 <div class="row">_x000D_
     <form>_x000D_
        <div class="form-fild">_x000D_
            <label>Name :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Email :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Number :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Message :</label>_x000D_
            <textarea cols="10" rows="5"></textarea>_x000D_
        </div>_x000D_
    </form>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to Lock the data in a cell in excel using vba

Try using the Worksheet.Protect method, like so:

Sub ProtectActiveSheet()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    ws.Protect DrawingObjects:=True, Contents:=True, _
        Scenarios:=True, Password="SamplePassword"
End Sub

You should, however, be concerned about including the password in your VBA code. You don't necessarily need a password if you're only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.

Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That's a good way to get started in VBA.

How to remove item from a python list in a loop?

x = [i for i in x if len(i)==2]

How to mock private method for testing using PowerMock?

For some reason Brice's answer is not working for me. I was able to manipulate it a bit to get it to work. It might just be because I have a newer version of PowerMock. I'm using 1.6.5.

import java.util.Random;

public class CodeWithPrivateMethod {

    public void meaningfulPublicApi() {
        if (doTheGamble("Whatever", 1 << 3)) {
            throw new RuntimeException("boom");
        }
    }

    private boolean doTheGamble(String whatever, int binary) {
        Random random = new Random(System.nanoTime());
        boolean gamble = random.nextBoolean();
        return gamble;
    }
}

The test class looks as follows:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doReturn;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
    private CodeWithPrivateMethod classToTest;

    @Test(expected = RuntimeException.class)
    public void when_gambling_is_true_then_always_explode() throws Exception {
        classToTest = PowerMockito.spy(classToTest);

        doReturn(true).when(classToTest, "doTheGamble", anyString(), anyInt());

        classToTest.meaningfulPublicApi();
    }
}

What is the runtime performance cost of a Docker container?

Here's some more benchmarks for Docker based memcached server versus host native memcached server using Twemperf benchmark tool https://github.com/twitter/twemperf with 5000 connections and 20k connection rate

Connect time overhead for docker based memcached seems to agree with above whitepaper at roughly twice native speed.

Twemperf Docker Memcached

Connection rate: 9817.9 conn/s
Connection time [ms]: avg 341.1 min 73.7 max 396.2 stddev 52.11
Connect time [ms]: avg 55.0 min 1.1 max 103.1 stddev 28.14
Request rate: 83942.7 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 83942.7 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 28.6 min 1.2 max 65.0 stddev 0.01
Response time [ms]: p25 24.0 p50 27.0 p75 29.0
Response time [ms]: p95 58.0 p99 62.0 p999 65.0

Twemperf Centmin Mod Memcached

Connection rate: 11419.3 conn/s
Connection time [ms]: avg 200.5 min 0.6 max 263.2 stddev 73.85
Connect time [ms]: avg 26.2 min 0.0 max 53.5 stddev 14.59
Request rate: 114192.6 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 114192.6 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 17.4 min 0.0 max 28.8 stddev 0.01
Response time [ms]: p25 12.0 p50 20.0 p75 23.0
Response time [ms]: p95 28.0 p99 28.0 p999 29.0

Here's bencmarks using memtier benchmark tool

memtier_benchmark docker Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets       16821.99          ---          ---      1.12600      2271.79
Gets      168035.07    159636.00      8399.07      1.12000     23884.00
Totals    184857.06    159636.00      8399.07      1.12100     26155.79

memtier_benchmark Centmin Mod Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets       28468.13          ---          ---      0.62300      3844.59
Gets      284368.51    266547.14     17821.36      0.62200     39964.31
Totals    312836.64    266547.14     17821.36      0.62200     43808.90

How to finish Activity when starting other activity in Android?

You need to intent your current context to another activity first with startActivity. After that you can finish your current activity from where you redirect.

 Intent intent = new Intent(this, FirstActivity.class);// New activity
 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 startActivity(intent);
 finish(); // Call once you redirect to another activity

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) - Clears the activity stack. If you don't want to clear the activity stack. PLease don't use that flag then.

How can I escape latex code received through user input?

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

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

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

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

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

Auto increment in MongoDB to store sequence of Unique User ID

The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:

maxObj = db.CollectionName.aggregate([
  {
    $group : { _id: '$item', maxValue: { $max: '$fieldName' } } 
  }
];
fieldNextValue = maxObj.maxValue + 1;

$fieldName is the name of your field, but without the $ sign.

CollectionName is the name of your collection.

The reason I am not using count() is that the produced value could meet an existing value.

The creation of an enforcing unique index could make it safer:

db.CollectionName.createIndex( { "fieldName": 1 }, { unique: true } )

Javascript communication between browser tabs/windows

There is also an experimental technology called Broadcast Channel API that is designed specifically for communication between different browser contexts with same origin. You can post messages to and recieve messages from another browser context without having a reference to it:

var channel = new BroadcastChannel("foo");
channel.onmessage = function( e ) {
  // Process messages from other contexts.
};
// Send message to other listening contexts.
channel.postMessage({ value: 42, type: "bar"});

Obviously this is experiental technology and is not supported accross all browsers yet.

OnChange event using React JS for drop down

var MySelect = React.createClass({
getInitialState: function() {
 

_x000D_
_x000D_
var MySelect = React.createClass({
 getInitialState: function() {
     return {
         value: 'select'
     }
 },
 change: function(event){
     event.persist(); //THE MAIN LINE THAT WILL SET THE VALUE
     this.setState({value: event.target.value});
 },
 render: function(){
    return(
       <div>
           <select id="lang" onChange={this.change.bind(this)} value={this.state.value}>
              <option value="select">Select</option>
              <option value="Java">Java</option>
              <option value="C++">C++</option>
           </select>
           <p></p>
           <p>{this.state.value}</p>
       </div>
    );
 }
});
React.render(<MySelect />, document.body); 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
_x000D_
_x000D_
_x000D_

Prevent linebreak after </div>

use this code for normal div display: inline;

use this code if u use it in table display: inline-table; better than table

Why should I use an IDE?

Simply put, an IDE offers additional time-saving features over a simple editor.

What is the first character in the sort order used by Windows Explorer?

From my testing, there are three criteria for sorting characters as described below. Aside from this, shorter strings are sorted above longer strings that start with the same characters.

Note: This testing only looked at the first character sorting and did not look into edge cases described by this answer, which found that, for all characters after the first character, numbers take precedence over symbols (i.e. the order is 1. Symbols 2. Numbers 3. Letters for first character, 1. Numbers 2. Symbols 3. Letters after). This answer also indicated that the Unicode/ASCII layer of sorting might not be entirely consistent. I'll update this answer if I get time to look into these edge cases.

Note: It's important to note that sorting order might be subject to change as described by this answer. It is not clear to me though the extent to which this actually ever changes. I've done this testing and found it to be valid on both Windows 7 and Windows 10.


Symbols
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

Numbers
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

Letters
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

enter image description here


Sorting Rule Sequence vs Observed Order

It's worth noting that there are really two ways of looking at this. Ultimately, what you have are sorting rules that are applied in a certain order, in turn, this produces an observed order. The ordering of older rules becomes nested under the ordering of newer rules. This means that the first rule applied is the last rule observed, while the last rule applied is the first or topmost rule observed.

Sorting Rule Sequence

1.) Sort on Unicode Value (U+xxxx)
2.) Sort on culture/language
3.) Sort on Type (Symbol, Number, Letter)

Observed Order

  • The highest level of grouping is by type in the following order...

    1.) Symbols
    2.) Numbers
    3.) Letters

    Therefore, any symbol from any language comes before any number from any language, while any letter from any language appears after all symbols and numbers.

  • The second level of grouping is by culture/language. The following order seems to apply for this:

    Latin
    Greek
    Cyrillic
    Hebrew
    Arabic

  • The lowest rule observed is Unicode order, so items within a type-language group are ordered by Unicode value (U+xxxx).


Adapted from here: https://superuser.com/a/971721/496260

Applications are expected to have a root view controller at the end of application launch

I had this same error message in the log. I had a UIAlertView pop up in application:didFinishLaunchingWithOptions. I solved it by delaying the call to the alertView to allow time for the root view controller to finishing loading.

In application:didFinishLaunchingWithOptions:

[self performSelector:@selector(callPopUp) withObject:nil afterDelay:1.0];

which calls after 1 second:

- (void)callPopUp
{
    // call UIAlertView
}

make sounds (beep) with c++

std::cout << '\7';

jQuery vs. javascript?

Jquery like any other good JavaScript frameworks supplies you with functionality independent of browser platform wrapping all the intricacies, which you may not care about or don't want to care about.

I think using a framework is better instead of using pure JavaScript and doing all the stuff from scratch, unless you usage is very limited.

I definitely recommend JQuery!

Thanks

python and sys.argv

I would do it this way:

import sys

def main(argv):
    if len(argv) < 2:
        sys.stderr.write("Usage: %s <database>" % (argv[0],))
        return 1

    if not os.path.exists(argv[1]):
        sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
        return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv))

This allows main() to be imported into other modules if desired, and simplifies debugging because you can choose what argv should be.

Get a timestamp in C in microseconds?

First we need to know on the range of microseconds i.e. 000_000 to 999_999 (1000000 microseconds is equal to 1second). tv.tv_usec will return value from 0 to 999999 not 000000 to 999999 so when using it with seconds we might get 2.1seconds instead of 2.000001 seconds because when only talking about tv_usec 000001 is essentially 1. Its better if you insert

if(tv.tv_usec<10)
{
 printf("00000");
} 
else if(tv.tv_usec<100&&tv.tv_usec>9)// i.e. 2digits
{
 printf("0000");
}

and so on...

@try - catch block in Objective-C

Now I've found the problem.

Removing the obj_exception_throw from my breakpoints solved this. Now it's caught by the @try block and also, NSSetUncaughtExceptionHandler will handle this if a @try block is missing.

How to check a string for a special character?

You can use string.punctuation and any function like this

import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

With this line

invalidChars = set(string.punctuation.replace("_", ""))

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any function will return True if atleast one of the characters is in invalidChars.

Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116

word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"

Upper memory limit?

Not only are you reading the whole of each file into memory, but also you laboriously replicate the information in a table called list_of_lines.

You have a secondary problem: your choices of variable names severely obfuscate what you are doing.

Here is your script rewritten with the readlines() caper removed and with meaningful names:

file_A1_B1 = open("A1_B1_100000.txt", "r")
file_A2_B2 = open("A2_B2_100000.txt", "r")
file_A1_B2 = open("A1_B2_100000.txt", "r")
file_A2_B1 = open("A2_B1_100000.txt", "r")
file_write = open ("average_generations.txt", "w")
mutation_average = open("mutation_average", "w") # not used
files = [file_A2_B2,file_A2_B2,file_A1_B2,file_A2_B1]
for afile in files:
    table = []
    for aline in afile:
        values = aline.split('\t')
        values.remove('\n') # why?
        table.append(values)
    row_count = len(table)
    row0length = len(table[0])
    print_counter = 4
    for column_index in range(row0length):
        column_total = 0
        for row_index in range(row_count):
            number = float(table[row_index][column_index])
            column_total = column_total + number
        column_average = column_total/row_count
        print column_average
        if print_counter == 4:
            file_write.write(str(column_average)+'\n')
            print_counter = 0
        print_counter +=1
file_write.write('\n')

It rapidly becomes apparent that (1) you are calculating column averages (2) the obfuscation led some others to think you were calculating row averages.

As you are calculating column averages, no output is required until the end of each file, and the amount of extra memory actually required is proportional to the number of columns.

Here is a revised version of the outer loop code:

for afile in files:
    for row_count, aline in enumerate(afile, start=1):
        values = aline.split('\t')
        values.remove('\n') # why?
        fvalues = map(float, values)
        if row_count == 1:
            row0length = len(fvalues)
            column_index_range = range(row0length)
            column_totals = fvalues
        else:
            assert len(fvalues) == row0length
            for column_index in column_index_range:
                column_totals[column_index] += fvalues[column_index]
    print_counter = 4
    for column_index in column_index_range:
        column_average = column_totals[column_index] / row_count
        print column_average
        if print_counter == 4:
            file_write.write(str(column_average)+'\n')
            print_counter = 0
        print_counter +=1