Programs & Examples On #Syndication

Unix command to find lines common in two files

perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/'  file1 file2

Best way to save a trained model in PyTorch?

I've found this page on their github repo, I'll just paste the content here.


Recommended approach for saving a model

There are two main approaches for serializing and restoring a model.

The first (recommended) saves and loads only the model parameters:

torch.save(the_model.state_dict(), PATH)

Then later:

the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))

The second saves and loads the entire model:

torch.save(the_model, PATH)

Then later:

the_model = torch.load(PATH)

However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.

onKeyDown event not working on divs in React

The answer with

<div 
    className="player"
    onKeyDown={this.onKeyPressed}
    tabIndex={0}
>

works for me, please note that the tabIndex requires a number, not a string, so tabIndex="0" doesn't work.

How to convert a byte array to Stream

I am using as what John Rasch said:

Stream streamContent = taxformUpload.FileContent;

Multiple separate IF conditions in SQL Server

Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.

As a beginner in SQL I find that when using a BEGIN and END SSMS usually adds a squiggly line with incorrect syntax near 'END' to END, simply because there's no content in between yet. If you're just setting up BEGIN and END to get started and add the actual query later, then simply add a bogus PRINT statement so SSMS stops bothering you.

For example:

IF (1=1)
BEGIN
  PRINT 'BOGUS'
END

The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:

IF (1=1)
BEGIN
END

webpack command not working

Actually, I have got this error a while ago. There are two ways to make this to work, as per my knowledge.

  1. Server wont update the changes made in the index.js because of some webpack bugs. So, restart your server.
  2. Updating your node.js will be helpful to avoid such problems.

How can I check the extension of a file?

import os
source = ['test_sound.flac','ts.mp3']

for files in source:
   fileName,fileExtension = os.path.splitext(files)
   print fileExtension   # Print File Extensions
   print fileName   # It print file name

Convert a list to a dictionary in Python

{x: a[a.index(x)+1] for x in a if a.index(x) % 2 ==0}

result : {'hello': 'world', '1': '2'}

Resize height with Highcharts

Ricardo's answer is correct, however: sometimes you may find yourself in a situation where the container simply doesn't resize as desired as the browser window changes size, thus not allowing highcharts to resize itself.

This always works:

  1. Set up a timed and pipelined resize event listener. Example with 500ms on jsFiddle
  2. use chart.setSize(width, height, doAnimation = true); in your actual resize function to set the height and width dynamically
  3. Set reflow: false in the highcharts-options and of course set height and width explicitly on creation. As we'll be doing our own resize event handling there's no need Highcharts hooks in another one.

Rails 3: I want to list all paths defined in my rails application

rake routes | grep <specific resource name>

displays resource specific routes, if it is a pretty long list of routes.

Can I use a min-height for table, tr or td?

Simply use the css entry of min-height to one of the cells of your table row. Works on old browsers too.

.rowNumberColumn {
    background-color: #e6e6e6;
    min-height: 22;
}

<table width="100%" cellspacing="0" class="htmlgrid-table">
    <tr id="tr_0">
            <td width="3%" align="center" class="readOnlyCell rowNumberColumn">1</td>
            <td align="left" width="40%" id="td_0_0" class="readOnlyCell gContentSection">411978430-Intimate:Ruby:Small</td>

Getting the filenames of all files in a folder

Here's how to look in the documentation.

First, you're dealing with IO, so look in the java.io package.

There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles() method in the File class. And the documentation for that method says:

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

Scrolling up in the File JavaDoc, I see the constructors. And that's really all I need to be able to create a File instance and call listFiles() on it. Scrolling still further, I can see some information about how files are named in different operating systems.

How to print third column to last column?

awk -v m="\x0a" -v N="3" '{$N=m$N ;print substr($0, index($0,m)+1)}'

This chops what is before the given field nr., N, and prints all the rest of the line, including field nr.N and maintaining the original spacing (it does not reformat). It doesn't mater if the string of the field appears also somewhere else in the line, which is the problem with daisaa's answer.

Define a function:

fromField () { 
awk -v m="\x0a" -v N="$1" '{$N=m$N; print substr($0,index($0,m)+1)}'
}

And use it like this:

$ echo "  bat   bi       iru   lau bost   " | fromField 3
iru   lau bost   
$ echo "  bat   bi       iru   lau bost   " | fromField 2
bi       iru   lau bost 

Output maintains everything, including trailing spaces

Works well for files where '/n' is the record separator so you don't have that new-line char inside the lines. If you want to use it with other record separators then use:

awk -v m="\x01" -v N="3" '{$N=m$N ;print substr($0, index($0,m)+1)}'

for example. Works well with almost all files as long as they don't use hexadecimal char nr. 1 inside the lines.

How to test if string exists in file with Bash?

Here's a fast way to search and evaluate a string or partial string:

if grep -R "my-search-string" /my/file.ext
then
    # string exists
else
    # string not found
fi

You can also test first, if the command returns any results by running only:

grep -R "my-search-string" /my/file.ext

How to get a unique device ID in Swift?

The value of identifierForVendor changes when the user deletes all of that vendor’s apps from the device, if you want to keep the unique ID even for the subsequent fresh installations, you can try to use the following function

func vendorIdentifierForDevice()->String {
    //Get common part of Applicatoin Bundle ID, Note : getCommonPartOfApplicationBundleID is to be defined.
    let commonAppBundleID = getCommonPartOfApplicationBundleID()
    //Read from KeyChain using bunndle ID, Note : readFromKeyChain is to be defined.
    if let vendorID = readFromKeyChain(commonAppBundleID) {
        return vendorID
    } else {
        var vendorID = NSUUID().uuidString
        //Save to KeyChain using bunndle ID, Note : saveToKeyChain is to be defined.
        saveToKeyChain(commonAppBundleID, vendorID)
        return vendorID
    }
}

return string with first match Regex

I'd go with:

r = re.search("\d+", ch)
result = return r.group(0) if r else ""

re.search only looks for the first match in the string anyway, so I think it makes your intent slightly more clear than using findall.

How do I draw a shadow under a UIView?

self.layer.masksToBounds = NO;
self.layer.cornerRadius = 8; // if you like rounded corners
self.layer.shadowOffset = CGSizeMake(-15, 20);
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = 0.5;

This will slow down the application. Adding the following line can improve performance as long as your view is visibly rectangular:

self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;

Matplotlib figure facecolor (background color)

savefig has its own parameter for facecolor. I think an even easier way than the accepted answer is to set them globally just once, instead of putting facecolor=fig.get_facecolor() every time:

plt.rcParams['axes.facecolor']='red'
plt.rcParams['savefig.facecolor']='red'

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

_x000D_
_x000D_
<script type="text/javascript">_x000D_
      jQuery(function($){_x000D_
        $('#map-country').cssMap({'size' : 810});_x000D_
       });_x000D_
    </script>
_x000D_
_x000D_
_x000D_

strong text

How to remove all ListBox items?

I think it would be better to actually bind your listBoxes to a datasource, since it looks like you are adding the same elements to each listbox. A simple example would be something like this:

    private List<String> _weight = new List<string>() { "kilogram", "pound" };
    private List<String> _height = new List<string>() { "foot", "inch", "meter" };

    public Window1()
    {            
        InitializeComponent();
    }        

    private void Weight_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _weight;
        listBox2.ItemsSource = _weight;
    }

    private void Height_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _height;
        listBox2.ItemsSource = _height;
    }

INSERT INTO vs SELECT INTO

The other answers are all great/correct (the main difference is whether the DestTable exists already (INSERT), or doesn't exist yet (SELECT ... INTO))

You may prefer to use INSERT (instead of SELECT ... INTO), if you want to be able to COUNT(*) the rows that have been inserted so far.

Using SELECT COUNT(*) ... WITH NOLOCK is a simple/crude technique that may help you check the "progress" of the INSERT; helpful if it's a long-running insert, as seen in this answer).

[If you use...] INSERT DestTable SELECT ... FROM SrcTable ...then your SELECT COUNT(*) from DestTable WITH (NOLOCK) query would work.

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

Check this method after iOS 7 and later.

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

Improvements have been made to this in iOS 8. We can set it as property of the table view itself.

How to get access token from FB.login method in javascript SDK

response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.
Check this for details: SDKs & Tools › JavaScript SDK › FB.login

SQL - HAVING vs. WHERE

WHERE clause introduces a condition on individual rows; HAVING clause introduces a condition on aggregations, i.e. results of selection where a single result, such as count, average, min, max, or sum, has been produced from multiple rows. Your query calls for a second kind of condition (i.e. a condition on an aggregation) hence HAVING works correctly.

As a rule of thumb, use WHERE before GROUP BY and HAVING after GROUP BY. It is a rather primitive rule, but it is useful in more than 90% of the cases.

While you're at it, you may want to re-write your query using ANSI version of the join:

SELECT  L.LectID, Fname, Lname
FROM Lecturers L
JOIN Lecturers_Specialization S ON L.LectID=S.LectID
GROUP BY L.LectID, Fname, Lname
HAVING COUNT(S.Expertise)>=ALL
(SELECT COUNT(Expertise) FROM Lecturers_Specialization GROUP BY LectID)

This would eliminate WHERE that was used as a theta join condition.

Two statements next to curly brace in an equation

Or this:

f(x)=\begin{cases}
0, & -\pi\leqslant x <0\\
\pi, & 0 \leqslant x \leqslant +\pi
\end{cases}

Hibernate: How to set NULL query-parameter value with HQL?

This is not a Hibernate specific issue (it's just SQL nature), and YES, there IS a solution for both SQL and HQL:

@Peter Lang had the right idea, and you had the correct HQL query. I guess you just needed a new clean run to pick up the query changes ;-)

The below code absolutely works and it is great if you keep all your queries in orm.xml

from CountryDTO c where ((:status is null and c.status is null) or c.status = :status) and c.type =:type

If your parameter String is null then the query will check if the row's status is null as well. Otherwise it will resort to compare with the equals sign.

Notes:

The issue may be a specific MySql quirk. I only tested with Oracle.

The above query assumes that there are table rows where c.status is null

The where clause is prioritized so that the parameter is checked first.

The parameter name 'type' may be a reserved word in SQL but it shouldn't matter since it is replaced before the query runs.

If you needed to skip the :status where_clause altogether; you can code like so:

from CountryDTO c where (:status is null or c.status = :status) and c.type =:type

and it is equivalent to:

sql.append(" where ");
if(status != null){
  sql.append(" c.status = :status and ");
}
sql.append(" c.type =:type ");

How do you stop tracking a remote branch in Git?

As mentioned in Yoshua Wuyts' answer, using git branch:

git branch --unset-upstream

Other options:

You don't have to delete your local branch.

Simply delete the local branch that is tracking the remote branch:

git branch -d -r origin/<remote branch name>

-r, --remotes tells git to delete the remote-tracking branch (i.e., delete the branch set to track the remote branch). This will not delete the branch on the remote repo!

See "Having a hard time understanding git-fetch"

there's no such concept of local tracking branches, only remote tracking branches.
So origin/master is a remote tracking branch for master in the origin repo

As mentioned in Dobes Vandermeer's answer, you also need to reset the configuration associated to the local branch:

git config --unset branch.<branch>.remote
git config --unset branch.<branch>.merge

Remove the upstream information for <branchname>.
If no branch is specified it defaults to the current branch.

(git 1.8+, Oct. 2012, commit b84869e by Carlos Martín Nieto (carlosmn))

That will make any push/pull completely unaware of origin/<remote branch name>.

How can I disable the default console handler, while using the java logging API?

You must instruct your logger not to send its messages on up to its parent logger:

...
import java.util.logging.*;
...
Logger logger = Logger.getLogger(this.getClass().getName());
logger.setUseParentHandlers(false);
...

However, this should be done before adding any more handlers to logger.

Bootstrap 3 - disable navbar collapse

The nabvar will collapse on small devices. The point of collapsing is defined by @grid-float-breakpoint in variables. By default this will by before 768px. For screens below the 768 pixels screen width, the navbar will look like:

enter image description here

It's possible to change the @grid-float-breakpoint in variables.less and recompile Bootstrap. When doing this you also will have to change @screen-xs-max in navbar.less. You will have to set this value to your new @grid-float-breakpoint -1. See also: https://github.com/twbs/bootstrap/pull/10465. This is needed to change navbar forms and dropdowns at the @grid-float-breakpoint to their mobile version too.

Easiest way is to customize bootstrap

find variable:

 @grid-float-breakpoint

which is set to @screen-sm, you can change it according to your needs. Hope it helps!


For SAAS Users

add your custom variables like $grid-float-breakpoint: 0px; before the @import "bootstrap.scss";

Column calculated from another column?

If you want to add a column to your table which is automatically updated to half of some other column, you can do that with a trigger.

But I think the already proposed answer are a better way to do this.

Dry coded trigger :

CREATE TRIGGER halfcolumn_insert AFTER INSERT ON table
  FOR EACH ROW BEGIN
    UPDATE table SET calculated = value / 2 WHERE id = NEW.id;
  END;
CREATE TRIGGER halfcolumn_update AFTER UPDATE ON table
  FOR EACH ROW BEGIN
    UPDATE table SET calculated = value / 2 WHERE id = NEW.id;
  END;

I don't think you can make only one trigger, since the event we must respond to are different.

Unloading classes in java?

Yes there are ways to load classes and to "unload" them later on. The trick is to implement your own classloader which resides between high level class loader (the System class loader) and the class loaders of the app server(s), and to hope that the app server's class loaders do delegate the classloading to the upper loaders.

A class is defined by its package, its name, and the class loader it originally loaded. Program a "proxy" classloader which is the first that is loaded when starting the JVM. Workflow:

  • The program starts and the real "main"-class is loaded by this proxy classloader.
  • Every class that then is normally loaded (i.e. not through another classloader implementation which could break the hierarchy) will be delegated to this class loader.
  • The proxy classloader delegates java.x and sun.x to the system classloader (these must not be loaded through any other classloader than the system classloader).
  • For every class that is replaceable, instantiate a classloader (which really loads the class and does not delegate it to the parent classloader) and load it through this.
  • Store the package/name of the classes as keys and the classloader as values in a data structure (i.e. Hashmap).
  • Every time the proxy classloader gets a request for a class that was loaded before, it returns the class from the class loader stored before.
  • It should be enough to locate the byte array of a class by your class loader (or to "delete" the key/value pair from your data structure) and reload the class in case you want to change it.

Done right there should not come a ClassCastException or LinkageError etc.

For more informations about class loader hierarchies (yes, that's exactly what you are implementing here ;- ) look at "Server-Based Java Programming" by Ted Neward - that book helped me implementing something very similar to what you want.

Can I add background color only for padding?

This would be a proper CSS solution which works for IE8/9 as well (IE8 with html5shiv ofcourse): codepen

nav {
  margin:0px auto;
  height:50px;
  background-color:gray;
  padding:10px;
  border:2px solid red;
  position: relative;
  color: white;
  z-index: 1;
}

nav:after {
  content: '';
  background: black;
  display: block;
  position: absolute;
  margin: 10px;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: -1;
}

How can I rollback a git repository to a specific commit?

Most suggestions are assuming that you need to somehow destroy the last 20 commits, which is why it means "rewriting history", but you don't have to.

Just create a new branch from the commit #80 and work on that branch going forward. The other 20 commits will stay on the old orphaned branch.

If you absolutely want your new branch to have the same name, remember that branch are basically just labels. Just rename your old branch to something else, then create the new branch at commit #80 with the name you want.

What is the return value of os.system() in Python?

The return value of os.system is OS-dependant.

On Unix, the return value is a 16-bit number that contains two different pieces of information. From the documentation:

a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero)

So if the signal number (low byte) is 0, it would, in theory, be safe to shift the result by 8 bits (result >> 8) to get the error code. The function os.WEXITSTATUS does exactly this. If the error code is 0, that usually means that the process exited without errors.

On Windows, the documentation specifies that the return value of os.system is shell-dependant. If the shell is cmd.exe (the default one), the value is the return code of the process. Again, 0 would mean that there weren't errors.

For others error codes:

Running windows shell commands with python

Refactoring of @srini-beerge's answer which gets the output and the return code

import subprocess
def run_win_cmd(cmd):
    result = []
    process = subprocess.Popen(cmd,
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    for line in process.stdout:
        result.append(line)
    errcode = process.returncode
    for line in result:
        print(line)
    if errcode is not None:
        raise Exception('cmd %s failed, see above for details', cmd)

How to do vlookup and fill down (like in Excel) in R?

I think you can also use match():

largetable$HouseTypeNo <- with(lookup,
                     HouseTypeNo[match(largetable$HouseType,
                                       HouseType)])

This still works if I scramble the order of lookup.

XSL xsl:template match="/"

It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?

But look at this, a well-formed XML document:

<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>

The root of this document has three children: a processing instruction, a comment, and an element.

So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:

<xsl:template match="/comment()"/>

Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*.

Remove the last line from a file in Bash

You can try this method also : example of removing last n number of lines.

a=0 ; while [ $a -lt 4 ];do sed -i '$ d' output.txt; a=expr $a + 1;done

Removing last 4 lines from file(output.txt).

How can I check out a GitHub pull request with git?

For Bitbucket, you need replace the word pull to pull-requests.

First, you can confirm the pull request URL style by git ls-remote origin command.

$ git ls-remote origin |grep pull
f3f40f2ca9509368c959b0b13729dc0ae2fbf2ae    refs/pull-requests/1503/from
da4666bd91eabcc6f2c214e0bbd99d543d94767e    refs/pull-requests/1503/merge
...

As you can see, it is refs/pull-requests/1503/from instead of refs/pull/1503/from

Then you can use the commands of any of the answers.

How To Format A Block of Code Within a Presentation?

http://www.tohtml.com/ created syntax highlighted HTML code for lots of languages. It might be what you're looking for.

gradle build fails on lint task

As for me, it's a bad and quick solution for your problem :

android { 
  lintOptions { 
    abortOnError false 
  }
}

Better solution is solving problem in your code, because lint tool checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization.

This problem most frequently occurring when:

  • Layout include unresolved symbols or missing some attribute
  • Other structural issues, such as use of deprecated elements or API calls that are not supported by the target API versions, might lead to code failing to run correctly.

Find your bugs by Inspect Code in Android Studio: Improve Your Code with Lint

Transparent scrollbar with css

Try this one, it works fine for me.

In CSS:

::-webkit-scrollbar
{
    width: 0px;
}
::-webkit-scrollbar-track-piece
{
    background-color: transparent;
    -webkit-border-radius: 6px;
}

and here is the working demo: https://jsfiddle.net/qpvnecz5/

What does it mean to "call" a function in Python?

To "call" means to make a reference in your code to a function that is written elsewhere. This function "call" can be made to the standard Python library (stuff that comes installed with Python), third-party libraries (stuff other people wrote that you want to use), or your own code (stuff you wrote). For example:

#!/usr/env python

import os

def foo():
    return "hello world"

print os.getlogin()
print foo()

I created a function called "foo" and called it later on with that print statement. I imported the standard "os" Python library then I called the "getlogin" function within that library.

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

A full list of all the new/popular databases and their uses?

Martin Fowler did an interesting blog post last year about non-relational databases starting to gain traction. He mentions:

  • Drizzle (a "bare bones" relational database)
  • CouchDB (a document-oriented database)
  • GemStone (an object-oriented database)

There is also Google's BigTable which is described as "a sparse, distributed multi-dimensional sorted map".

I have been working with GemStone for a number of years now and the productivity gains is amazing - having the database store your objects directly removes the need to constantly marshall back and forth between tables and objects.

What is the difference between Java RMI and RPC?

RPC is an old protocol based on C.It can invoke a remote procedure and make it look like a local call.RPC handles the complexities of passing that remote invocation to the server and getting the result to client.

Java RMI also achieves the same thing but slightly differently.It uses references to remote objects.So, what it does is that it sends a reference to the remote object alongwith the name of the method to invoke.It is better because it results in cleaner code in case of large programs and also distribution of objects over the network enables multiple clients to invoke methods in the server instead of establishing each connection individually.

Custom Listview Adapter with filter Android

One thing I've noticed is that whenever you are editing the list (adding items for example) as well as filtering for it, then inside the @Override getView method, you shouldn't use filteredData.get(position), as it throws an IndexOutOfBounds exception.

Instead, what worked for me, was using the getItem(position) method, which belongs to the ArrayAdapter class.

Calling stored procedure from another stored procedure SQL Server

First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table

SET IDENTITY_INSERT table2 ON;

before the insert.

So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID

EXEC test2 'productName', 'productDescription'
SET @newID = SCOPE_IDENTIY()

or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID

Convert a python dict to a string and back

If your dictionary isn't too big maybe str + eval can do the work:

dict1 = {'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }}
str1 = str(dict1)

dict2 = eval(str1)

print dict1==dict2

You can use ast.literal_eval instead of eval for additional security if the source is untrusted.

How can I populate a select dropdown list from a JSON feed with AngularJS?

The proper way to do it is using the ng-options directive. The HTML would look like this.

<select ng-model="selectedTestAccount" 
        ng-options="item.Id as item.Name for item in testAccounts">
    <option value="">Select Account</option>
</select>

JavaScript:

angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
    $scope.selectedTestAccount = null;
    $scope.testAccounts = [];

    $http({
            method: 'GET',
            url: '/Admin/GetTestAccounts',
            data: { applicationId: 3 }
        }).success(function (result) {
        $scope.testAccounts = result;
    });
});

You'll also need to ensure angular is run on your html and that your module is loaded.

<html ng-app="test">
    <body ng-controller="DemoCtrl">
    ....
    </body>
</html>

How to use clock() in C++

you can measure how long your program works. The following functions help measure the CPU time since the start of the program:

  • C++ (double)clock() / CLOCKS PER SEC with ctime included.
  • python time.clock() returns floating-point value in seconds.
  • Java System.nanoTime() returns long value in nanoseconds.

my reference: Algorithms toolbox week 1 course part of data structures and algorithms specialization by University of California San Diego & National Research University Higher School of Economics

so you can add this line of code after your algorithm

cout << (double)clock() / CLOCKS_PER_SEC ;

Expected Output: the output representing the number of clock ticks per second

Unescape HTML entities in Javascript?

The question doesn't specify the origin of x but it makes sense to defend, if we can, against malicious (or just unexpected, from our own application) input. For example, suppose x has a value of &amp; <script>alert('hello');</script>. A safe and simple way to handle this in jQuery is:

var x    = "&amp; <script>alert('hello');</script>";
var safe = $('<div />').html(x).text();

// => "& alert('hello');"

Found via https://gist.github.com/jmblog/3222899. I can't see many reasons to avoid using this solution given it is at least as short, if not shorter than some alternatives and provides defence against XSS.

(I originally posted this as a comment, but am adding it as an answer since a subsequent comment in the same thread requested that I do so).

How to get the first item from an associative PHP array?

Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first. If you're sure that your array has values it in then you can just do:

$first = $array[array_key_first($array)];

More likely, you'll want to handle the case where the array is empty:

$first = (empty($array)) ? $default : $array[array_key_first($array)];

How to display a range input slider vertically

First, set height greater than width. In theory, this is all you should need. The HTML5 Spec suggests as much:

... the UA determined the orientation of the control from the ratio of the style-sheet-specified height and width properties.

Opera had it implemented this way, but Opera is now using WebKit Blink. As of today, no browser implements a vertical slider based solely on height being greater than width.

Regardless, setting height greater than width is needed to get the layout right between browsers. Applying left and right padding will also help with layout and positioning.

For Chrome, use -webkit-appearance: slider-vertical.

For IE, use writing-mode: bt-lr.

For Firefox, add an orient="vertical" attribute to the html. Pity that they did it this way. Visual styles should be controlled via CSS, not HTML.

_x000D_
_x000D_
input[type=range][orient=vertical]
{
    writing-mode: bt-lr; /* IE */
    -webkit-appearance: slider-vertical; /* WebKit */
    width: 8px;
    height: 175px;
    padding: 0 5px;
}
_x000D_
<input type="range" orient="vertical" />
_x000D_
_x000D_
_x000D_


Disclaimers:

This solution is based on current browser implementations of as yet undefined or unfinalized CSS properties. If you intend to use it in your code, be prepared to make code adjustments as newer browser versions are released and w3c recommendations are completed.

MDN contains an explicit warning against using -webkit-appearance on the web:

Do not use this property on Web sites: not only is it non-standard, but its behavior change from one browser to another. Even the keyword none has not the same behavior on each form element on different browsers, and some doesn't support it at all.

The caption for the vertical slider demo in the IE documentation erroneously indicates that setting height greater than width will display a range slider vertically, but this does not work. In the code section, it plainly does not set height or width, and instead uses writing-mode. The writing-mode property, as implemented by IE, is very robust. Sadly, the values defined in the current working draft of the spec as of this writing, are much more limited. Should future versions of IE drop support of bt-lr in favor of the currently proposed vertical-lr (which would be the equivalent of tb-lr), the slider would display upside down. Most likely, future versions would extend the writing-mode to accept new values rather than drop support for existing values. But, it's good to know what you are dealing with.

React.js inline style best practices

Depending on your configuration inline styling can offer you Hot reload. The webpage is immediately re-rendered every time the style changes. This helps me develop components quicker. Having said that, I am sure you can setup a Hot reload environment for CSS + SCSS.

How do I delete rows in a data frame?

Problems with deleting by row number

For quick and dirty analyses, you can delete rows of a data.frame by number as per the top answer. I.e.,

newdata <- myData[-c(2, 4, 6), ] 

However, if you are trying to write a robust data analysis script, you should generally avoid deleting rows by numeric position. This is because the order of the rows in your data may change in the future. A general principle of a data.frame or database tables is that the order of the rows should not matter. If the order does matter, this should be encoded in an actual variable in the data.frame.

For example, imagine you imported a dataset and deleted rows by numeric position after inspecting the data and identifying the row numbers of the rows that you wanted to delete. However, at some later point, you go into the raw data and have a look around and reorder the data. Your row deletion code will now delete the wrong rows, and worse, you are unlikely to get any errors warning you that this has occurred.

Better strategy

A better strategy is to delete rows based on substantive and stable properties of the row. For example, if you had an id column variable that uniquely identifies each case, you could use that.

newdata <- myData[ !(myData$id %in% c(2,4,6)), ]

Other times, you will have a formal exclusion criteria that could be specified, and you could use one of the many subsetting tools in R to exclude cases based on that rule.

Trim Cells using VBA in Excel

This works well for me. It uses an array so you aren't looping through each cell. Runs much faster over large worksheet sections.

Sub Trim_Cells_Array_Method()

Dim arrData() As Variant
Dim arrReturnData() As Variant
Dim rng As Excel.Range
Dim lRows As Long
Dim lCols As Long
Dim i As Long, j As Long

  lRows = Selection.Rows.count
  lCols = Selection.Columns.count

  ReDim arrData(1 To lRows, 1 To lCols)
  ReDim arrReturnData(1 To lRows, 1 To lCols)

  Set rng = Selection
  arrData = rng.value

  For j = 1 To lCols
    For i = 1 To lRows
      arrReturnData(i, j) = Trim(arrData(i, j))
    Next i
  Next j

  rng.value = arrReturnData

  Set rng = Nothing
End Sub

Using jQuery to center a DIV on the screen

What I have here is a "center" method that ensures the element you are attempting to center is not only of "fixed" or "absolute" positioning, but it also ensures that the element you are centering is smaller than its parent, this centers and element relative to is parent, if the elements parent is smaller than the element itself, it will pillage up the DOM to the next parent, and center it relative to that.

$.fn.center = function () {
        /// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>

        var element = $(this),
            elementPos = element.css('position'),
            elementParent = $(element.parent()),
            elementWidth = element.outerWidth(),
            parentWidth = elementParent.width();

        if (parentWidth <= elementWidth) {
            elementParent = $(elementParent.parent());
            parentWidth = elementParent.width();
        }

        if (elementPos === "absolute" || elementPos === "fixed") {
            element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');
        }
    };

How can I make a thumbnail <img> show a full size image when clicked?

<img src='thumb.gif' onclick='this.src="full_size.gif"' />

Of course you can change the onclick event to load the image wherever you want.

How do you use colspan and rowspan in HTML tables?

If anyone is looking for a rowspan on both the left AND on the right, here is how you can do it:

_x000D_
_x000D_
table { _x000D_
    border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
    padding: 20px; _x000D_
    border: 1px solid black; _x000D_
    text-align: center;_x000D_
}
_x000D_
<table>_x000D_
    <tbody>_x000D_
    <tr>_x000D_
        <td rowspan="2">LEFT</td>_x000D_
        <td> 1 </td>_x000D_
        <td> 2 </td>_x000D_
        <td> 3 </td>_x000D_
        <td> 4 </td>_x000D_
        <td rowspan="2">RIGHT</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 5 </td>_x000D_
        <td> 6 </td>_x000D_
        <td> 7 </td>_x000D_
        <td> 8 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
    </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Alternatively, if you want to add the LEFT and RIGHT to an existing rowset, you can achieve the same result by throwing them in with a collapsed colspan in between:

_x000D_
_x000D_
table {_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
    padding: 20px; _x000D_
    border: 1px solid black; _x000D_
    text-align: center;_x000D_
}
_x000D_
<table>_x000D_
    <tbody>_x000D_
    <tr>_x000D_
        <td rowspan="3">LEFT</td>_x000D_
        <td colspan="4" style="padding: 0; border-bottom: solid 1px transparent;"></td>_x000D_
        <td rowspan="3">RIGHT</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 1 </td>_x000D_
        <td> 2 </td>_x000D_
        <td> 3 </td>_x000D_
        <td> 4 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 5 </td>_x000D_
        <td> 6 </td>_x000D_
        <td> 7 </td>_x000D_
        <td> 8 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
    </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

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

A cookie is a object with key value pair to store information related to the customer. Main objective is to personalize the customer's experience.

An utility method can be created like

private Cookie createCookie(String cookieName, String cookieValue) {
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setPath("/");
    cookie.setMaxAge(MAX_AGE_SECONDS);
    cookie.setHttpOnly(true);
    cookie.setSecure(true);
    return cookie;
}

If storing important information then we should alsways put setHttpOnly so that the cookie cannot be accessed/modified via javascript. setSecure is applicable if you are want cookies to be accessed only over https protocol.

using above utility method you can add cookies to response as

Cookie cookie = createCookie("name","value");
response.addCookie(cookie);

Why is it said that "HTTP is a stateless protocol"?

HTTP is a connectionless and this is a direct result that HTTP is a stateless protocol. The server and client are aware of each other only during a current request. Afterwards, both of them forget about each other. Due to this nature of the protocol, neither the client nor the browser can retain information between different request across the web pages.

Java ArrayList for integers

How about creating an ArrayList of a set amount of Integers?

The below method returns an ArrayList of a set amount of Integers.

public static ArrayList<Integer> createRandomList(int sizeParameter)
{
    // An ArrayList that method returns
    ArrayList<Integer> setIntegerList = new ArrayList<Integer>(sizeParameter);
    // Random Object helper
    Random randomHelper = new Random();
    
    for (int x = 0; x < sizeParameter; x++)
    {
        setIntegerList.add(randomHelper.nextInt());
    }   // End of the for loop
    
    return setIntegerList;
}

Get size of all tables in database

As a simple extension to marc_s's answer (the one that has been accepted), this is adjusted to return column count and allow for filtering:

SELECT *
FROM
(

SELECT 
    t.NAME AS TableName,
    s.Name AS SchemaName,
    p.rows AS RowCounts,
    COUNT(DISTINCT c.COLUMN_NAME) as ColumnCount,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    (SUM(a.used_pages) * 8) AS UsedSpaceKB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
INNER JOIN
    INFORMATION_SCHEMA.COLUMNS c ON t.NAME = c.TABLE_NAME
LEFT OUTER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
WHERE 
    t.NAME NOT LIKE 'dt%' 
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255
GROUP BY 
    t.Name, s.Name, p.Rows
) AS Result

WHERE
    RowCounts > 1000
    AND ColumnCount > 10
ORDER BY 
    UsedSpaceKB DESC

better way to drop nan rows in pandas

To expand Hitesh's answer if you want to drop rows where 'x' specifically is nan, you can use the subset parameter. His answer will drop rows where other columns have nans as well

dat.dropna(subset=['x'])

Find IP address of directly connected device

Your Best Approach is to install Wireshark, reboot the device wait for the TCP/UDP stream , broadcasts will announce the IP address for both Ethernet ports This is especially useful when the device connected does not have DHCP Client enabled, then you can go from there.

android: how to change layout on button click?

I would add an android:onClick to the layout and then change the layout in the activity.

So in the layout

<ImageView
(Other things like source etc.)
android:onClick="changelayout"
/>

Then in the activity add the following:

public void changelayout(View view){
    setContentView(R.layout.second_layout);
}

File to byte[] in Java

Not only does the following way convert a java.io.File to a byte[], I also found it to be the fastest way to read in a file, when testing many different Java file reading methods against each other:

java.nio.file.Files.readAllBytes()

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class ReadFile_Files_ReadAllBytes {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    byte [] fileBytes = Files.readAllBytes(file.toPath());
    char singleChar;
    for(byte b : fileBytes) {
      singleChar = (char) b;
      System.out.print(singleChar);
    }
  }
}

How to insert a blob into a database using sql server management studio

However you can simply read a file from disk on SQL server machine:

select * from openrowset (bulk 'c:\path\filename.ext',single_blob) a

to see it in management application in hex form (Management Studio).

So, you can, for example, backup database to file (locally on server) and then download it to other place by the statement above.

Selecting only numeric columns from a data frame

If you have many factor variables, you can use select_if funtion. install the dplyr packages. There are many function that separates data by satisfying a condition. you can set the conditions.

Use like this.

categorical<-select_if(df,is.factor)
str(categorical)

How do I determine k when using k-means clustering?

Assuming you have a matrix of data called DATA, you can perform partitioning around medoids with estimation of number of clusters (by silhouette analysis) like this:

library(fpc)
maxk <- 20  # arbitrary here, you can set this to whatever you like
estimatedK <- pamk(dist(DATA), krange=1:maxk)$nc

powershell is missing the terminator: "

In my specific case of the same issue, it was caused by not having the Powershell script saved with an encoding of Windows-1252 or UFT-8 WITH BOM.

Submit a form using jQuery

you could do it like this :

$('#myform').bind('submit', function(){ ... });

Bash scripting, multiple conditions in while loop

Try:

while [ $stats -gt 300 -o $stats -eq 0 ]

[ is a call to test. It is not just for grouping, like parentheses in other languages. Check man [ or man test for more information.

No 'Access-Control-Allow-Origin' header is present on the requested resource error

Just FYI, I noticed this information from the jQuery documentation which I believe applies to this issue:

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.

Changing the hosts file like @thanix didn't work for me, but the extension mentioned by @dkruchok did solve the problem.

What's the actual use of 'fail' in JUnit test case?

Some cases where I have found it useful:

  • mark a test that is incomplete, so it fails and warns you until you can finish it
  • making sure an exception is thrown:
try{
  // do stuff...
  fail("Exception not thrown");
}catch(Exception e){
  assertTrue(e.hasSomeFlag());
}

Note:

Since JUnit4, there is a more elegant way to test that an exception is being thrown: Use the annotation @Test(expected=IndexOutOfBoundsException.class)

However, this won't work if you also want to inspect the exception, then you still need fail().

How to validate numeric values which may contain dots or commas?

\d{1,2}[,.]\d{1,2}

\d means a digit, the {1,2} part means 1 or 2 of the previous character (\d in this case) and the [,.] part means either a comma or dot.

Predict() - Maybe I'm not understanding it

First, you want to use

model <- lm(Total ~ Coupon, data=df)

not model <-lm(df$Total ~ df$Coupon, data=df).

Second, by saying lm(Total ~ Coupon), you are fitting a model that uses Total as the response variable, with Coupon as the predictor. That is, your model is of the form Total = a + b*Coupon, with a and b the coefficients to be estimated. Note that the response goes on the left side of the ~, and the predictor(s) on the right.

Because of this, when you ask R to give you predicted values for the model, you have to provide a set of new predictor values, ie new values of Coupon, not Total.

Third, judging by your specification of newdata, it looks like you're actually after a model to fit Coupon as a function of Total, not the other way around. To do this:

model <- lm(Coupon ~ Total, data=df)
new.df <- data.frame(Total=c(79037022, 83100656, 104299800))
predict(model, new.df)

What is the http-header "X-XSS-Protection"?

X-XSS-Protection is a HTTP header understood by Internet Explorer 8 (and newer versions). This header lets domains toggle on and off the "XSS Filter" of IE8, which prevents some categories of XSS attacks. IE8 has the filter activated by default, but servers can switch if off by setting

   X-XSS-Protection: 0

See also http://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-internet-explorer-xss-filter-with-the-x-xss-protection-http-header.aspx

How to replace all occurrences of a character in string?

Old School :-)

std::string str = "H:/recursos/audio/youtube/libre/falta/"; 

for (int i = 0; i < str.size(); i++) {
    if (str[i] == '/') {
        str[i] = '\\';
    }
}

std::cout << str;

Result:

H:\recursos\audio\youtube\libre\falta\

How to locate the php.ini file (xampp)

i'm using xampp with PHP 7. you can trying looking for php.ini in

/etc/php/7.0/apache2

How to convert a double to long without casting?

Simply put, casting is more efficient than creating a Double object.

dictionary update sequence element #0 has length 3; 2 is required

This error raised up because you trying to update dict object by using a wrong sequence (list or tuple) structure.

cash_id.create(cr, uid, lines,context=None) trying to convert lines into dict object:

(0, 0, {
    'name': l.name,
    'date': l.date,
    'amount': l.amount,
    'type': l.type,
    'statement_id': exp.statement_id.id,
    'account_id': l.account_id.id,
    'account_analytic_id': l.analytic_account_id.id,
    'ref': l.ref,
    'note': l.note,
    'company_id': l.company_id.id
})

Remove the second zero from this tuple to properly convert it into a dict object.

To test it your self, try this into python shell:

>>> l=[(0,0,{'h':88})]
>>> a={}
>>> a.update(l)

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    a.update(l)
ValueError: dictionary update sequence element #0 has length 3; 2 is required

>>> l=[(0,{'h':88})]
>>> a.update(l)

Copy a file list as text from Windows Explorer

In Windows 7 and later, this will do the trick for you

  • Select the file/files.
  • Hold the shift key and then right-click on the selected file/files.
  • You will see Copy as Path. Click that.
  • Open a Notepad file and paste and you will be good to go.

The menu item Copy as Path is not available in Windows XP.

T-sql - determine if value is integer

I have a feeling doing it this way is the work of satan, but as an alternative:

How about a TRY - CATCH?

DECLARE @Converted as INT
DECLARE @IsNumeric BIT

BEGIN TRY
    SET @Converted = cast(@ValueToCheck as int)
    SET @IsNumeric=1
END TRY
BEGIN CATCH
    SET @IsNumeric=0
END CATCH

select IIF(@IsNumeric=1,'Integer','Not integer') as IsInteger

This works, though only in SQL Server 2008 and up.

How to open remote files in sublime text 3

Base on this.

Step by step:

  • On your local workstation: On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub
  • On your local workstation: Add RemoteForward 52698 127.0.0.1:52698 to your .ssh/config file, or -R 52698:localhost:52698 if you prefer command line
  • On your remote server:

    sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
    sudo chmod a+x /usr/local/bin/rsub
    

Just keep your ST3 editor open, and you can easily edit remote files with

rsub myfile.txt

EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:

echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc

Now just log off, log back in, and you'll be all set.

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

BLOB primarily intended to hold non-traditional data, such as images,videos,voice or mixed media. CLOB intended to retain character-based data.

jQuery Date Picker - disable past dates

$('#datepicker-dep').datepicker({
    minDate: 0
});

minDate:0 works for me.

wildcard * in CSS for classes

If you don't need the unique identifier for further styling of the divs and are using HTML5 you could try and go with custom Data Attributes. Read on here or try a google search for HTML5 Custom Data Attributes

Config Error: This configuration section cannot be used at this path

The error says that the configuration section is locked at the parent level. So it will not be directly 1 config file which will resolve the issue, we need to go through the hierarchy of the config files to see the inheritance Check the below link to go through the File hierarchy and inheritance in IIS

https://msdn.microsoft.com/en-us/library/ms178685.aspx

So you need to check for the app config settings in the below order

  1. ApplicationHost.config in C:windows\system32\inetsrv\config. Change the overrideModeDefault attribute to be Allow.
  2. ApplicationName.config or web.config in the applications directory
  3. Web.config in the root directory.
  4. Web.config in the specific website (My issue was found at this place).
  5. Web.config of the root web (server's configuration)
  6. machine.config of the machine (Root's web.config and machine.config can be found at - systemroot\MicrosoftNET\Framework\versionNumber\CONFIG\Machine.config)

Go carefully through all these configs in the order of 1 to 6 and you should find it.

Android Spinner : Avoid onItemSelected calls during initialization

spinner.setOnItemSelectedListener(this); // Will call onItemSelected() Listener.

So first time handle this with any Integer value

Example: Initially Take int check = 0;

public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
   if(++check > 1) {
      TextView textView = (TextView) findViewById(R.id.textView1);
      String str = (String) parent.getItemAtPosition(pos);
      textView.setText(str);
   }
}

You can do it with boolean value and also by checking current and previous positions. See here

403 - Forbidden: Access is denied. ASP.Net MVC

I just had this issue, it was because the IIS site was pointing at the wrong Application Pool.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved

Try the following steps:

  1. Make sure you have connectivity (you can browse) (This kind of error is usually due to connectivity with Internet)

  2. Download Maven and unzip it

  3. Create a JAVA_HOME System Variable

  4. Create an M2_HOME System Variable

  5. Add %JAVA_HOME%\bin;%M2_HOME%\bin; to your PATH variable

  6. Open a command window cmd. Check: mvn -v

  7. If you have a proxy, you will need to configure it

http://maven.apache.org/guides/mini/guide-proxies.html

  1. Make sure you have .m2/repository (erase all the folders and files below)

  2. If you are going to use Eclipse, You will need to create the settings.xml

Maven plugin in Eclipse - Settings.xml file is missing

You can see more detail in

http://maven.apache.org/ref/3.2.5/maven-settings/settings.html

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I was able to fix this on Windows 7 64-bit running Python 3.4.3 by running the set command at a command prompt to determine the existing Visual Studio tools environment variable; in my case it was VS140COMNTOOLS for Visual Studio Community 2015.

Then run the following (substituting the variable on the right-hand side if yours has a different name):

set VS100COMNTOOLS=%VS140COMNTOOLS%

This allowed me to install the PyCrypto module that was previously giving me the same error as the OP.

For a more permanent solution, add this environment variable to your Windows environment via Control Panel ("Edit the system environment variables"), though you might need to use the actual path instead of the variable substitution.

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

The .env file should have same database name , username and password as in the mysql database and check whether all permissions are granted to the user for accessing the database or not. I solved my problem by adding the cpanel username in front of database name and username like jumbo_admingo and jumbo_user1 respectively where jumbo is my cpanel username and admingo is the database name i created in mysql and user1 is the user which has been provided the access to the database admingo. THIS SOLVED MY PROBLEM.

find a minimum value in an array of floats

If min value in array, you can try like:

>>> mydict = {"a": -1.5, "b": -1000.44, "c": -3}
>>> min(mydict.values())
-1000.44

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

Programmatically get the version number of a DLL

var versionAttrib = new AssemblyName(Assembly.GetExecutingAssembly().FullName);

Get min and max value in PHP Array

$Location_Category_array = array(5,50,7,6,1,7,7,30,50,50,50,40,50,9,9,11,2,2,2,2,2,11,21,21,1,12,1,5);

asort($Location_Category_array);
$count=array_count_values($Location_Category_array);//Counts the values in the array, returns associatve array
        print_r($count);
        $maxsize = 0;
        $maxvalue = 0;
        foreach($count as $a=>$y){
            echo "<br/>".$a."=".$y;
            if($y>=$maxvalue){
                $maxvalue = $y;
                if($a>$maxsize){
                    $maxsize = $a;
                }
            }
        }

    echo "<br/>max = ".$maxsize;

what is the differences between sql server authentication and windows authentication..?

I don't know SQLServer as well as other DBMS' but I imagine the benefit is the same as with DB2 and Oracle. If you use Windows authentication, you only have to maintain one set of users and/or passwords, that of Windows, which is already done for you.

DBMS authentication means having a separate set of users and/or passwords which must be maintained.

In addition, Windows passwords allow them to be configured centrally for the enterprise (Active Directory) whereas SQLServer has to maintain one set for each DBMS instance.

PHP, display image with Header()

Browsers can often tell the image type by sniffing out the meta information of the image. Also, there should be a space in that header:

header('Content-type: image/png');

Save PHP variables to a text file

Use a combination of of fopen, fwrite and fread. PHP.net has excellent documentation and examples of each of them.

http://us2.php.net/manual/en/function.fopen.php
http://us2.php.net/manual/en/function.fwrite.php
http://us2.php.net/manual/en/function.fread.php

How to use fetch in typescript

If you take a look at @types/node-fetch you will see the body definition

export class Body {
    bodyUsed: boolean;
    body: NodeJS.ReadableStream;
    json(): Promise<any>;
    json<T>(): Promise<T>;
    text(): Promise<string>;
    buffer(): Promise<Buffer>;
}

That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json<Actor>())
      .then(res => {
          let b:Actor = res;
      });

How can I sort a dictionary by key?

Found another way:

import json
print json.dumps(d, sort_keys = True)

upd:
1. this also sorts nested objects (thanks @DanielF).
2. python dictionaries are unordered therefore this is sutable for print or assign to str only.

Number of processors/cores in command line

When someone asks for "the number of processors/cores" there are 2 answers being requested. The number of "processors" would be the physical number installed in sockets on the machine.

The number of "cores" would be physical cores. Hyperthreaded (virtual) cores would not be included (at least to my mind). As someone who writes a lot of programs with thread pools, you really need to know the count of physical cores vs cores/hyperthreads. That said, you can modify the following script to get the answers that you need.

#!/bin/bash

MODEL=`cat /cpu/procinfo | grep "model name" | sort | uniq`
ALL=`cat /proc/cpuinfo | grep "bogo" | wc -l`
PHYSICAL=`cat /proc/cpuinfo | grep "physical id" | sort | uniq | wc -l`
CORES=`cat /proc/cpuinfo | grep "cpu cores" | sort | uniq | cut -d':' -f2`
PHY_CORES=$(($PHYSICAL * $CORES))
echo "Type $MODEL"
echo "Processors $PHYSICAL"
echo "Physical cores $PHY_CORES"
echo "Including hyperthreading cores $ALL"

The result on a machine with 2 model Xeon X5650 physical processors each with 6 physical cores that also support hyperthreading:

Type model name : Intel(R) Xeon(R) CPU           X5650  @ 2.67GHz
Processors 2
Physical cores 12
Including hyperthreading cores 24

On a machine with 2 mdeol Xeon E5472 processors each with 4 physical cores that doesn't support hyperthreading

Type model name : Intel(R) Xeon(R) CPU           E5472  @ 3.00GHz
Processors 2
Physical cores 8
Including hyperthreading cores 8

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else

How to correctly represent a whitespace character

You can always use Unicode character, for me personally this is the most clear solution:

var space = "\u0020"

How to send custom headers with requests in Swagger UI?

In ASP.net WebApi, the simplest way to pass-in a header on Swagger UI is to implement the Apply(...) method on the IOperationFilter interface.

Add this to your project:

public class AddRequiredHeaderParameter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.parameters == null)
            operation.parameters = new List<Parameter>();

        operation.parameters.Add(new Parameter
        {
            name = "MyHeaderField",
            @in = "header",
            type = "string",
            description = "My header field",
            required = true
        });
    }
}

In SwaggerConfig.cs, register the filter from above using c.OperationFilter<>():

public static void Register()
{
    var thisAssembly = typeof(SwaggerConfig).Assembly;

    GlobalConfiguration.Configuration 
        .EnableSwagger(c =>
        {
            c.SingleApiVersion("v1", "YourProjectName");
            c.IgnoreObsoleteActions();
            c.UseFullTypeNameInSchemaIds();
            c.DescribeAllEnumsAsStrings();
            c.IncludeXmlComments(GetXmlCommentsPath());
            c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());


            c.OperationFilter<AddRequiredHeaderParameter>(); // Add this here
        })
        .EnableSwaggerUi(c =>
        {
            c.DocExpansion(DocExpansion.List);
        });
}

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

Below Solution worked for me :

Type About:Config in the Address Bar and press Enter.

“This Might void your warranty!” warning will be displayed, click on I’ll be careful, I Promise button.

Type security.ssl.enable_ocsp_stapling in search box.

The value field is true, double click on it to make it false.

Now try to connect your website again.

How to append contents of multiple files into one file

All of the (text-) files into one

find . | xargs cat > outfile

xargs makes the output-lines of find . the arguments of cat.

find has many options, like -name '*.txt' or -type.

you should check them out if you want to use it in your pipeline

Converting a date string to a DateTime object using Joda Time library

You need a DateTimeFormatter appropriate to the format you're using. Take a look at the docs for instructions on how to build one.

Off the cuff, I think you need format = DateTimeFormat.forPattern("M/d/y H:m:s")

Finding an element in an array in Java

You might want to consider using a Collection implementation instead of a flat array.

The Collection interface defines a contains(Object o) method, which returns true/false.

ArrayList implementation defines an indexOf(Object o), which gives an index, but that method is not on all collection implementations.

Both these methods require proper implementations of the equals() method, and you probably want a properly implemented hashCode() method just in case you are using a hash based Collection (e.g. HashSet).

Greater than and less than in one statement

If getFiles() returns a java.util.Collection, !getFiles().isEmpty() && size<5 can be OK.

On the other hand, unless you encapsulate the container which provides method such as boolean sizeBetween(int min, int max).

Python object.__repr__(self) should be an expression?

Guideline: If you can succinctly provide an exact representation, format it as a Python expression (which implies that it can be both eval'd and copied directly into source code, in the right context). If providing an inexact representation, use <...> format.

There are many possible representations for any value, but the one that's most interesting for Python programmers is an expression that recreates the value. Remember that those who understand Python are the target audience—and that's also why inexact representations should include relevant context. Even the default <XXX object at 0xNNN>, while almost entirely useless, still provides type, id() (to distinguish different objects), and indication that no better representation is available.

Javascript AES encryption

Use CryptoJS

Here's the code: https://github.com/odedhb/AES-encrypt

And here's an online working example: https://odedhb.github.io/AES-encrypt/

How can I render HTML from another file in a React component?

If your template.html file is just HTML and not a React component, then you can't require it in the same way you would do with a JS file.

However, if you are using Browserify — there is a transform called stringify which will allow you to require non-js files as strings. Once you have added the transform, you will be able to require HTML files and they will export as though they were just strings.

Once you have required the HTML file, you'll have to inject the HTML string into your component, using the dangerouslySetInnerHTML prop.

var __html = require('./template.html');
var template = { __html: __html };

React.module.exports = React.createClass({
  render: function() {
    return(
      <div dangerouslySetInnerHTML={template} />
    );
  }
});

This goes against a lot of what React is about though. It would be more natural to create your templates as React components with JSX, rather than as regular HTML files.

The JSX syntax makes it trivially easy to express structured data, like HTML, especially when you use stateless function components.

If your template.html file looked something like this

<div class='foo'>
  <h1>Hello</h1>
  <p>Some paragraph text</p>
  <button>Click</button>
</div>

Then you could convert it instead to a JSX file that looked like this.

module.exports = function(props) {
  return (
    <div className='foo'>
      <h1>Hello</h1>
      <p>Some paragraph text</p>
      <button>Click</button>
    </div>
  );
};

Then you can require and use it without needing stringify.

var Template = require('./template');

module.exports = React.createClass({
  render: function() {
    var bar = 'baz';
    return(
      <Template foo={bar}/>
    );
  }
});

It maintains all of the structure of the original file, but leverages the flexibility of React's props model and allows for compile time syntax checking, unlike a regular HTML file.

Warning about `$HTTP_RAW_POST_DATA` being deprecated

Unfortunately, this answer here by @EatOng is not correct. After reading his answer I added a dummy variable to every AJAX request I was firing (even if some of them already had some fields) just to be sure the error never appears.

But just now I came across the same damn error from PHP. I double-confirmed that I had sent some POST data (some other fields too along with the dummy variable). PHP version 5.6.25, always_populate_raw_post_data value is set to 0.

Also, as I am sending a application/json request, PHP is not populating it to $_POST, rather I have to json_decode() the raw POST request body, accessible by php://input.

As the answer by @rr- cites,

0/off/whatever: BC behavior (populate if content-type is not registered or request method is other than POST).

Because the request method is for sure POST, I guess PHP didn't recognize/like my Content-Type: application/json request (again, why??).

OPTION 1:

Edit the php.ini file manually and set the culprit variable to -1, as many of the answers here suggest.

OPTION 2:

This is a PHP 5.6 bug. Upgrade PHP.

OPTION 3:

As @user9541305 answered here, changing the Content-Type of AJAX request to application/x-www-form-urlencoded or multipart/form-data will make PHP populate the $_POST from the POSTed body (because PHP likes/recognizes those content-type headers!?).

OPTION 4: LAST RESORT

Well, I did not want to change the Content-Type of AJAX, it would cause a lot of trouble for debugging. (Chrome DevTools nicely views the POSTed variables of JSON requests.)

I am developing this thing for a client and cannot ask them to use latest PHP, nor to edit the php.ini file. As a last resort, I will just check if it is set to 0 and if so, edit the php.ini file in my PHP script itself. Of course I will have to ask the user to restart apache. What a shame!

Here is a sample code:

<?php

if(ini_get('always_populate_raw_post_data') != '-1')
{
    // Get the path to php.ini file
    $iniFilePath = php_ini_loaded_file();

    // Get the php.ini file content
    $iniContent = file_get_contents($iniFilePath);

    // Un-comment (if commented) always_populate_raw_post_data line, and set its value to -1
    $iniContent = preg_replace('~^\s*;?\s*always_populate_raw_post_data\s*=\s*.*$~im', 'always_populate_raw_post_data = -1', $iniContent);

    // Write the content back to the php.ini file
    file_put_contents($iniFilePath, $iniContent);

    // Exit the php script here
    // Also, write some response here to notify the user and ask to restart Apache / WAMP / Whatever.
    exit;
}

Composer install error - requires ext_curl when it's actually enabled

According to https://github.com/composer/composer/issues/2119 you could extend your local composer.json to state that it provides the extension (which it doesn't really do - that's why you shouldn't publicly publish your package, only use it internally).

What are the uses of the exec command in shell scripts?

The exec built-in command mirrors functions in the kernel, there are a family of them based on execve, which is usually called from C.

exec replaces the current program in the current process, without forking a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;

  1. We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile, the last statement says something like:

     exec appln-program
    

    so now there is no shell to go back to. Even if appln-program crashes, the end-user cannot get to a shell, because it is not there - the exec replaced it.

  2. We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh, and everyone just put into their .login (csh start-up file) a call to ksh. While that worked, it left a stray csh process running, and the logout was two stage which could get confusing. So we changed it to exec ksh which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh is not a login-shell).

  3. Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4 etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.

You have obviously seen exec used somewhere, perhaps if you showed the code that's bugging you we could justify its use.

Edit: I realised that my answer above is incomplete. There are two uses of exec in shells like ksh and bash - used for opening file descriptors. Here are some examples:

exec 3< thisfile          # open "thisfile" for reading on file descriptor 3
exec 4> thatfile          # open "thatfile" for writing on file descriptor 4
exec 8<> tother           # open "tother" for reading and writing on fd 8
exec 6>> other            # open "other" for appending on file descriptor 6
exec 5<&0                 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4                 # copy write file descriptor 4 onto 7
exec 3<&-                 # close the read file descriptor 3
exec 6>&-                 # close the write file descriptor 6

Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec reverts to the original meaning:

  exec 3 < thisfile       # oops, overwrite the current program with command "3"

There are several ways you can use these, on ksh use read -u or print -u, on bash, for example:

read <&3
echo stuff >&4

CSS Disabled scrolling

I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype

Change / Add syntax highlighting for a language in Sublime 2/3

I finally found a way to customize the given Themes.

Go to C:\Program Files\Sublime Text 3\Packages and copy + rename Color Scheme - Default.sublime-package to Color Scheme - Default.zip. Afterwards unzip it and copy the Theme, you want to change to %APPDATA%\Sublime Text 3\Packages\User. (In my case, All Hallow's Eve.tmTheme).

Then you can open it with any Text Editor and change / add something, for example for changing this in JavaScript:

<dict>
    <key>name</key>
    <string>Lang Variable</string>
    <key>scope</key>
    <string>variable.language</string>
    <key>settings</key>
    <dict>
        <key>foreground</key>
        <string>#FF0000</string>
    </dict>
</dict>

This will mark this in JavaScript Files red. You can select your Theme under Preferences -> Color Scheme -> User -> <Your Name>.

Command to list all files in a folder as well as sub-folders in windows

An addition to the answer: when you do not want to list the folders, only the files in the subfolders, use /A-D switch like this:

dir ..\myfolder /b /s /A-D /o:gn>list.txt

Saving changes after table edit in SQL Server Management Studio

Go into Tools -> Options -> Designers-> Uncheck "Prevent saving changes that require table re-creation". Voila.

That happens because sometimes it is necessary to drop and recreate a table in order to change something. This can take a while, since all data must be copied to a temp table and then re-inserted in the new table. Since SQL Server by default doesn't trust you, you need to say "OK, I know what I'm doing, now let me do my work."

How to split a string content into an array of strings in PowerShell?

As of PowerShell 2, simple:

$recipients = $addresses -split "; "

Note that the right hand side is actually a case-insensitive regular expression, not a simple match. Use csplit to force case-sensitivity. See about_Split for more details.

Determine if variable is defined in Python

One possible situation where this might be needed:

If you are using finally block to close connections but in the try block, the program exits with sys.exit() before the connection is defined. In this case, the finally block will be called and the connection closing statement will fail since no connection was created.

Removing an element from an Array (Java)

You can not change the length of an array, but you can change the values the index holds by copying new values and store them to a existing index number. 1=mike , 2=jeff // 10 = george 11 goes to 1 overwriting mike .

Object[] array = new Object[10];
int count = -1;

public void myFunction(String string) {
    count++;
    if(count == array.length) { 
        count = 0;  // overwrite first
    }
    array[count] = string;    
}

How to remove a class from elements in pure JavaScript?

Find elements:

var elements = document.getElementsByClassName('widget hover');

Since elements is a live array and reflects all dom changes you can remove all hover classes with a simple while loop:

while(elements.length > 0){
    elements[0].classList.remove('hover');
}

How can I compile a Java program in Eclipse without running it?

You can un-check the build automatically in Project menu and then build by hand by type Ctrl + B, or clicking an icon the appears to the right of the printer icon.

anaconda - path environment variable in windows

C:\Users\\Anaconda3

I just added above path , to my path environment variables and it worked. Now, all we have to do is to move to the .py script location directory, open the cmd with that location and run to see the output.

How to make Twitter bootstrap modal full screen

I achieved this in Bootstrap 3 with the following code:

.modal-dialog {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.modal-content {
  height: auto;
  min-height: 100%;
  border-radius: 0;
}

In general, when you have questions about spacing / padding issues, try right+clicking (or cmd+clicking on mac) the element and select "inspect element" on Chrome or "inspect element with firebug" on Firefox. Try selecting different HTML elements in the "elements" panel and editing the CSS on the right in real-time until you get the padding / spacing you want.

Here is a live demo

Here is a link to the fiddle

How do you get the logical xor of two variables in Python?

As I don't see the simple variant of xor using variable arguments and only operation on Truth values True or False, I'll just throw it here for anyone to use. It's as noted by others, pretty (not to say very) straightforward.

def xor(*vars):
    result = False
    for v in vars:
        result = result ^ bool(v)
    return result

And usage is straightforward as well:

if xor(False, False, True, False):
    print "Hello World!"

As this is the generalized n-ary logical XOR, it's truth value will be True whenever the number of True operands is odd (and not only when exactly one is True, this is just one case in which n-ary XOR is True).

Thus if you are in search of a n-ary predicate that is only True when exactly one of it's operands is, you might want to use:

def isOne(*vars):
    result = False
    for v in vars:
        if result and v:
            return False
        else:
            result = result or v
    return result

How to setup Tomcat server in Netbeans?

If TomCat is install. Perhaps it is not installed Java EE. Services-> plug-ins-> additional plug-ins-> in the search dial tomcat. and install the module java ee. then in the services, servers, add the tomcat server.

Exit/save edit to sudoers file? Putty SSH

The tutorial you saw was telling you how to exit nano editor. By typing Ctrl+X nano exits and if your file needs change you will be prompted to save the changes in which case to save you should press Y and then enter to save changes in the same file you open.

If you are not using any gui and you just want to leave the shell the command is Ctrl+D.

Regarding tutorial, The Linux Documentation Project would be a good place to start. If you like books I would recommend by far any book you want from O'Reilly. They have nice cd bookshelfs with good compilation for any linux sysadmin, and without much effort you can find many places where those html bookshelfs are available to read online.

Can functions be passed as parameters?

Yes, consider some of these examples:

package main

import "fmt"

// convert types take an int and return a string value.
type convert func(int) string

// value implements convert, returning x as string.
func value(x int) string {
    return fmt.Sprintf("%v", x)
}

// quote123 passes 123 to convert func and returns quoted string.
func quote123(fn convert) string {
    return fmt.Sprintf("%q", fn(123))
}

func main() {
    var result string

    result = value(123)
    fmt.Println(result)
    // Output: 123

    result = quote123(value)
    fmt.Println(result)
    // Output: "123"

    result = quote123(func(x int) string { return fmt.Sprintf("%b", x) })
    fmt.Println(result)
    // Output: "1111011"

    foo := func(x int) string { return "foo" }
    result = quote123(foo)
    fmt.Println(result)
    // Output: "foo"

    _ = convert(foo) // confirm foo satisfies convert at runtime

    // fails due to argument type
    // _ = convert(func(x float64) string { return "" })
}

Play: http://play.golang.org/p/XNMtrDUDS0

Tour: https://tour.golang.org/moretypes/25 (Function Closures)

Insert an element at a specific index in a list and return the updated list

Use the Python list insert() method. Usage:

#Syntax

The syntax for the insert() method -

list.insert(index, obj)

#Parameters

  • index - This is the Index where the object obj need to be inserted.
  • obj - This is the Object to be inserted into the given list.

#Return Value This method does not return any value, but it inserts the given element at the given index.

Example:

a = [1,2,4,5]

a.insert(2,3)

print(a)

Returns [1, 2, 3, 4, 5]

How to create an Array, ArrayList, Stack and Queue in Java?

Without more details as to what the question is exactly asking, I am going to answer the title of the question,

Create an Array:

String[] myArray = new String[2];
int[] intArray = new int[2];

// or can be declared as follows
String[] myArray = {"this", "is", "my", "array"};
int[] intArray = {1,2,3,4};

Create an ArrayList:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");

ArrayList<Integer> myNum = new ArrayList<Integer>();
myNum.add(1);
myNum.add(2);

This means, create an ArrayList of String and Integer objects. You cannot use int because thats a primitive data types, see the link for a list of primitive data types.

Create a Stack:

Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);

Create an Queue: (using LinkedList)

Queue<String> myQueue = new LinkedList<String>();
Queue<Integer> myNumbers = new LinkedList<Integer>();
myQueue.add("Hello");
myQueue.add("World");
myNumbers.add(1);
myNumbers.add(2);

Same thing as an ArrayList, this declaration means create an Queue of String and Integer objects.


Update:

In response to your comment from the other given answer,

i am pretty confused now, why are using string. and what does <String> means

We are using String only as a pure example, but you can add any other object, but the main point is that you use an object not a primitive type. Each primitive data type has their own primitive wrapper class, see link for list of primitive data type's wrapper class.

I have posted some links to explain the difference between the two, but here are a list of primitive types

  • byte
  • short
  • char
  • int
  • long
  • boolean
  • double
  • float

Which means, you are not allowed to make an ArrayList of integer's like so:

ArrayList<int> numbers = new ArrayList<int>(); 
           ^ should be an object, int is not an object, but Integer is!
ArrayList<Integer> numbers = new ArrayList<Integer>();
            ^ perfectly valid

Also, you can use your own objects, here is my Monster object I created,

public class Monster {
   String name = null;
   String location = null;
   int age = 0;

public Monster(String name, String loc, int age) { 
   this.name = name;
   this.loc = location;
   this.age = age;
 }

public void printDetails() {
   System.out.println(name + " is from " + location +
                                     " and is " + age + " old.");
 }
} 

Here we have a Monster object, but now in our Main.java class we want to keep a record of all our Monster's that we create, so let's add them to an ArrayList

public class Main {
    ArrayList<Monster> myMonsters = new ArrayList<Monster>();

public Main() {
    Monster yetti = new Monster("Yetti", "The Mountains", 77);
    Monster lochness = new Monster("Lochness Monster", "Scotland", 20);

    myMonsters.add(yetti); // <-- added Yetti to our list
    myMonsters.add(lochness); // <--added Lochness to our list
  
    for (Monster m : myMonsters) {
        m.printDetails();
     }
   }

public static void main(String[] args) {
    new Main();
 }
}

(I helped my girlfriend's brother with a Java game, and he had to do something along those lines as well, but I hope the example was well demonstrated)

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

def dict_to_object(dick):
    # http://stackoverflow.com/a/1305663/968442

    class Struct:
        def __init__(self, **entries):
            self.__dict__.update(entries)

    return Struct(**dick)

If one decides to permanently convert that dict to object this should do. You can create a throwaway object just before accessing.

d = dict_to_object(d)

How do you put an image file in a json object?

To upload files directly to Mongo DB you can make use of Grid FS. Although I will suggest you to upload the file anywhere in file system and put the image's url in the JSON object for every entry and then when you call the data for specific object you can call for the image using URL.

Tell me which backend technology are you using? I can give more suggestions based on that.

Convert InputStream to byte array in Java

Do you really need the image as a byte[]? What exactly do you expect in the byte[] - the complete content of an image file, encoded in whatever format the image file is in, or RGB pixel values?

Other answers here show you how to read a file into a byte[]. Your byte[] will contain the exact contents of the file, and you'd need to decode that to do anything with the image data.

Java's standard API for reading (and writing) images is the ImageIO API, which you can find in the package javax.imageio. You can read in an image from a file with just a single line of code:

BufferedImage image = ImageIO.read(new File("image.jpg"));

This will give you a BufferedImage, not a byte[]. To get at the image data, you can call getRaster() on the BufferedImage. This will give you a Raster object, which has methods to access the pixel data (it has several getPixel() / getPixels() methods).

Lookup the API documentation for javax.imageio.ImageIO, java.awt.image.BufferedImage, java.awt.image.Raster etc.

ImageIO supports a number of image formats by default: JPEG, PNG, BMP, WBMP and GIF. It's possible to add support for more formats (you'd need a plug-in that implements the ImageIO service provider interface).

See also the following tutorial: Working with Images

The simplest possible JavaScript countdown timer?

I have two demos, one with jQuery and one without. Neither use date functions and are about as simple as it gets.

Demo with vanilla JavaScript

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var timer = duration, minutes, seconds;_x000D_
    setInterval(function () {_x000D_
        minutes = parseInt(timer / 60, 10);_x000D_
        seconds = parseInt(timer % 60, 10);_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds;_x000D_
_x000D_
        if (--timer < 0) {_x000D_
            timer = duration;_x000D_
        }_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Demo with jQuery

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});

However if you want a more accurate timer that is only slightly more complicated:

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var start = Date.now(),_x000D_
        diff,_x000D_
        minutes,_x000D_
        seconds;_x000D_
    function timer() {_x000D_
        // get the number of seconds that have elapsed since _x000D_
        // startTimer() was called_x000D_
        diff = duration - (((Date.now() - start) / 1000) | 0);_x000D_
_x000D_
        // does the same job as parseInt truncates the float_x000D_
        minutes = (diff / 60) | 0;_x000D_
        seconds = (diff % 60) | 0;_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds; _x000D_
_x000D_
        if (diff <= 0) {_x000D_
            // add one second so that the count down starts at the full duration_x000D_
            // example 05:00 not 04:59_x000D_
            start = Date.now() + 1000;_x000D_
        }_x000D_
    };_x000D_
    // we don't want to wait a full second before the timer starts_x000D_
    timer();_x000D_
    setInterval(timer, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time"></span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"

  • Should a count down timer count down? Yes
  • Should a count down timer know how to display itself on the DOM? No
  • Should a count down timer know to restart itself when it reaches 0? No
  • Should a count down timer provide a way for a client to access how much time is left? Yes

So with these things in mind lets write a better (but still very simple) CountDownTimer

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer functions.

An example that displays the time in XX:XX format and restarts after reaching 00:00

An example that displays the time in two different formats

An example that has two different timers and only one restarts

An example that starts the count down timer when a button is pressed

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set radio button checked as default in radiogroup?

It's a bug of RadioGroup

RadioButton radioBtn2 = new RadioButton(context);

radioBtn2 without viewId, and generateViewId is in onChildViewAdded()

public void onChildViewAdded(View parent, View child) {
    if (parent == RadioGroup.this && child instanceof RadioButton) {
        int id = child.getId();
        // generates an id if it's missing
        if (id == View.NO_ID) {
            id = View.generateViewId();
            child.setId(id);
        }
        ((RadioButton) child).setOnCheckedChangeWidgetListener(
                mChildOnCheckedChangeListener);
    }

    if (mOnHierarchyChangeListener != null) {
        mOnHierarchyChangeListener.onChildViewAdded(parent, child);
    }
}

so, first radioGroup.addView(radioBtn2), then radioBtn2.setChecked(true);

Like this:

RadioGroup radioGroup = new RadioGroup(context);
RadioButton radioBtn1 = new RadioButton(context);
RadioButton radioBtn2 = new RadioButton(context);
RadioButton radioBtn3 = new RadioButton(context);

radioBtn1.setText("Less");
radioBtn2.setText("Normal");
radioBtn3.setText("More");

radioGroup.addView(radioBtn1);
radioGroup.addView(radioBtn2);
radioGroup.addView(radioBtn3);

radioBtn2.setChecked(true);

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

This error message...

Selenium message:session not created: This version of ChromeDriver only supports Chrome version 74
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Mac OS X 10.14.3 x86_64)

...implies that the ChromeDriver expects the Chrome Browser version to be 74.


Quick installation of the latest ChromeDriver

To install the latest version of ChromeDriver you can use:

  • Mac users with Homebrew: brew tap homebrew/cask && brew cask install chromedriver
  • Debian based Linux distros: sudo apt-get install chromium-chromedriver
  • Windows users with Chocolatey installed: choco install chromedriver

Analysis

Your main issue is the incompatibility between the version of the binaries you are using as follows:

Supports Chrome v74

  • You are using the currently released chrome=73.0

So there is a clear mismatch between the ChromeDriver v74.0.3729.6 and the Chrome Browser v73.0


Solution

  • Downgrade ChromeDriver to ChromeDriver v73.0.3683.68 level.
  • Keep Chrome version at Chrome v73 level. (as per ChromeDriver v73.0.3683.68 release notes)
  • Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
  • If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.
  • Execute your @Test.
  • Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Reference

You can find a relevant detailed discussion in:

How to enable local network users to access my WAMP sites?

I have some experiences in Wamp 3.0 and Apache 2.4 .

After all works do this steps:

1- Disable nod32.

2- Add this line to <VirtualHost *:80> block in httpd-vhosts.conf file:

Require ip 192.168.100 #client ip, allow 192.168.100.### ip's access

How do I get a UTC Timestamp in JavaScript?

I think this what you are expecting...

var currTimestamp = Date.now(), //1482905176396
    utcDateString = (new Date(currTimestamp)).toUTCString(); //"Wed, 28 Dec 2016 06:06:50 GMT"

Now,

new Date(utcDateString).getTime(); //This will give you UTC Timestamp in JavaScript

CSS disable hover effect

You can achieve this using :not selector:

HTML code:

<a class="button">Click me</a>
<a class="button disable">Click me</a>

CSS code (using scss):

.button {
  background-color: red;
  &:not(.disable):hover {
    /* apply hover effect here */
  }   
}

In this way you apply the hover effect style when a specified class (.disable) is not applied.

How to change text color of simple list item

Another simplest way is to create a layout file containing the textview you want with textSize, textStyle, color etc preferred by you and then use it with the ArrayAdapter.

e.g. mytextview.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv"
    android:textColor="@color/font_content"
    android:padding="5sp"
    android:layout_width="fill_parent"
    android:background="@drawable/rectgrad"
    android:singleLine="true"
    android:gravity="center"
    android:layout_height="fill_parent"/>

and then use it with your ArrayAdapter as usual like

ListView lst = new ListView(context);
String[] arr = {"Item 1","Item 2"};
ArrayAdapter<String> ad = new ArrayAdapter<String>(context,R.layout.mytextview,arr);
lst.setAdapter(ad);

This way you won't need to create a custom adapter for it.

How do I combine two data-frames based on two columns?

You can also use the join command (dplyr).

For example:

new_dataset <- dataset1 %>% right_join(dataset2, by=c("column1","column2"))

Visual Studio 2012 Web Publish doesn't copy files

An easy fix is to delete your publish profile and create a fresh one.

when you right click on your solution and select publish, you have a profile set. delete this and create a new one.

this will fix it.

I had this problem from switching from 2010 to 2012

Scala best way of turning a Collection into a Map-by-key?

This can be implemented immutably and with a single traversal by folding through the collection as follows.

val map = c.foldLeft(Map[P, T]()) { (m, t) => m + (t.getP -> t) }

The solution works because adding to an immutable Map returns a new immutable Map with the additional entry and this value serves as the accumulator through the fold operation.

The tradeoff here is the simplicity of the code versus its efficiency. So, for large collections, this approach may be more suitable than using 2 traversal implementations such as applying map and toMap.

Purge or recreate a Ruby on Rails database

To drop a particular database, you can do this on rails console:

$rails console
Loading development environment
1.9.3 > ActiveRecord::Migration.drop_table(:<table_name>)
1.9.3 > exit

And then migrate DB again

$bundle exec rake db:migrate 

Use of "global" keyword in Python

It means that you should not do the following:

x = 1

def myfunc():
  global x

  # formal parameter
  def localfunction(x):
    return x+1

  # import statement
  import os.path as x

  # for loop control target
  for x in range(10):
    print x

  # class definition
  class x(object):
    def __init__(self):
      pass

  #function definition
  def x():
    print "I'm bad"

Get a list of numbers as input from the user

you can pass a string representation of the list to json:

import json

str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)

user enters in the list as you would in python: [2, 34, 5.6, 90]

How to remove the last element added into the List?

if you need to do it more often , you can even create your own method for pop the last element; something like this:

public void pop(List<string> myList) {
    myList.RemoveAt(myList.Count - 1);
}

or even instead of void you can return the value like:

public string pop (List<string> myList) {
    // first assign the  last value to a seperate string 
    string extractedString = myList(myList.Count - 1);
    // then remove it from list
    myList.RemoveAt(myList.Count - 1);
    // then return the value 
    return extractedString;
}

just notice that the second method's return type is not void , it is string b/c we want that function to return us a string ...

'npm' is not recognized as internal or external command, operable program or batch file

I faced the exact same issue and notice that after installing node.js there was a new path entry in the user variable section for PATH with value --> c:\User\\AppData\Roaming\npm. Also the Path entry in the system variable is appended with --> C:\Program Files\nodejs. Now since user variable has preference over system you have two options to fix this. Either delete the path from user variable or correct the right path (C:\Program Files\nodejs). Restart CMD and it should work.

default select option as blank

just use "..option hidden selected.." as default option

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Javascript use variable as object name

One of the challenges I had with the answers is that it assumed that the object was a single level. For example,

const testObj = { testKey: 'testValue' }
const refString = 'testKey';
const refObj = testObj[refString];

works fine, but

const testObj = { testKey:
                  { level2Key: 'level2Value' }
                }
const refString = 'testKey.level2Key';
const refObj = testObj[refString];

does not work.

What I ended up doing was building a function to access multi-level objects:

objVar(str) {
    let obj = this;
    const parts = str.split('.');
    for (let p of parts) {
        obj = obj[p];
    }
    return obj;
}

In the second scenario, then, I can pass the string to this function to get back the object I'm looking for:

const testObj = { testKey:
                  { level2Key: 'level2Value' }
                }
const refString = 'testObj.testKey.level2Key';
const refObj = objVar[refString];

Bootstrap visible and hidden classes not working properly

No CSS required, visible class should like this: visible-md-block not just visible-md and the code should be like this:

<div class="containerdiv hidden-sm hidden-xs visible-md-block visible-lg-block">
    <div class="row">
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 logo">

        </div>
    </div>
</div>

<div class="mobile hidden-md hidden-lg ">
    test
</div>

Extra css is not required at all.

How to use JavaScript variables in jQuery selectors?

var x = $(this).attr("name");
$("#" + x).hide();

How to add Options Menu to Fragment in Android

on your onCreate method add setHasOptionMenu()

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

Then override your onCreateOptionsMenu

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.add("Menu item")
            .setIcon(android.R.drawable.ic_delete)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}

Remove blue border from css custom-styled button in Chrome

I faced the same issue so I used simple CSS-

.custom-button {
    outline: none
}

There can be only one auto column

My MySQL says "Incorrect table definition; there can be only one auto column and it must be defined as a key" So when I added primary key as below it started working:

CREATE TABLE book (
   id INT AUTO_INCREMENT NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL,
   primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

What is a "slug" in Django?

A "slug" is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.

An example:

<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>

Now let's pretend that we have a Django model such as:

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=1000)
    slug = models.SlugField(max_length=40)

How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this:

www.example.com/article/23

Or, you might want to reference the title like this:

www.example.com/article/The 46 Year Old Virgin

Since spaces aren't valid in URLs, they must be replaced by %20, which results in:

www.example.com/article/The%2046%20Year%20Old%20Virgin

Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:

www.example.com/article/the-46-year-old-virgin

In this example, the-46-year-old-virgin is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens -.

Also see the URL of this very web page for another example.

Python TypeError: not enough arguments for format string

You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

Absolute positioning ignoring padding of parent

Could have easily done using an extra level of Div.

<div style="background-color: blue; padding: 10px; position: relative; height: 100px;">
  <div style="position: absolute; left: 0px; right: 0px; bottom: 10px; padding:0px 10px;">
    <div style="background-color: gray;">css sux</div>
  </div>
</div>

Demo: https://jsfiddle.net/soxv3vr0/

jQuery click event not working after adding class

Since the class is added dynamically, you need to use event delegation to register the event handler

$(document).on('click', "a.tabclick", function() {
    var liId = $(this).parent("li").attr("id");
    alert(liId);        
});

How to find out when a particular table was created in Oracle?

Try this query:

SELECT sysdate FROM schema_name.table_name;

This should display the timestamp that you might need.

How do you get the width and height of a multi-dimensional array?

ary.GetLength(0) 
ary.GetLength(1)

for 2 dimensional array

How can I get the current directory name in Javascript?

An interesting approach to get the dirname of the current URL is to make use of your browser's built-in path resolution. You can do that by:

  1. Create a link to ., i.e. the current directory
  2. Use the HTMLAnchorElement interface of the link to get the resolved URL or path equivalent to ..

Here's one line of code that does just that:

Object.assign(document.createElement('a'), {href: '.'}).pathname

In contrast to some of the other solutions presented here, the result of this method will always have a trailing slash. E.g. running it on this page will yield /questions/3151436/, running it on https://stackoverflow.com/ will yield /.

It's also easy to get the full URL instead of the path. Just read the href property instead of pathname.

Finally, this approach should work in even the most ancient browsers if you don't use Object.assign:

function getCurrentDir () {
    var link = document.createElement('a');
    link.href = '.';
    return link.pathname;
}

Git, fatal: The remote end hung up unexpectedly

I was facing a similar error uploading a large repo, "fatal: The remote end hung up unexpectedly" without any further details.

After a lot of research, here's what I did:

  • Using SSH instead of HTTPS, didn't solve the problem.
  • Increasing http.postBuffer incrementally up to a very large value, still no luck.
  • I figured out that it might be because of large files in the repo (as this is a newly migrated repo from perforce), so I recreated the repo using LFS, setting largeFileThreshold to 40m, which greatly reduced the repo size (from 3.5G to 500M). I thought this will solve the problem, but to my surprise I still faced the same error.

Finally, it occurred to me that may be I'm using an older git client, as I didn't see additional error messages. I upgraded git client to latest (2.20.1), and voila, the error is gone!

JBoss vs Tomcat again

First the facts, neither is better. As you already mentioned, Tomcat provides a servlet container that supports the Servlet specification (Tomcat 7 supports Servlet 3.0). JBoss AS, a 'complete' application server supports Java EE 6 (including Servlet 3.0) in its current version.

Tomcat is fairly lightweight and in case you need certain Java EE features beyond the Servlet API, you can easily enhance Tomcat by providing the required libraries as part of your application. For example, if you need JPA features you can include Hibernate or OpenEJB and JPA works nearly out of the box.

How to decide whether to use Tomcat or a full stack Java EE application server:

When starting your project you should have an idea what it requires. If you're in a large enterprise environment JBoss (or any other Java EE server) might be the right choice as it provides built-in support for e.g:

  1. JMS messaging for asynchronous integration
  2. Web Services engine (JAX-WS and/or JAX-RS)
  3. Management capabilities like JMX and a scripted administration interface
  4. Advanced security, e.g. out-of-the-box integration with 3rd party directories
  5. EAR file instead of "only" WAR file support
  6. all the other "great" Java EE features I can't remember :-)

In my opinion Tomcat is a very good fit if it comes to web centric, user facing applications. If backend integration comes into play, a Java EE application server should be (at least) considered. Last but not least, migrating a WAR developed for Tomcat to JBoss should be a 1 day excercise.

Second, you should also take the usage inside your environment into account. In case your organization already runs say 1,000 JBoss instances, you might always go with that regardless of your concrete requirements (consider aspects like cost for operations or upskilling). Of course, this applies vice versa.

my 2 cent

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

How to combine paths in Java?

This solution offers an interface for joining path fragments from a String[] array. It uses java.io.File.File(String parent, String child):

    public static joinPaths(String[] fragments) {
        String emptyPath = "";
        return buildPath(emptyPath, fragments);
    }

    private static buildPath(String path, String[] fragments) {
        if (path == null || path.isEmpty()) {
            path = "";
        }

        if (fragments == null || fragments.length == 0) {
            return "";
        }

        int pathCurrentSize = path.split("/").length;
        int fragmentsLen = fragments.length;

        if (pathCurrentSize <= fragmentsLen) {
            String newPath = new File(path, fragments[pathCurrentSize - 1]).toString();
            path = buildPath(newPath, fragments);
        }

        return path;
    }

Then you can just do:

String[] fragments = {"dir", "anotherDir/", "/filename.txt"};
String path = joinPaths(fragments);

Returns:

"/dir/anotherDir/filename.txt"

How to open VMDK File of the Google-Chrome-OS bundle 2012?

For me my vmdk file was accompanied by a vmx file. Opening the vmx file worked for vmware player.

Why would $_FILES be empty when uploading files to PHP?

Make sure your input element has a 'name' attribute. <input type="file" name="uploadedfile" />

If this is missing the $_FILES will be empty.

Fastest way to count exact number of rows in a very large table?

For Sql server try this

SELECT T.name, 
       I.rows AS [ROWCOUNT] 
FROM   sys.tables AS T 
       INNER JOIN sys.sysindexes AS I 
               ON T.object_id = I.id AND I.indid < 2 
WHERE T.name = 'Your_Table_Name'
ORDER  BY I.rows DESC 

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

With ES6 (or using Babel or Typescipt) you can simply do:

var duplicates = myArray.filter(i => myArray.filter(ii => ii === i).length > 1);

https://es6console.com/j58euhbt/

Spring JPA @Query with LIKE

Another way: instead CONCAT function we can use double pipe: :lastname || '%'

@Query("select c from Customer c where c.lastName LIKE :lastname||'%'")
List<Customer> findCustomByLastName( @Param("lastname") String lastName);

You can put anywhere, prefix, suffix or both

:lastname ||'%'  
'%' || :lastname  
'%' || :lastname || '%'  

Using str_replace so that it only acts on the first match?

If you string does not contains any multibyte characters and if you want to replace only one char you can simply use strpos

Here a function who handle errors

/**
 * Replace the first occurence of given string
 *
 * @param  string $search  a char to search in `$subject`
 * @param  string $replace a char to replace in `$subject`
 * @param  string $subject
 * @return string
 *
 * @throws InvalidArgumentException if `$search` or `$replace` are invalid or if `$subject` is a multibytes string
 */
function str_replace_first(string $search , string $replace , string $subject) : string {
    // check params
    if(strlen($replace) != 1 || strlen($search) != 1) {
        throw new InvalidArgumentException('$search & $replace must be char');
    }elseif(mb_strlen($subject) != strlen($subject)){
        throw new InvalidArgumentException('$subject is an multibytes string');
    }
    // search 
    $pos = strpos($subject, $search);
    if($pos === false) {
        // not found
        return $subject;
    }

    // replace
    $subject[$replace] = $subject;

    return $subject;
}

PHP Sort a multidimensional array by element containing date

From php7 you can use the Spaceship operator:

usort($array, function($a, $b) {
  return new DateTime($a['datetime']) <=> new DateTime($b['datetime']);
});

Is there a .NET/C# wrapper for SQLite?

Here are the ones I can find:

Sources:

'uint32_t' does not name a type

I also encountered the same problem on Mac OSX 10.6.8 and unfortunately adding #include <stdint.h> or <cstdint.h> to the corresponding file did not solve my problem. However, after more search, I found this solution advicing to add #include <sys/types.h> which worked well for me!

Vertically align an image inside a div with responsive height

With flexbox this is easy:

FIDDLE

Just add the following to the image container:

.img-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex; /* add */
    justify-content: center; /* add to align horizontal */
    align-items: center; /* add to align vertical */
}

how to get login option for phpmyadmin in xampp

Step 1:

Locate phpMyAdmin installation path.

Step 2:

Open phpMyAdmin/config.inc.php in your favourite text editor. Copy config.sample.inc.php to config.inc.php if it's missing.

Step 3:

Search for $cfg['Servers'][$i]['auth_type'] = 'config';

Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';

PHP Warning: Division by zero

A lot of the answers here do not work for (string)"0.00".

Try this:

if (isset($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

Or even more strict:

if (isset($_POST['num1']) && is_numeric($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

How to calculate difference in hours (decimal) between two dates in SQL Server?

Just subtract the two datetime values and multiply by 24:

  Select Cast((@DateTime2 - @DateTime1) as Float) * 24.0

a test script might be:

  Declare @Dt1 dateTime Set @Dt1 = '12 Jan 2009 11:34:12'
  Declare @Dt2 dateTime Set @Dt2 = getdate()

  Select Cast((@Dt2 - @Dt1) as Float) * 24.0

This works because all datetimes are stored internally as a pair of integers, the first integer is the number of days since 1 Jan 1900, and the second integer (representing the time) is the number of (1) ticks since Midnight. (For SmallDatetimes the time portion integer is the number of minutes since midnight). Any arithmetic done on the values uses the time portion as a fraction of a day. 6am = 0.25, noon = 0.5, etc... See MSDN link here for more details.

So Cast((@Dt2 - @Dt1) as Float) gives you total days between two datetimes. Multiply by 24 to convert to hours. If you need total minutes, Multiple by Minutes per day (24 * 60 = 1440) instead of 24...

NOTE 1: This is not the same as a dotNet or javaScript tick - this tick is about 3.33 milliseconds.

How can I emulate a get request exactly like a web browser?

Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at http://docs.php.net/function.curl-setopt.
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.

edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.

$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);

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

You can also check if your version is using MKL with:

import numpy
numpy.show_config()

Why is MySQL InnoDB insert so slow?

Solution

  1. Create new UNIQUE key that is identical to your current PRIMARY key
  2. Add new column id is unsigned integer, auto_increment
  3. Create primary key on new id column

Bam, immediate 10x+ insert improvement.

adding 30 minutes to datetime php/mysql

Use DATE_ADD function

DATE_ADD(datecolumn, INTERVAL 30 MINUTE);

C - function inside struct

You can pass the struct pointer to function as function argument. It called pass by reference.

If you modify something inside that pointer, the others will be updated to. Try like this:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;
};

pno AddClient(client_t *client)
{
        /* this will change the original client value */
        client.password = "secret";
}

int main()
{
    client_t client;

    //code ..

    AddClient(&client);
}

How can I access an internal class from an external assembly?

Without access to the type (and no "InternalsVisibleTo" etc) you would have to use reflection. But a better question would be: should you be accessing this data? It isn't part of the public type contract... it sounds to me like it is intended to be treated as an opaque object (for their purposes, not yours).

You've described it as a public instance field; to get this via reflection:

object obj = ...
string value = (string)obj.GetType().GetField("test").GetValue(obj);

If it is actually a property (not a field):

string value = (string)obj.GetType().GetProperty("test").GetValue(obj,null);

If it is non-public, you'll need to use the BindingFlags overload of GetField/GetProperty.

Important aside: be careful with reflection like this; the implementation could change in the next version (breaking your code), or it could be obfuscated (breaking your code), or you might not have enough "trust" (breaking your code). Are you spotting the pattern?

jquery can't get data attribute value

You can change the selector and data attributes as you wish!

 <select id="selectVehicle">
       <option value="1" data-year="2011">Mazda</option>
       <option value="2" data-year="2015">Honda</option>
       <option value="3" data-year="2008">Mercedes</option>
       <option value="4" data-year="2005">Toyota</option>
  </select>

$("#selectVehicle").change(function () {
     alert($(this).find(':selected').data("year"));
});

Here is the working example: https://jsfiddle.net/ed5axgvk/1/

How to search if dictionary value contains certain string with Python

Klaus solution has less overhead, on the other hand this one may be more readable

myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
          'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}

def search(myDict, lookup):
    for key, value in myDict.items():
        for v in value:
            if lookup in v:
                return key

search(myDict, 'Mary')

Default settings Raspberry Pi /etc/network/interfaces

These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:

auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

Modifying a file inside a jar

This may be more work than you're looking to deal with in the short term, but I suspect in the long term it would be very beneficial for you to look into using Ant (or Maven, or even Bazel) instead of building jar's manually. That way you can just click on the ant file (if you use Eclipse) and rebuild the jar.

Alternatively, you may want to actually not have these config files in the jar at all - if you're expecting to need to replace these files regularly, or if it's supposed to be distributed to multiple parties, the config file should not be part of the jar at all.

CodeIgniter - return only one row?

We can get a single using limit in query

_x000D_
_x000D_
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
_x000D_
_x000D_
_x000D_

 $query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);