Programs & Examples On #Uint64

How to program a delay in Swift 3

After a lot of research, I finally figured this one out.

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
   // Code you want to be delayed
}

This creates the desired "wait" effect in Swift 3 and Swift 4.

Inspired by a part of this answer.

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

I coded up an equivalent C program to experiment, and I can confirm this strange behaviour. What's more, gcc believes the 64-bit integer (which should probably be a size_t anyway...) to be better, as using uint_fast32_t causes gcc to use a 64-bit uint.

I did a bit of mucking around with the assembly:
Simply take the 32-bit version, replace all 32-bit instructions/registers with the 64-bit version in the inner popcount-loop of the program. Observation: the code is just as fast as the 32-bit version!

This is obviously a hack, as the size of the variable isn't really 64 bit, as other parts of the program still use the 32-bit version, but as long as the inner popcount-loop dominates performance, this is a good start.

I then copied the inner loop code from the 32-bit version of the program, hacked it up to be 64 bit, fiddled with the registers to make it a replacement for the inner loop of the 64-bit version. This code also runs as fast as the 32-bit version.

My conclusion is that this is bad instruction scheduling by the compiler, not actual speed/latency advantage of 32-bit instructions.

(Caveat: I hacked up assembly, could have broken something without noticing. I don't think so.)

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

I had the same issue on a Windows 10 PC. I copied the project from my old computer to the new one, both 64 bits, and I installed the Oracle Client 64 bit on the new machine. I got the same error message, but after trying many solutions to no effect, what actually worked for me was this: In your Visual Studio (mine is 2017) go to Tools > Options > Projects and Solutions > Web Projects

On that page, check the option that says: Use the 64 bit version of IIS Express for Websites and Projects

size of uint8, uint16 and uint32?

It's quite unclear how you are computing the size ("the size in debug mode"?").

Use printf():

printf("the size of c is %u\n", (unsigned int) sizeof c);

Normally you'd print a size_t value (which is the type sizeof returns) with %zu, but if you're using a pre-C99 compiler like Visual Studio that won't work.

You need to find the typedef statements in your code that define the custom names like uint8 and so on; those are not standard so nobody here can know how they're defined in your code.

New C code should use <stdint.h> which gives you uint8_t and so on.

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

When compiling memcached under Centos 5.x i got the same problem.

The solution is to upgrade gcc and g++ to version 4.4 at least.

Make sure your CC/CXX is set (exported) to right binaries before compiling.

Are types like uint32, int32, uint64, int64 defined in any stdlib header?

If you are using C99 just include stdint.h. BTW, the 64bit types are there iff the processor supports them.

long long int vs. long int vs. int64_t in C++

So my question is: Is there a way to tell the compiler that a long long int is the also a int64_t, just like long int is?

This is a good question or problem, but I suspect the answer is NO.

Also, a long int may not be a long long int.


# if __WORDSIZE == 64
typedef long int  int64_t;
# else
__extension__
typedef long long int  int64_t;
# endif

I believe this is libc. I suspect you want to go deeper.

In both 32-bit compile with GCC (and with 32- and 64-bit MSVC), the output of the program will be:

int:           0
int64_t:       1
long int:      0
long long int: 1

32-bit Linux uses the ILP32 data model. Integers, longs and pointers are 32-bit. The 64-bit type is a long long.

Microsoft documents the ranges at Data Type Ranges. The say the long long is equivalent to __int64.

However, the program resulting from a 64-bit GCC compile will output:

int:           0
int64_t:       1
long int:      1
long long int: 0

64-bit Linux uses the LP64 data model. Longs are 64-bit and long long are 64-bit. As with 32-bit, Microsoft documents the ranges at Data Type Ranges and long long is still __int64.

There's a ILP64 data model where everything is 64-bit. You have to do some extra work to get a definition for your word32 type. Also see papers like 64-Bit Programming Models: Why LP64?


But this is horribly hackish and does not scale well (actual functions of substance, uint64_t, etc)...

Yeah, it gets even better. GCC mixes and matches declarations that are supposed to take 64 bit types, so its easy to get into trouble even though you follow a particular data model. For example, the following causes a compile error and tells you to use -fpermissive:

#if __LP64__
typedef unsigned long word64;
#else
typedef unsigned long long word64;
#endif

// intel definition of rdrand64_step (http://software.intel.com/en-us/node/523864)
// extern int _rdrand64_step(unsigned __int64 *random_val);

// Try it:
word64 val;
int res = rdrand64_step(&val);

It results in:

error: invalid conversion from `word64* {aka long unsigned int*}' to `long long unsigned int*'

So, ignore LP64 and change it to:

typedef unsigned long long word64;

Then, wander over to a 64-bit ARM IoT gadget that defines LP64 and use NEON:

error: invalid conversion from `word64* {aka long long unsigned int*}' to `uint64_t*'

Java equivalent of unsigned long long?

Seems like in Java 8 some methods are added to Long to treat old good [signed] long as unsigned. Seems like a workaround, but may help sometimes.

Is there a constraint that restricts my generic method to numeric types?

There's no constraint for this. It's a real issue for anyone wanting to use generics for numeric calculations.

I'd go further and say we need

static bool GenericFunction<T>(T value) 
    where T : operators( +, -, /, * )

Or even

static bool GenericFunction<T>(T value) 
    where T : Add, Subtract

Unfortunately you only have interfaces, base classes and the keywords struct (must be value-type), class (must be reference type) and new() (must have default constructor)

You could wrap the number in something else (similar to INullable<T>) like here on codeproject.


You could apply the restriction at runtime (by reflecting for the operators or checking for types) but that does lose the advantage of having the generic in the first place.

How can I update a row in a DataTable in VB.NET?

You can access columns by index, by name and some other ways:

dtResult.Rows(i)("columnName") = strVerse

You should probably make sure your DataTable has some columns first...

SQL NVARCHAR and VARCHAR Limits

The accepted answer helped me but I got tripped up while doing concatenation of varchars involving case statements. I know the OP's question does not involve case statements but I thought this would be helpful to post here for others like me who ended up here while struggling to build long dynamic SQL statements involving case statements.

When using case statements with string concatenation the rules mentioned in the accepted answer apply to each section of the case statement independently.

declare @l_sql varchar(max) = ''

set @l_sql = @l_sql +
case when 1=1 then
    --without this correction the result is truncated
    --CONVERT(VARCHAR(MAX), '')
 +REPLICATE('1', 8000)
 +REPLICATE('1', 8000)
end

print len(@l_sql)

How to create EditText with cross(x) button at end of it?

Use

android:drawableRight="@android:drawable/ic_input_delete"

What is the exact meaning of Git Bash?

git bash is a shell where:

See "Fix msysGit Portable $HOME location":

On a Windows 64:

C:\Windows\SysWOW64\cmd.exe /c ""C:\Prog\Git\1.7.1\bin\sh.exe" --login -i"

This differs from git-cmd.bat, which provides git commands in a plain DOS command prompt.

A tool like GitHub for Windows (G4W) provides different shell for git (including a PowerShell one)


Update April 2015:

Note: the git bash in msysgit/Git for windows 1.9.5 is an old one:

GNU bash, version 3.1.20(4)-release (i686-pc-msys)
Copyright (C) 2005 Free Software Foundation, Inc.

But with the phasing out of msysgit (Q4 2015) and the new Git For Windows (Q2 2015), you now have Git for Windows 2.3.5.
It has a much more recent bash, based on the 64bits msys2 project, an independent rewrite of MSYS, based on modern Cygwin (POSIX compatibility layer) and MinGW-w64 with the aim of better interoperability with native Windows software. msys2 comes with its own installer too.

The git bash is now (with the new Git For Windows):

GNU bash, version 4.3.33(3)-release (x86_64-pc-msys)
Copyright (C) 2013 Free Software Foundation, Inc.

Original answer (June 2013) More precisely, from msygit wiki:

Historically, Git on Windows was only officially supported using Cygwin.
To help make a native Windows version, this project was started, based on the mingw fork.

To make the milky 'soup' of project names more clear, we say like this:

  • msysGit - is the name of this project, a build environment for Git for Windows, which releases the official binaries
  • MinGW - is a minimalist development environment for native Microsoft Windows applications.
    It is really a very thin compile-time layer over the Microsoft Runtime; MinGW programs are therefore real Windows programs, with no concept of Unix-style paths or POSIX niceties such as a fork() call
  • MSYS - is a Bourne Shell command line interpreter system, is used by MinGW (and others), was forked in the past from Cygwin
  • Cygwin - a Linux like environment, which was used in the past to build Git for Windows, nowadays has no relation to msysGit

So, your two lines description about "git bash" are:

"Git bash" is a msys shell included in "Git for Windows", and is a slimmed-down version of Cygwin (an old version at that), whose only purpose is to provide enough of a POSIX layer to run a bash.


Reminder:

msysGit is the development environment to compile Git for Windows. It is complete, in the sense that you just need to install msysGit, and then you can build Git. Without installing any 3rd-party software.

msysGit is not Git for Windows; that is an installer which installs Git -- and only Git.

See more in "Difference between msysgit and Cygwin + git?".

Two submit buttons in one form

There’s a new HTML5 approach to this, the formaction attribute:

<button type="submit" formaction="/action_one">First action</button>
<button type="submit" formaction="/action_two">Second action</button>

Apparently this does not work in IE9 and earlier, but for other browsers you should be fine (see: w3schools.com HTML <button> formaction Attribute).

Personally, I generally use Javascript to submit forms remotely (for faster perceived feedback) with this approach as backup. Between the two, the only people not covered are IE<9 with Javascript disabled.

Of course, this may be inappropriate if you’re basically taking the same action server-side regardless of which button was pushed, but often if there are two user-side actions available then they will map to two server-side actions as well.

Edit: As noted by Pascal_dher in the comments, this attribute is also available on the <input> tag as well.

bootstrap button shows blue outline when clicked

Keep in mind, if you're button is inside of an anchor like:

<a href='some_link'>
    <button class='btn'>Button</button>
</a>

Adding the style to the button itself may not be enough, you may need to add the a:focus, a:active { outline: none } CSS rules where appropriate (this worked for me).

What is the difference between char s[] and char *s?

char *s1 = "Hello world"; // Points to fixed character string which is not allowed to modify
char s2[] = "Hello world"; // As good as fixed array of characters in string so allowed to modify

// s1[0] = 'J'; // Illegal
s2[0] = 'J'; // Legal

List of strings to one string

I would go with option A:

String.Join(String.Empty, los.ToArray());

My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...

As per @Nuri YILMAZ without .ToArray(), but this is .NET 4+:

String.Join(String.Empty, los);

How to backup MySQL database in PHP?

Try out following example of using SELECT INTO OUTFILE query for creating table backup. This will only backup a particular table.

<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';

   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $table_name = "employee";
   $backup_file  = "/tmp/employee.sql";
   $sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";

   mysql_select_db('test_db');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not take data backup: ' . mysql_error());
   }

   echo "Backedup  data successfully\n";

   mysql_close($conn);
?>

Moment.js: Date between dates

In versions 2.9+ there is an isBetween function, but it's exclusive:

var compareDate = moment("15/02/2013", "DD/MM/YYYY");
var startDate   = moment("12/01/2013", "DD/MM/YYYY");
var endDate     = moment("15/01/2013", "DD/MM/YYYY");

// omitting the optional third parameter, 'units'
compareDate.isBetween(startDate, endDate); //false in this case

There is an inclusive workaround ...
x.isBetween(a, b) || x.isSame(a) || x.isSame(b)

... which is logically equivalent to
!(x.isBefore(a) || x.isAfter(b))


In version 2.13 the isBetween function has a fourth optional parameter, inclusivity.

Use it like this:

target.isBetween(start, finish, 'days', '()') // default exclusive
target.isBetween(start, finish, 'days', '(]') // right inclusive
target.isBetween(start, finish, 'days', '[)') // left inclusive
target.isBetween(start, finish, 'days', '[]') // all inclusive

More units to consider: years, months, days, hours, minutes, seconds, milliseconds

Note: units are still optional. Use null as the third argument to disregard units in which case milliseconds is the default granularity.

Visit the Official Docs

How to use absolute path in twig functions

The following works for me:

<img src="{{ asset('bundle/myname/img/image.gif', null, true) }}" />

How to disable Django's CSRF validation?

In setting.py in MIDDLEWARE you can simply remove/comment this line:

'django.middleware.csrf.CsrfViewMiddleware',

Finding the length of a Character Array in C

If you want the length of the character array use sizeof(array)/sizeof(array[0]), if you want the length of the string use strlen(array).

Kill detached screen session

Alternatively, while in your screen session all you have to do is type exit

This will kill the shell session initiated by the screen, which effectively terminates the screen session you are on.

No need to bother with screen session id, etc.

How to display the value of the bar on each bar with pyplot.barh()?

Use plt.text() to put text in the plot.

Example:

import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
ind = np.arange(N)

#Creating a figure with some fig size
fig, ax = plt.subplots(figsize = (10,5))
ax.bar(ind,menMeans,width=0.4)
#Now the trick is here.
#plt.text() , you need to give (x,y) location , where you want to put the numbers,
#So here index will give you x pos and data+1 will provide a little gap in y axis.
for index,data in enumerate(menMeans):
    plt.text(x=index , y =data+1 , s=f"{data}" , fontdict=dict(fontsize=20))
plt.tight_layout()
plt.show()

This will show the figure as:

bar chart with values at the top

Is there a destructor for Java?

Just thinking about the original question... which, I think we can conclude from all the other learned answers, and also from Bloch's essential Effective Java, item 7, "Avoid finalizers", seeks the solution to a legitimate question in a manner which is inappropriate to the Java language...:

... wouldn't a pretty obvious solution to do what the OP actually wants be to keep all your objects which need to be reset in a sort of "playpen", to which all other non-resettable objects have references only through some sort of accessor object...

And then when you need to "reset" you disconnect the existing playpen and make a new one: all the web of objects in the playpen is cast adrift, never to return, and one day to be collected by the GC.

If any of these objects are Closeable (or not, but have a close method) you could put them in a Bag in the playpen as they are created (and possibly opened), and the last act of the accessor before cutting off the playpen would be to go through all the Closeables closing them... ?

The code would probably look something like this:

accessor.getPlaypen().closeCloseables();
accessor.setPlaypen( new Playpen() );

closeCloseables would probably be a blocking method, probably involving a latch (e.g. CountdownLatch), to deal with (and wait as appropriate for) any Runnables/Callables in any threads specific to the Playpen to be ended as appropriate, in particular in the JavaFX thread.

Concatenating two std::vectors

vector1.insert( vector1.end(), vector2.begin(), vector2.end() );

how to call a function from another function in Jquery

I think in this case you want something like this:

$(window).resize(resize=function resize(){ some code...}

Now u can call resize() within some other nested functions:

$(window).scroll(function(){ resize();}

Cast IList to List

List<SubProduct> subProducts= (List<SubProduct>)Model.subproduct;

The implicit conversion failes because List<> implements IList, not viceversa. So you can say IList<T> foo = new List<T>(), but not List<T> foo = (some IList-returning method or property).

How can I use Google's Roboto font on a website?

For Website you can use 'Roboto' font as below:

If you have created separate css file then put below line at the top of css file as:

@import url('https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,500,500i,700,700i,900,900i');

Or if you don't want to create separate file then add above line in between <style>...</style>:

<style>
  @import url('https://fonts.googleapis.com/css? 
  family=Roboto:300,300i,400,400i,500,500i,700,700i,900,900i');
</style>

then:

html, body {
    font-family: 'Roboto', sans-serif;
}

getting file size in javascript

You can't get the file size of local files with javascript in a standard way using a web browser.

But if the file is accessible from a remote path, you might be able to send a HEAD request using Javascript, and read the Content-length header, depending on the webserver

Error using eclipse for Android - No resource found that matches the given name

Yet another Googlemare Landmine....

I solved this same problem today: Somehow, if you mess up, the icon line on your .gen file dies. (Empirical proof of mine after struggling 2 hours)

Insert a new icon 72x72 icon on the hdpi folder with a different name from the original, and update the name on the manifest also.

The icon somehow resurrects on the Gen file and voila!! time to move on.

When is it appropriate to use C# partial classes?

Service references are another example where partial classes are useful to separate generated code from user-created code.

You can "extend" the service classes without having them overwritten when you update the service reference.

How to build query string with Javascript

No, I don't think standard JavaScript has that built in, but Prototype JS has that function (surely most other JS frameworks have too, but I don't know them), they call it serialize.

I can reccomend Prototype JS, it works quite okay. The only drawback I've really noticed it it's size (a few hundred kb) and scope (lots of code for ajax, dom, etc.). Thus if you only want a form serializer it's overkill, and strictly speaking if you only want it's Ajax functionality (wich is mainly what I used it for) it's overkill. Unless you're careful you may find that it does a little too much "magic" (like extending every dom element it touches with Prototype JS functions just to find elements) making it slow on extreme cases.

How to remove MySQL completely with config and library files?

Just a little addition to the answer of @dAm2k :

In addition to sudo apt-get remove --purge mysql\*

I've done a sudo apt-get remove --purge mariadb\*.

I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.

Hope it helps.

Simplest way to do a recursive self-join?

Using CTEs you can do it this way

DECLARE @Table TABLE(
        PersonID INT,
        Initials VARCHAR(20),
        ParentID INT
)

INSERT INTO @Table SELECT     1,'CJ',NULL
INSERT INTO @Table SELECT     2,'EB',1
INSERT INTO @Table SELECT     3,'MB',1
INSERT INTO @Table SELECT     4,'SW',2
INSERT INTO @Table SELECT     5,'YT',NULL
INSERT INTO @Table SELECT     6,'IS',5

DECLARE @PersonID INT

SELECT @PersonID = 1

;WITH Selects AS (
        SELECT *
        FROM    @Table
        WHERE   PersonID = @PersonID
        UNION ALL
        SELECT  t.*
        FROM    @Table t INNER JOIN
                Selects s ON t.ParentID = s.PersonID
)
SELECT  *
FROm    Selects

What is JNDI? What is its basic use? When is it used?

What is JNDI ?

JNDI stands for Java Naming and Directory Interface. It comes standard with J2EE.

What is its basic use?

With this API, you can access many types of data, like objects, devices, files of naming and directory services, eg. it is used by EJB to find remote objects. JNDI is designed to provide a common interface to access existing services like DNS, NDS, LDAP, CORBA and RMI.

When it is used?

You can use the JNDI to perform naming operations, including read operations and operations for updating the namespace. The following operations are described here.

What is the difference between server side cookie and client side cookie?

You probably mean the difference between Http Only cookies and their counter part?

Http Only cookies cannot be accessed (read from or written to) in client side JavaScript, only server side. If the Http Only flag is not set, or the cookie is created in (client side) JavaScript, the cookie can be read from and written to in (client side) JavaScript as well as server side.

How to resolve git status "Unmerged paths:"?

All you should need to do is:

# if the file in the right place isn't already committed:
git add <path to desired file>

# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai

# commit the merge:
git commit

Split a large pandas dataframe

you can use list comprehensions to do this in a single line

n = 4
chunks = [df[i:i+n] for i in range(0,df.shape[0],n)]

ASP.net page without a code behind

By default Sharepoint does not allow server-side code to be executed in ASPX files. See this for how to resolve that.

However, I would raise that having a code-behind is not necessarily difficult to deploy in Sharepoint (we do it extensively) - just compile your code-behind classes into an assembly and deploy it using a solution.

If still no, you can include all the code you'd normally place in a codebehind like so:

<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
  //hello, world!
}
</script>

How can I assign the output of a function to a variable using bash?

You may use bash functions in commands/pipelines as you would otherwise use regular programs. The functions are also available to subshells and transitively, Command Substitution:

VAR=$(scan)

Is the straighforward way to achieve the result you want in most cases. I will outline special cases below.

Preserving trailing Newlines:

One of the (usually helpful) side effects of Command Substitution is that it will strip any number of trailing newlines. If one wishes to preserve trailing newlines, one can append a dummy character to output of the subshell, and subsequently strip it with parameter expansion.

function scan2 () {
    local nl=$'\x0a';  # that's just \n
    echo "output${nl}${nl}" # 2 in the string + 1 by echo
}

# append a character to the total output.
# and strip it with %% parameter expansion.
VAR=$(scan2; echo "x"); VAR="${VAR%%x}"

echo "${VAR}---"

prints (3 newlines kept):

output


---

Use an output parameter: avoiding the subshell (and preserving newlines)

If what the function tries to achieve is to "return" a string into a variable , with bash v4.3 and up, one can use what's called a nameref. Namerefs allows a function to take the name of one or more variables output parameters. You can assign things to a nameref variable, and it is as if you changed the variable it 'points to/references'.

function scan3() {
    local -n outvar=$1    # -n makes it a nameref.
    local nl=$'\x0a'
    outvar="output${nl}${nl}"  # two total. quotes preserve newlines
}

VAR="some prior value which will get overwritten"

# you pass the name of the variable. VAR will be modified.
scan3 VAR

# newlines are also preserved.
echo "${VAR}==="

prints:

output

===

This form has a few advantages. Namely, it allows your function to modify the environment of the caller without using global variables everywhere.

Note: using namerefs can improve the performance of your program greatly if your functions rely heavily on bash builtins, because it avoids the creation of a subshell that is thrown away just after. This generally makes more sense for small functions reused often, e.g. functions ending in echo "$returnstring"

This is relevant. https://stackoverflow.com/a/38997681/5556676

jQuery.click() vs onClick

Most of the time, native JavaScript methods are a better choice over jQuery when performance is the only criteria, but jQuery makes use of JavaScript and makes the development easy. You can use jQuery as it does not degrade performance too much. In your specific case, the difference of performance is ignorable.

How to copy data from one table to another new table in MySQL?

CREATE TABLE newTable LIKE oldTable;

Then, to copy the data over

INSERT INTO newTable SELECT * FROM oldTable;

Create a simple HTTP server with Java?

Jetty is a great way to easily embed an HTTP server. It supports it's own simple way to attach handlers and is a full J2EE app server if you need more functionality.

Run a string as a command within a Bash script

I usually place commands in parentheses $(commandStr), if that doesn't help I find bash debug mode great, run the script as bash -x script

Solution to "subquery returns more than 1 row" error

You can use in():

select * 
from table
where id in (multiple row query)

or use a join:

select distinct t.* 
from source_of_id_table s
join table t on t.id = s.t_id
where <conditions for source_of_id_table>

The join is never a worse choice for performance, and depending on the exact situation and the database you're using, can give much better performance.

Online SQL syntax checker conforming to multiple databases

I haven't ever seen such a thing, but there is this dev tool that includes a syntax checker for oracle, mysql, db2, and sql server... http://www.sqlparser.com/index.php

However this seems to be just the library. You'd need to build an app to leverage the parser to do what you want. And the Enterprise edition that includes all of the databases would cost you $450... ouch!

EDIT: And, after saying that - it looks like someone might already have done what you want using that library: http://www.wangz.net/cgi-bin/pp/gsqlparser/sqlpp/sqlformat.tpl

The online tool doesn't automatically check against each DB though, you need to run each manually. Nor can I say how good it is at checking the syntax. That you'd need to investigate yourself.

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

Imagine you have a numpy array of integers (it works with other types but you need some slight modification). You can do this:

a = np.array([0, 3, 5])
a_str = ','.join(str(x) for x in a) # '0,3,5'
a2 = np.array([int(x) for x in a_str.split(',')]) # np.array([0, 3, 5])

If you have an array of float, be sure to replace int by float in the last line.

You can also use the __repr__() method, which will have the advantage to work for multi-dimensional arrays:

from numpy import array
numpy.set_printoptions(threshold=numpy.nan)
a = array([[0,3,5],[2,3,4]])
a_str = a.__repr__() # 'array([[0, 3, 5],\n       [2, 3, 4]])'
a2 = eval(a_str) # array([[0, 3, 5],
                 #        [2, 3, 4]])

jQuery set radio button

Why do you need 'input:radio[name=cols]'. Don't know your html, but assuming that ids are unique, you can simply do this.

$('#'+newcol).prop('checked', true);

LINQ with groupby and count

userInfos.GroupBy(userInfo => userInfo.metric)
        .OrderBy(group => group.Key)
        .Select(group => Tuple.Create(group.Key, group.Count()));

How to set initial size of std::vector?

std::vector<CustomClass *> whatever(20000);

or:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

ByRef argument type mismatch in Excel VBA

It looks like ByRef needs to know the size of the parameter. A declaration of Dim last_name as string doesn't specify the size of the string so it takes it as an error. Before using Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name) The last_name has to be declared as Dim last_name as string *10 ' size of string is up to you but must be a fix length

No need to change the function. Function doesn't take a fix length declaration.

jQuery Event Keypress: Which key was pressed?

If you are using jQuery UI you have translations for common key codes. In ui/ui/ui.core.js:

$.ui.keyCode = { 
    ...
    ENTER: 13, 
    ...
};

There's also some translations in tests/simulate/jquery.simulate.js but I could not find any in the core JS library. Mind you, I merely grep'ed the sources. Maybe there is some other way to get rid of these magic numbers.

You can also make use of String.charCodeAt and .fromCharCode:

>>> String.charCodeAt('\r') == 13
true
>>> String.fromCharCode(13) == '\r'
true

How do I get the current year using SQL on Oracle?

Use extract(datetime) function it's so easy, simple.

It returns year, month, day, minute, second

Example:

select extract(year from sysdate) from dual;

Clear the cache in JavaScript

window.location.reload(true) seems to have been deprecated by the HTML5 standard. One way to do this without using query strings is to use the Clear-Site-Data header, which seems to being standardized.

Tab Escape Character?

Easy one! "\t"

Edit: In fact, here's something official: Escape Sequences

selecting unique values from a column

Depends on what you need.

In this case I suggest:

SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;

because there are few fields and the execution time of DISTINCT is lower than the execution of GROUP BY.

In other cases, for example where there are many fields, I prefer:

SELECT * FROM buy GROUP BY date ORDER BY date DESC;

Python Prime number checker

max=int(input("Find primes upto what numbers?"))
primeList=[]
for x in range(2,max+1):
    isPrime=True
    for y in range(2,int(x**0.5)+1) :
        if x%y==0:
            isPrime=False
            break

    if isPrime:
        primeList.append(x)
print(primeList)

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

This answer seems relevant since the OP makes reference to a need for a multi-OS solution. This Github help article details available approaches for handling lines endings cross-OS. There are global and per-repo approaches to managing cross-os line endings.

Global approach

Configure Git line endings handling on Linux or OS X:

git config --global core.autocrlf input

Configure Git line endings handling on Windows:

git config --global core.autocrlf true

Per-repo approach:

In the root of your repo, create a .gitattributes file and define line ending settings for your project files, one line at a time in the following format: path_regex line-ending-settings where line-ending-settings is one of the following:

  • text
  • binary (files that Git should not modify line endings for - as this can cause some image types such as PNGs not to render in a browser)

The text value can be configured further to instruct Git on how to handle line endings for matching files:

  • text - Changes line endings to OS native line endings.
  • text eol=crlf - Converts line endings to CRLF on checkout.
  • text eol=lf - Converts line endings to LF on checkout.
  • text=auto - Sensible default that leaves line handle up to Git's discretion.

Here is the content of a sample .gitattributes file:

# Set the default behavior for all files.
* text=auto

# Normalized and converts to 
# native line endings on checkout.
*.c text
*.h text

# Convert to CRLF line endings on checkout.
*.sln text eol=crlf

# Convert to LF line endings on checkout.
*.sh text eol=lf

# Binary files.
*.png binary
*.jpg binary

More on how to refresh your repo after changing line endings settings here. Tldr:

backup your files with Git, delete every file in your repository (except the .git directory), and then restore the files all at once. Save your current files in Git, so that none of your work is lost.

git add . -u

git commit -m "Saving files before refreshing line endings"

Remove the index and force Git to rescan the working directory.

rm .git/index

Rewrite the Git index to pick up all the new line endings.

git reset

Show the rewritten, normalized files.

In some cases, this is all that needs to be done. Others may need to complete the following additional steps:

git status

Add all your changed files back, and prepare them for a commit. This is your chance to inspect which files, if any, were unchanged.

git add -u

It is perfectly safe to see a lot of messages here that read[s] "warning: CRLF will be replaced by LF in file."

Rewrite the .gitattributes file.

git add .gitattributes

Commit the changes to your repository.

git commit -m "Normalize all the line endings"

Test for array of string type in TypeScript

You can have do it easily using Array.prototype.some() as below.

const isStringArray = (test: any[]): boolean => {
 return Array.isArray(test) && !test.some((value) => typeof value !== 'string')
}
const myArray = ["A", "B", "C"]
console.log(isStringArray(myArray)) // will be log true if string array

I believe this approach is better that others. That is why I am posting this answer.

Update on Sebastian Vittersø's comment

Here you can use Array.prototype.every() as well.

const isStringArray = (test: any[]): boolean => {
 return Array.isArray(test) && test.every((value) => typeof value === 'string')
}

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h looks like a syntax error.

Android TextView padding between lines

You can use lineSpacingExtra and lineSpacingMultiplier in your XML file.

Align nav-items to right side in bootstrap-4

In last versions, it is easier. Just put a ml-auto class in the ul like so:

<ul class="nav navbar-nav ml-auto">

Calculate summary statistics of columns in dataframe

describe may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once

In [43]:

df.describe()

Out[43]:

       shopper_num is_martian  number_of_items  count_pineapples
count      14.0000         14        14.000000                14
mean        7.5000          0         3.357143                 0
std         4.1833          0         6.452276                 0
min         1.0000      False         0.000000                 0
25%         4.2500          0         0.000000                 0
50%         7.5000          0         0.000000                 0
75%        10.7500          0         3.500000                 0
max        14.0000      False        22.000000                 0

[8 rows x 4 columns]

Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data

As you prefer you can transpose the result if you prefer:

In [47]:

df.describe().transpose()

Out[47]:

                 count      mean       std    min   25%  50%    75%    max
shopper_num         14       7.5    4.1833      1  4.25  7.5  10.75     14
is_martian          14         0         0  False     0    0      0  False
number_of_items     14  3.357143  6.452276      0     0    0    3.5     22
count_pineapples    14         0         0      0     0    0      0      0

[4 rows x 8 columns]

Return row of Data Frame based on value in a column - R

@Zelazny7's answer works, but if you want to keep ties you could do:

df[which(df$Amount == min(df$Amount)), ]

For example with the following data frame:

df <- data.frame(Name = c("A", "B", "C", "D", "E"), 
                 Amount = c(150, 120, 175, 160, 120))

df[which.min(df$Amount), ]
#   Name Amount
# 2    B    120

df[which(df$Amount == min(df$Amount)), ]
#   Name Amount
# 2    B    120
# 5    E    120

Edit: If there are NAs in the Amount column you can do:

df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ]

Laravel blank white screen

Reason can be Middleware if you forget to put following code to the end of handle function

return $next($request);

How to rotate the background image in the container?

Very well done and answered here - http://www.sitepoint.com/css3-transform-background-image/

#myelement:before
{
    content: "";
    position: absolute;
    width: 200%;
    height: 200%;
    top: -50%;
    left: -50%;
    z-index: -1;
    background: url(background.png) 0 0 repeat;
    -webkit-transform: rotate(30deg);
    -moz-transform: rotate(30deg);
    -ms-transform: rotate(30deg);
    -o-transform: rotate(30deg);
    transform: rotate(30deg);
}

How to easily import multiple sql files into a MySQL database?

  1. Goto cmd

  2. Type in command prompt C:\users\Usersname>cd [.sql tables folder path ]
    Press Enter
    Ex: C:\users\Usersname>cd E:\project\database

  3. Type command prompt
    C:\users\Usersname>[.sql folder's drive (directory)name]
    Press Enter
    Ex: C:\users\Usersname>E:

  4. Type command prompt for marge all .sql file(table) in a single file
    copy /b *.sql newdatabase.sql
    Press Enter
    EX: E:\project\database>copy /b *.sql newdatabase.sql

  5. You can see Merge Multiple .sql(file) tables Files Into A Single File in your directory folder
    Ex: E:\project\database

What is ".NET Core"?

Microsoft recognized the future web open source paradigm and decided to open .NET to other operating systems. .NET Core is a .NET Framework for Mac and Linux. It is a “lightweight” .NET Framework, so some features/libraries are missing.

On Windows, I would still run .NET Framework and Visual Studio 2015. .NET Core is more friendly with the open source world like Node.js, npm, Yeoman, Docker, etc.

You can develop full-fledged web sites and RESTful APIs on Mac or Linux with Visual Studio Code + .NET Core which wasn't possible before. So if you love Mac or Ubuntu and you are a .NET developer then go ahead and set it up.

For Mono vs. .NET Core, Mono was developed as a .NET Framework for Linux which is now acquired by Microsoft (company called Xamarin) and used in mobile development. Eventually, Microsoft may merge/migrate Mono to .NET Core. I would not worry about Mono right now.

File name without extension name VBA

The answers given here already may work in limited situations, but are certainly not the best way to go about it. Don't reinvent the wheel. The File System Object in the Microsoft Scripting Runtime library already has a method to do exactly this. It's called GetBaseName. It handles periods in the file name as is.

Public Sub Test()

    Dim fso As New Scripting.FileSystemObject
    Debug.Print fso.GetBaseName(ActiveWorkbook.Name)

End Sub

Public Sub Test2()

    Dim fso As New Scripting.FileSystemObject
    Debug.Print fso.GetBaseName("MyFile.something.txt")

End Sub

Instructions for adding a reference to the Scripting Library

Why doesn't Java support unsigned ints?

I think Java is fine as it is, adding unsigned would complicate it without much gain. Even with the simplified integer model, most Java programmers don't know how the basic numeric types behave - just read the book Java Puzzlers to see what misconceptions you might hold.

As for practical advice:

  • If your values are somewhat arbitrary size and don't fit into int, use long. If they don't fit into long use BigInteger.

  • Use the smaller types only for arrays when you need to save space.

  • If you need exactly 64/32/16/8 bits, use long/int/short/byte and stop worrying about the sign bit, except for division, comparison, right shift, and casting.

See also this answer about "porting a random number generator from C to Java".

How to extract the nth word and count word occurrences in a MySQL string?

Shorter option to extract the second word in a sentence:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('THIS IS A TEST', ' ',  2), ' ', -1) as FoundText

MySQL docs for SUBSTRING_INDEX

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

I faced the same error after upgrading MySQL server from 5.1.73 to 5.5.45 There is another way to fix that error.

In my case I was able to connect to MySQL using root password but MySQL actively refused to GRANT PRIVILEGES to any user;

  1. Connect to MySQL as root

    mysql -u root -p
    

    then enter your MySQL root password;

  2. Select database;

    use mysql;
    
  3. Most probably there is only one record for root in mysql.user table allowing to connect only from localhost (that was in my case) but by the default there should be two records for root, one for localhost and another one for 127.0.0.1;

  4. Create additional record for root user with Host='127.0.0.1' if it's not there;

        SET @s = CONCAT('INSERT INTO mysql.user SELECT ',
                REPLACE((SELECT GROUP_CONCAT(COLUMN_NAME) 
                         FROM INFORMATION_SCHEMA.COLUMNS
                         WHERE TABLE_NAME = 'user' AND TABLE_SCHEMA = 'mysql')
                ,"Host","'127.0.0.1'"),
                ' FROM mysql.user WHERE User="root"'); 
    
         PREPARE stmt FROM @s; 
         EXECUTE stmt;
    
  5. Additionally to that you can execute mysql_upgrade -u -p to see if everything is ok.

How do you create a daemon in Python?

Here's my basic 'Howdy World' Python daemon that I start with, when I'm developing a new daemon application.

#!/usr/bin/python
import time
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/foo.pid'
        self.pidfile_timeout = 5
    def run(self):
        while True:
            print("Howdy!  Gig'em!  Whoop!")
            time.sleep(10)

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

Note that you'll need the python-daemon library. You can install it by:

pip install python-daemon

Then just start it with ./howdy.py start, and stop it with ./howdy.py stop.

Binding IIS Express to an IP Address

Change bindingInformation=":8080:"

And remember to turn off the firewall for IISExpress

Show SOME invisible/whitespace characters in Eclipse

I would prefer to keep the "Show Whitespace" button on the toolbar, so that in one click you can toggle it.

Go to Window -> Perspective -> Customize Perspective and enable to show the button on toolbar.

enter image description here

Get value from a string after a special character

Assuming you have your hidden input in a jQuery object $myHidden, you then use JavaScript (not jQuery) to get the part after ?:

var myVal = $myHidden.val ();
var tmp = myVal.substr ( myVal.indexOf ( '?' ) + 1 ); // tmp now contains whatever is after ?

Simple int to char[] conversion

Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

char c[2];
int i=1;
sprintf(c, "%d", i);

MySQL - select data from database between two dates

Maybe use in between better. It worked for me to get range then filter it

How can I convert an HTML element to a canvas element?

Building on top of the Mozdev post that natevw references I've started a small project to render HTML to canvas in Firefox, Chrome & Safari. So for example you can simply do:

rasterizeHTML.drawHTML('<span class="color: green">This is HTML</span>' 
                     + '<img src="local_img.png"/>', canvas);

Source code and a more extensive example is here.

Why the switch statement cannot be applied on strings?

C++

constexpr hash function:

constexpr unsigned int hash(const char *s, int off = 0) {                        
    return !s[off] ? 5381 : (hash(s, off+1)*33) ^ s[off];                           
}                                                                                

switch( hash(str) ){
case hash("one") : // do something
case hash("two") : // do something
}

Take a char input from the Scanner

You could use typecasting:

Scanner sc= new Scanner(System.in);
char a=(char) sc.next();

This way you will take input in String due to the function 'next()' but then it will be converted into character due to the 'char' mentioned in the brackets.

This method of conversion of data type by mentioning the destination data type in brackets is called typecating. It works for me, I hope it works for u :)

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I was getting an "out of space" error, which left me scratching my head as I had plenty of disk space, until I realized that it ran out of space on /tmp, which on Arch Linux is mounted on a tmpfs with a size limit.

What are the options for storing hierarchical data in a relational database?

If your database supports arrays, you can also implement a lineage column or materialized path as an array of parent ids.

Specifically with Postgres you can then use the set operators to query the hierarchy, and get excellent performance with GIN indices. This makes finding parents, children, and depth pretty trivial in a single query. Updates are pretty manageable as well.

I have a full write up of using arrays for materialized paths if you're curious.

HTML5 Local storage vs. Session storage

The only difference is that localStorage has a different expiration time, sessionStorage will only be accessible while and by the window that created it is open.
localStorage lasts until you delete it or the user deletes it.
Lets say that you wanted to save a login username and password you would want to use sessionStorageover localStorage for security reasons (ie. another person accessing their account at a later time).
But if you wanted to save a user's settings on their machine you would probably want localStorage. All in all:

localStorage - use for long term use.
sessionStorage - use when you need to store somthing that changes or somthing temporary

lvalue required as left operand of assignment

Change = to == i.e if (strcmp("hello", "hello") == 0)

You want to compare the result of strcmp() to 0. So you need ==. Assigning it to 0 won't work because rvalues cannot be assigned to.

Make sure that the controller has a parameterless public constructor error

Sometimes because you are resolving your interface in ContainerBootstraper.cs it's very difficult to catch the error. In my case there was an error in resolving the implementation of the interface I've injected to the api controller. I couldn't find the error because I have resolve the interface in my bootstraperContainer like this: container.RegisterType<IInterfaceApi, MyInterfaceImplementaionHelper>(new ContainerControlledLifetimeManager());
then I've adde the following line in my bootstrap container : container.RegisterType<MyController>(); so when I compile the project , compiler complained and stopped in above line and showed the error.

How to copy files across computers using SSH and MAC OS X Terminal

First zip or gzip the folders:
Use the following command:

zip -r NameYouWantForZipFile.zip foldertozip/

or

tar -pvczf BackUpDirectory.tar.gz /path/to/directory

for gzip compression use SCP:

scp [email protected]:~/serverpath/public_html ~/Desktop

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

To add to the above: If interrupt is not working, you can restart the kernel.

Go to the kernel dropdown >> restart >> restart and clear output. This usually does the trick. If this still doesn't work, kill the kernel in the terminal (or task manager) and then restart.

Interrupt doesn't work well for all processes. I especially have this problem using the R kernel.

Cannot ignore .idea/workspace.xml - keeps popping up

Ignore the files ending with .iws, and the workspace.xml and tasks.xml files in your .gitignore Reference

jQuery function after .append

Well I've got exactly the same problem with size recalculation and after hours of headache I have to disagree with .append() behaving strictly synchronous. Well at least in Google Chrome. See following code.

var input = $( '<input />' );
input.append( arbitraryElement );
input.css( 'padding-left' );

The padding-left property is correctly retrieved in Firefox but it is empty in Chrome. Like all other CSS properties I suppose. After some experiments I had to settle for wrapping the CSS 'getter' into setTimeout() with 10 ms delay which I know is UGLY as hell but the only one working in Chrome. If any of you had an idea how to solve this issue better way I'd be very grateful.

MySQL JOIN ON vs USING?

It is mostly syntactic sugar, but a couple differences are noteworthy:

ON is the more general of the two. One can join tables ON a column, a set of columns and even a condition. For example:

SELECT * FROM world.City JOIN world.Country ON (City.CountryCode = Country.Code) WHERE ...

USING is useful when both tables share a column of the exact same name on which they join. In this case, one may say:

SELECT ... FROM film JOIN film_actor USING (film_id) WHERE ...

An additional nice treat is that one does not need to fully qualify the joining columns:

SELECT film.title, film_id -- film_id is not prefixed
FROM film
JOIN film_actor USING (film_id)
WHERE ...

To illustrate, to do the above with ON, we would have to write:

SELECT film.title, film.film_id -- film.film_id is required here
FROM film
JOIN film_actor ON (film.film_id = film_actor.film_id)
WHERE ...

Notice the film.film_id qualification in the SELECT clause. It would be invalid to just say film_id since that would make for an ambiguity:

ERROR 1052 (23000): Column 'film_id' in field list is ambiguous

As for select *, the joining column appears in the result set twice with ON while it appears only once with USING:

mysql> create table t(i int);insert t select 1;create table t2 select*from t;
Query OK, 0 rows affected (0.11 sec)

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

Query OK, 1 row affected (0.19 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select*from t join t2 on t.i=t2.i;
+------+------+
| i    | i    |
+------+------+
|    1 |    1 |
+------+------+
1 row in set (0.00 sec)

mysql> select*from t join t2 using(i);
+------+
| i    |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

mysql>

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

Pull "pulls" the div towards the left of the browser and and Push "pushes" the div away from left of browser.

Like: enter image description here

So basically in a 3 column layout of any web page the "Main Body" appears at the "Center" and in "Mobile" view the "Main Body" appears at the "Top" of the page. This is mostly desired by everyone with 3 column layout.

<div class="container">
    <div class="row">
        <div id="content" class="col-lg-4 col-lg-push-4 col-sm-12">
        <h2>This is Content</h2>
        <p>orem Ipsum ...</p>
        </div>

        <div id="sidebar-left" class="col-lg-4  col-sm-6 col-lg-pull-4">
        <h2>This is Left Sidebar</h2>
        <p>orem Ipsum...</p>
        </div>


        <div id="sidebar-right" class="col-lg-4 col-sm-6">
        <h2>This is Right Sidebar</h2>
        <p>orem Ipsum.... </p>
        </div>
    </div>
</div>

You can view it here: http://jsfiddle.net/DrGeneral/BxaNN/1/

Hope it helps

Implement an input with a mask

Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);

function applyDataMask(field) {
    var mask = field.dataset.mask.split('');

    // For now, this just strips everything that's not a number
    function stripMask(maskedData) {
        function isDigit(char) {
            return /\d/.test(char);
        }
        return maskedData.split('').filter(isDigit);
    }

    // Replace `_` characters with characters from `data`
    function applyMask(data) {
        return mask.map(function(char) {
            if (char != '_') return char;
            if (data.length == 0) return char;
            return data.shift();
        }).join('')
    }

    function reapplyMask(data) {
        return applyMask(stripMask(data));
    }

    function changed() {   
        var oldStart = field.selectionStart;
        var oldEnd = field.selectionEnd;

        field.value = reapplyMask(field.value);

        field.selectionStart = oldStart;
        field.selectionEnd = oldEnd;
    }

    field.addEventListener('click', changed)
    field.addEventListener('keyup', changed)
}
Date: <input type="text" value="__-__-____" data-mask="__-__-____"/><br/>
Telephone: <input type="text" value="(___) ___-____" data-mask="(___) ___-____"/><br/>

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

I had same error, I think the problem is that the error text is confusing, because its giving a false key name.

In your case It should say "There is no ViewData item of type 'IEnumerable' that has the key "Submarkets"".

My error was a misspelling in the view code (your "Submarkets"), but the error text made me go crazy.

I post this answer because I want to say people looking for this error, like I was, that the problem is that its not finding the IENumerable, but in the var that its supposed to look for it ("Submarkets" in this case), not in the one showed in error ("submarket_0").

Accepted answer is very interesting, but as you said the convention is applied if you dont specify the 2nd parameter, in this case it was specified, but the var was not found (in your case because the viewdata had not it, in my case because I misspelled the var name)

Hope this helps!

implements Closeable or implements AutoCloseable

Here is the small example

public class TryWithResource {

    public static void main(String[] args) {
        try (TestMe r = new TestMe()) {
            r.generalTest();
        } catch(Exception e) {
            System.out.println("From Exception Block");
        } finally {
            System.out.println("From Final Block");
        }
    }
}



public class TestMe implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println(" From Close -  AutoCloseable  ");
    }

    public void generalTest() {
        System.out.println(" GeneralTest ");
    }
}

Here is the output:

GeneralTest 
From Close -  AutoCloseable  
From Final Block

What's the correct way to convert bytes to a hex string in Python 3?

If you want to convert b'\x61' to 97 or '0x61', you can try this:

[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'

Reference:https://docs.python.org/3.5/library/struct.html

How to make for loops in Java increase by increments other than 1

It's just a syntax error. You just have to replace j+3 by j=j+3 or j+=3.

Char to int conversion in C

You can simply use theatol()function:

#include <stdio.h>
#include <stdlib.h>

int main() 
{
    const char *c = "5";
    int d = atol(c);
    printf("%d\n", d);

}

Scroll RecyclerView to show selected item on top

what i did to restore the scroll position after refreshing the RecyclerView on button clicked:

if (linearLayoutManager != null) {

    index = linearLayoutManager.findFirstVisibleItemPosition();
    View v = linearLayoutManager.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - linearLayoutManager.getPaddingTop());
    Log.d("TAG", "visible position " + " " + index);
}

else{
    index = 0;
}

linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.scrollToPositionWithOffset(index, top);

getting the offset of the first visible item from the top before creating the linearLayoutManager object and after instantiating it the scrollToPositionWithOffset of the LinearLayoutManager object was called.

Python Binomial Coefficient

Here is a function that recursively calculates the binomial coefficients using conditional expressions

def binomial(n,k):
    return 1 if k==0 else (0 if n==0 else binomial(n-1, k) + binomial(n-1, k-1))

How do I concatenate two text files in PowerShell?

Do not use >; it messes up the character encoding. Use:

Get-Content files.* | Set-Content newfile.file

Multiple argument IF statement - T-SQL

You are doing it right. The empty code block is what is causing your issue. It's not the condition structure :)

DECLARE @StartDate AS DATETIME

DECLARE @EndDate AS DATETIME

SET @StartDate = NULL
SET @EndDate = NULL

IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
    BEGIN
        print 'yoyoyo'
    END

IF (@StartDate IS NULL AND @EndDate IS NULL AND 1=1 AND 2=2) 
    BEGIN
        print 'Oh hey there'
    END

Using python PIL to turn a RGB image into a pure black and white image

A simple way to do it using python :

Python
import numpy as np
import imageio

image = imageio.imread(r'[image-path]', as_gray=True)

# getting the threshold value
thresholdValue = np.mean(image)

# getting the dimensions of the image
xDim, yDim = image.shape

# turn the image into a black and white image
for i in range(xDim):
    for j in range(yDim):
        if (image[i][j] > thresholdValue):
            image[i][j] = 255
        else:
            image[i][j] = 0

Splitting a Java String by the pipe symbol using split("|")

Use this code:

public static void main(String[] args) {
    String test = "A|B|C||D";

    String[] result = test.split("\\|");

    for (String s : result) {
        System.out.println(">" + s + "<");
    }
}

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

Setting ssh authorized_keys seem to be simple, but it hides some traps I'm trying to figure.

-- SERVER --

In /etc/ssh/sshd_config, set passwordAuthentication yes to let the server temporarily accept password authentication

-- CLIENT --

consider Cygwin as Linux emulation and install & run OpenSSH

1. Generate private and public keys (client side) # ssh-keygen

Here pressing just Enter, you get default two files, "id_rsa" and "id_rsa.pub", in ~/.ssh/, but if you give a name_for_the_key, the generated files are saved in your current working directory.

2. Transfer the your_key.pub file to the target machine, ssh-copy-id user_name@host_name

If you didn't create a default key, this is the first step to go wrong ... you should use:

ssh-copy-id -i path/to/key_name.pub user_name@host_name

3. Logging ssh user_name@host_name will work only for the default id_rsa file, so here is the second trap. You need to do ssh -i path/to/key_name user@host

(Use ssh -v ... option to see what is happening.)

If the server still asks for a password then you gave something. To Enter passphrase: when you've created keys (so it's normal).

If ssh is not listening on the default port 22, you must use ssh -p port_nr.

-- SERVER -----

4. Modify file /etc/ssh/sshd_config to have

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile  %h/.ssh/authorized_keys

(uncomment if case)

This tells ssh to accept file authorized_keys and look in the user home directory for the key_name sting written in the .ssh/authorized_keys file.

5 Set permissions on the target machine

chmod 755 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

Also turn off pass authentication,

passwordAuthentication no

to close the gate to all ssh root/admin/....@your_domain attempts.

6. Ensure ownership and group ownership of all non-root home directories are appropriate.

chown -R ~ usernamehere
chgrp -R ~/.ssh/ user

===============================================

7. Consider the excellent http://www.fail2ban.org

8. Extra SSH tunnel to access a MySQL (bind = 127.0.0.1) server

How to remove focus border (outline) around text/input boxes? (Chrome)

Set

input:focus{
    outline: 0 none;
}

"!important" is just in case. That's not necessary. [And now it's gone. –Ed.]

Convert string to binary then back again using PHP

easiest way I found was to convert to HEX instead of a string. If it works for you:

$hex = bin2hex($bin); // It will convert a binary data to its hex representation

$bin = pack("H*" , $hex); // It will convert a hex to binary

OR

$bin = hex2bin($hex); // Available only on PHP 5.4

React Native Error: ENOSPC: System limit for number of file watchers reached

From the official document:

"Visual Studio Code is unable to watch for file changes in this large workspace" (error ENOSPC)

When you see this notification, it indicates that the VS Code file watcher is running out of handles because the workspace is large and contains many files. The current limit can be viewed by running:

cat /proc/sys/fs/inotify/max_user_watches

The limit can be increased to its maximum by editing

/etc/sysctl.conf

and adding this line to the end of the file:

fs.inotify.max_user_watches=524288

The new value can then be loaded in by running

sudo sysctl -p

Note that Arch Linux works a little differently, See Increasing the amount of inotify watchers for details.

While 524,288 is the maximum number of files that can be watched, if you're in an environment that is particularly memory constrained, you may wish to lower the number. Each file watch takes up 540 bytes (32-bit) or ~1kB (64-bit), so assuming that all 524,288 watches are consumed, that results in an upper bound of around 256MB (32-bit) or 512MB (64-bit).

Another option

is to exclude specific workspace directories from the VS Code file watcher with the files.watcherExclude setting. The default for files.watcherExclude excludes node_modules and some folders under .git, but you can add other directories that you don't want VS Code to track.

"files.watcherExclude": {
    "**/.git/objects/**": true,
    "**/.git/subtree-cache/**": true,
    "**/node_modules/*/**": true
  }

How to create an Explorer-like folder browser control?

It's not as easy as it seems to implement a control like that. Explorer works with shell items, not filesystem items (ex: the control panel, the printers folder, and so on). If you need to implement it i suggest to have a look at the Windows shell functions at http://msdn.microsoft.com/en-us/library/bb776426(VS.85).aspx.

Python Selenium accessing HTML source

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome()
html_source_code = driver.execute_script("return document.body.innerHTML;")
html_soup: BeautifulSoup = BeautifulSoup(html_source_code, 'html.parser')

Now you can apply BeautifulSoup function to extract data...

How to center HTML5 Videos?

All you have to do is set you video tag to display:block; FTW the default is inline-block FTL.

Try this

.center {
  margin: 0 auto;
  width: (whatever you want);
  display: block;
}

Shortest way to print current year in a website

_x000D_
_x000D_
<div>&copy;<script>document.write(new Date().getFullYear());</script>, Company._x000D_
</div>
_x000D_
_x000D_
_x000D_

How to generate Javadoc HTML files in Eclipse?

This is a supplement answer related to the OP:

An easy and reliable solution to add Javadocs comments in Eclipse:

  1. Go to Help > Eclipse Marketplace....
  2. Find "JAutodoc".
  3. Install it and restart Eclipse.

To use this tool, right-click on class and click on JAutodoc.

How to ping a server only once from within a batch file?

For bash (OSX) ping google.com -c 1 (incase search brought you here)

Read file line by line in PowerShell

I was able to read a 4GB log file in about 50 seconds with the following. You may be able to make it faster by loading it as a C# assembly dynamically using PowerShell.

[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
    $line = $sr.ReadLine()
}
$sr.Close() 

Initialising mock objects - MockIto

A little example for JUnit 5 Jupiter, the "RunWith" was removed you now need to use the Extensions using the "@ExtendWith" Annotation.

@ExtendWith(MockitoExtension.class)
class FooTest {

  @InjectMocks
  ClassUnderTest test = new ClassUnderTest();

  @Spy
  SomeInject bla = new SomeInject();
}

How to request Location Permission at runtime

This code work for me. I also handled case "Never Ask Me"

In AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

In build.gradle (Module: app)

dependencies {
    ....
    implementation "com.google.android.gms:play-services-location:16.0.0"
}

This is CurrentLocationManager.kt

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.IntentSender
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.CountDownTimer
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.CommonStatusCodes
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.LocationSettingsRequest
import com.google.android.gms.location.LocationSettingsStatusCodes
import java.lang.ref.WeakReference


object CurrentLocationManager : LocationListener {

    const val REQUEST_CODE_ACCESS_LOCATION = 123

    fun checkLocationPermission(activity: Activity) {
        if (ContextCompat.checkSelfPermission(
                activity,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                activity,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                REQUEST_CODE_ACCESS_LOCATION
            )
        } else {
            Thread(Runnable {
                // Moves the current Thread into the background
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
                //
                requestLocationUpdates(activity)
            }).start()
        }
    }

    /**
     * be used in HomeActivity.
     */
    const val REQUEST_CHECK_SETTINGS = 55
    /**
     * The number of millis in the future from the call to start().
     * until the countdown is done and onFinish() is called.
     *
     *
     * It is also the interval along the way to receive onTick(long) callbacks.
     */
    private const val TWENTY_SECS: Long = 20000
    /**
     * Timer to get location from history when requestLocationUpdates don't return result.
     */
    private var mCountDownTimer: CountDownTimer? = null
    /**
     * WeakReference of current activity.
     */
    private var mWeakReferenceActivity: WeakReference<Activity>? = null
    /**
     * user's location.
     */
    var currentLocation: Location? = null

    @Synchronized
    fun requestLocationUpdates(activity: Activity) {
        if (mWeakReferenceActivity == null) {
            mWeakReferenceActivity = WeakReference(activity)
        } else {
            mWeakReferenceActivity?.clear()
            mWeakReferenceActivity = WeakReference(activity)
        }
        //create location request: https://developer.android.com/training/location/change-location-settings.html#prompt
        val mLocationRequest = LocationRequest()
        // Which your app prefers to receive location updates. Note that the location updates may be
        // faster than this rate, or slower than this rate, or there may be no updates at all
        // (if the device has no connectivity)
        mLocationRequest.interval = 20000
        //This method sets the fastest rate in milliseconds at which your app can handle location updates.
        // You need to set this rate because other apps also affect the rate at which updates are sent
        mLocationRequest.fastestInterval = 10000
        mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

        //Get Current Location Settings
        val builder = LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest)
        //Next check whether the current location settings are satisfied
        val client = LocationServices.getSettingsClient(activity)
        val task = client.checkLocationSettings(builder.build())
        //Prompt the User to Change Location Settings
        task.addOnSuccessListener(activity) {
            Log.d("CurrentLocationManager", "OnSuccessListener")
            // All location settings are satisfied. The client can initialize location requests here.
            // If it's failed, the result after user updated setting is sent to onActivityResult of HomeActivity.
            val activity1 = mWeakReferenceActivity?.get()
            if (activity1 != null) {
                startRequestLocationUpdate(activity1.applicationContext)
            }
        }

        task.addOnFailureListener(activity) { e ->
            Log.d("CurrentLocationManager", "addOnFailureListener")
            val statusCode = (e as ApiException).statusCode
            when (statusCode) {
                CommonStatusCodes.RESOLUTION_REQUIRED ->
                    // Location settings are not satisfied, but this can be fixed
                    // by showing the user a dialog.
                    try {
                        val activity1 = mWeakReferenceActivity?.get()
                        if (activity1 != null) {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            val resolvable = e as ResolvableApiException
                            resolvable.startResolutionForResult(
                                activity1, REQUEST_CHECK_SETTINGS
                            )
                        }
                    } catch (sendEx: IntentSender.SendIntentException) {
                        // Ignore the error.
                        sendEx.printStackTrace()
                    }

                LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
                    // Location settings are not satisfied. However, we have no way
                    // to fix the settings so we won't show the dialog.
                }
            }
        }
    }

    fun startRequestLocationUpdate(appContext: Context) {
        val mLocationManager = appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (ActivityCompat.checkSelfPermission(
                appContext.applicationContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            //Utilities.showProgressDialog(mWeakReferenceActivity.get());
            if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 10000, 0f, this
                )
            } else {
                mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 10000, 0f, this
                )
            }
        }

        /*Timer to call getLastKnownLocation() when requestLocationUpdates don 't return result*/
        countDownUpdateLocation()
    }

    override fun onLocationChanged(location: Location?) {
        if (location != null) {
            stopRequestLocationUpdates()
            currentLocation = location
        }
    }

    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {

    }

    override fun onProviderEnabled(provider: String) {

    }

    override fun onProviderDisabled(provider: String) {

    }

    /**
     * Init CountDownTimer to to get location from history when requestLocationUpdates don't return result.
     */
    @Synchronized
    private fun countDownUpdateLocation() {
        mCountDownTimer?.cancel()
        mCountDownTimer = object : CountDownTimer(TWENTY_SECS, TWENTY_SECS) {
            override fun onTick(millisUntilFinished: Long) {}

            override fun onFinish() {
                if (mWeakReferenceActivity != null) {
                    val activity = mWeakReferenceActivity?.get()
                    if (activity != null && ActivityCompat.checkSelfPermission(
                            activity,
                            Manifest.permission.ACCESS_FINE_LOCATION
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {
                        val location = (activity.applicationContext
                            .getSystemService(Context.LOCATION_SERVICE) as LocationManager)
                            .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)
                        stopRequestLocationUpdates()
                        onLocationChanged(location)
                    } else {
                        stopRequestLocationUpdates()
                    }
                } else {
                    mCountDownTimer?.cancel()
                    mCountDownTimer = null
                }
            }
        }.start()
    }

    /**
     * The method must be called in onDestroy() of activity to
     * removeUpdateLocation and cancel CountDownTimer.
     */
    fun stopRequestLocationUpdates() {
        val activity = mWeakReferenceActivity?.get()
        if (activity != null) {
            /*if (ActivityCompat.checkSelfPermission(activity,
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {*/
            (activity.applicationContext
                .getSystemService(Context.LOCATION_SERVICE) as LocationManager).removeUpdates(this)
            /*}*/
        }
        mCountDownTimer?.cancel()
        mCountDownTimer = null
    }
}

In MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
...
CurrentLocationManager.checkLocationPermission(this@LoginActivity)
}

override fun onDestroy() {
        CurrentLocationManager.stopRequestLocationUpdates()
        super.onDestroy()
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CurrentLocationManager.REQUEST_CODE_ACCESS_LOCATION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                //denied
                val builder = AlertDialog.Builder(this)
                builder.setMessage("We need permission to use your location for the purpose of finding friends near you.")
                    .setTitle("Device Location Required")
                    .setIcon(com.eswapp.R.drawable.ic_info)
                    .setPositiveButton("OK") { _, _ ->
                        if (ActivityCompat.shouldShowRequestPermissionRationale(
                                this,
                                Manifest.permission.ACCESS_FINE_LOCATION
                            )
                        ) {
                            //only deny
                            CurrentLocationManager.checkLocationPermission(this@LoginActivity)
                        } else {
                            //never ask again
                            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                            val uri = Uri.fromParts("package", packageName, null)
                            intent.data = uri
                            startActivityForResult(intent, CurrentLocationManager.REQUEST_CHECK_SETTINGS)
                        }
                    }
                    .setNegativeButton("Ask Me Later") { _, _ ->

                    }
                // Create the AlertDialog object and return it
                val dialog = builder.create()
                dialog.show()
            } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                CurrentLocationManager.requestLocationUpdates(this)
            }
        }
    }

    //Forward Login result to the CallBackManager in OnActivityResult()
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            //case 1. After you allow the app access device location, Another dialog will be displayed to request you to turn on device location
            //case 2. Or You chosen Never Ask Again, you open device Setting and enable location permission
            CurrentLocationManager.REQUEST_CHECK_SETTINGS -> when (resultCode) {
                RESULT_OK -> {
                    Log.d("REQUEST_CHECK_SETTINGS", "RESULT_OK")
                    //case 1. You choose OK
                    CurrentLocationManager.startRequestLocationUpdate(applicationContext)
                }
                RESULT_CANCELED -> {
                    Log.d("REQUEST_CHECK_SETTINGS", "RESULT_CANCELED")
                    //case 1. You choose NO THANKS
                    //CurrentLocationManager.requestLocationUpdates(this)

                    //case 2. In device Setting screen: user can enable or not enable location permission,
                    // so when user back to this activity, we should re-call checkLocationPermission()
                    CurrentLocationManager.checkLocationPermission(this@LoginActivity)
                }
                else -> {
                    //do nothing
                }
            }
            else -> {
                super.onActivityResult(requestCode, resultCode, data)
            }
        }
    }

Finding duplicate rows in SQL Server

Select * from (Select orgName,id,
ROW_NUMBER() OVER(Partition By OrgName ORDER by id DESC) Rownum
From organizations )tbl Where Rownum>1

So the records with rowum> 1 will be the duplicate records in your table. ‘Partition by’ first group by the records and then serialize them by giving them serial nos. So rownum> 1 will be the duplicate records which could be deleted as such.

How to revert to origin's master branch's version of file

If you didn't commit it to the master branch yet, its easy:

  • get off the master branch (like git checkout -b oops/fluke/dang)
  • commit your changes there (like git add -u; git commit;)
  • go back the master branch (like git checkout master)

Your changes will be saved in branch oops/fluke/dang; master will be as it was.

Best approach to remove time part of datetime in SQL Server

CAST(round(cast(getdate()as real),0,1) AS datetime)

This method does not use string function. Date is basically a real datatype with digits before decimal are fraction of a day.

this I guess will be faster than a lot.

The system cannot find the file specified. in Visual Studio

Another take on this that hasn't been mentioned here is that, when in debug, the project may build, but it won't run, giving the error message displayed in the question.

If this is the case, another option to look at is the output file versus the target file. These should match.

A quick way to check the output file is to go to the project's property pages, then go to Configuration Properties -> Linker -> General (In VS 2013 - exact path may vary depending on IDE version).

There is an "Output File" setting. If it is not $(OutDir)$(TargetName)$(TargetExt), then you may run into issues.

This is also discussed in more detail here.

How to remove unwanted space between rows and columns in table?

Add this CSS reset to your CSS code: (From here)

/* http://meyerweb.com/eric/tools/css/reset/ 
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

It'll reset the CSS effectively, getting rid of the padding and margins.

What is the difference between json.load() and json.loads() functions

Yes, s stands for string. The json.loads function does not take the file path, but the file contents as a string. Look at the documentation at https://docs.python.org/2/library/json.html!

Find the similarity metric between two strings

Solution #1: Python builtin

use SequenceMatcher from difflib

pros: native python library, no need extra package.
cons: too limited, there are so many other good algorithms for string similarity out there.

example :
>>> from difflib import SequenceMatcher
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75

Solution #2: jellyfish library

its a very good library with good coverage and few issues. it supports:
- Levenshtein Distance
- Damerau-Levenshtein Distance
- Jaro Distance
- Jaro-Winkler Distance
- Match Rating Approach Comparison
- Hamming Distance

pros: easy to use, gamut of supported algorithms, tested.
cons: not native library.

example:

>>> import jellyfish
>>> jellyfish.levenshtein_distance(u'jellyfish', u'smellyfish')
2
>>> jellyfish.jaro_distance(u'jellyfish', u'smellyfish')
0.89629629629629637
>>> jellyfish.damerau_levenshtein_distance(u'jellyfish', u'jellyfihs')
1

How to make a new List in Java

One example:

List somelist = new ArrayList();

You can look at the javadoc for List and find all known implementing classes of the List interface that are included with the java api.

Java Synchronized list

It will give consistent behavior for add/remove operations. But while iterating you have to explicitly synchronized. Refer this link

GDB: break if variable equal value

in addition to a watchpoint nested inside a breakpoint you can also set a single breakpoint on the 'filename:line_number' and use a condition. I find it sometimes easier.

(gdb) break iter.c:6 if i == 5
Breakpoint 2 at 0x4004dc: file iter.c, line 6.
(gdb) c
Continuing.
0
1
2
3
4

Breakpoint 2, main () at iter.c:6
6           printf("%d\n", i);

If like me you get tired of line numbers changing, you can add a label then set the breakpoint on the label like so:

#include <stdio.h>
main()
{ 
     int i = 0;
     for(i=0;i<7;++i) {
       looping:
        printf("%d\n", i);
     }
     return 0;
}

(gdb) break main:looping if i == 5

How to create Python egg file

You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode

  1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup from setuptools, not distutils.

  2. Yep. That should be right.

  3. I don't think so. pyc files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py files leaving .pyc files, but it wouldn't be recommended.

  4. I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?

C++ Object Instantiation

The only reason I'd worry about is that Dog is now allocated on the stack, rather than the heap. So if Dog is megabytes in size, you may have a problem,

If you do need to go the new/delete route, be wary of exceptions. And because of this you should use auto_ptr or one of the boost smart pointer types to manage the object lifetime.

CodeIgniter - File upload required validation

I found a solution that works exactly how I want.

I changed

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');

To

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
    $this->form_validation->set_rules('userfile', 'Document', 'required');
}

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

This should do the trick!

// convert object => json
$json = json_encode($myObject);

// convert json => object
$obj = json_decode($json);

Here's an example

$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";

$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}

print_r(json_decode($json));
// stdClass Object
// (
//   [hello] => world
//   [bar] => baz
// )

If you want the output as an Array instead of an Object, pass true to json_decode

print_r(json_decode($json, true));
// Array
// (
//   [hello] => world
//   [bar] => baz
// )    

More about json_encode()

See also: json_decode()

Passing data to a bootstrap modal

Your code would have worked with correct modal html structure.

_x000D_
_x000D_
$(function(){_x000D_
  $(".open-AddBookDialog").click(function(){_x000D_
     $('#bookId').val($(this).data('id'));_x000D_
    $("#addBookDialog").modal("show");_x000D_
  });_x000D_
});
_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<a data-id="@book.Id" title="Add this item" class="open-AddBookDialog">Open Modal</a>_x000D_
_x000D_
<div id="addBookDialog" class="modal fade" tabindex="-1" role="dialog">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-body">_x000D_
       <input type="hidden" name="bookId" id="bookId" value=""/>_x000D_
      </div>_x000D_
    _x000D_
    </div><!-- /.modal-content -->_x000D_
  </div><!-- /.modal-dialog -->_x000D_
</div><!-- /.modal -->_x000D_
</html>
_x000D_
_x000D_
_x000D_

RandomForestClassfier.fit(): ValueError: could not convert string to float

I had a similar issue and found that pandas.get_dummies() solved the problem. Specifically, it splits out columns of categorical data into sets of boolean columns, one new column for each unique value in each input column. In your case, you would replace train_x = test[cols] with:

train_x = pandas.get_dummies(test[cols])

This transforms the train_x Dataframe into the following form, which RandomForestClassifier can accept:

   C  A_Hello  A_Hola  B_Bueno  B_Hi
0  0        1       0        0     1
1  1        0       1        1     0

How to make two plots side-by-side using Python?

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

How do I make a splash screen?

Though there are good answers, I will show the google recommended way:

1)First create a Theme for splash screen: you have a theme called splashscreenTheme, your launcher theme would be:

<style name="splashscreenTheme">
  <item name="android:windowBackground">@drawable/launch_screen</item>
</style>

Note:

android:windowBackground already sets your splashscreen image no
need to do this in UI again.

you can also use color here instead of a drawable.

2)Set the theme to manifest of splashscreenActivity

   <activity
            android:name=".activity.splashscreenActivity"
            android:screenOrientation="portrait"
            android:theme="@style/splashscreenTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

3)make sure you launch_screen drawable is not in drawable folder if your image is not small.

It will result in faster launch screen start and save you from the black screen

It also avoids extra overdraw

How to check if a value exists in a dictionary (python)

In Python 3 you can use the values() function of the dictionary. It returns a view object of the values. This, in turn, can be passed to the iter function which returns an iterator object. The iterator can be checked using in, like this,

'one' in iter(d.values())

Or you can use the view object directly since it is similar to a list

'one' in d.values()

How to replace ${} placeholders in a text file?

I was thinking about this again, given the recent interest, and I think that the tool that I was originally thinking of was m4, the macro processor for autotools. So instead of the variable I originally specified, you'd use:

$echo 'I am a DBNAME' | m4 -DDBNAME="database name"

How to recursively find and list the latest modified files in a directory with subdirectories and times

This could be done with a recursive function in Bash too.

Let F be a function that displays the time of file which must be lexicographically sortable yyyy-mm-dd, etc., (OS-dependent?)

F(){ stat --format %y "$1";}                # Linux
F(){ ls -E "$1"|awk '{print$6" "$7}';}      # SunOS: maybe this could be done easier

R, the recursive function that runs through directories:

R(){ local f;for f in "$1"/*;do [ -d "$f" ]&&R $f||F "$f";done;}

And finally

for f in *;do [ -d "$f" ]&&echo `R "$f"|sort|tail -1`" $f";done

Random row selection in Pandas dataframe

With pandas version 0.16.1 and up, there is now a DataFrame.sample method built-in:

import pandas

df = pandas.DataFrame(pandas.np.random.random(100))

# Randomly sample 70% of your dataframe
df_percent = df.sample(frac=0.7)

# Randomly sample 7 elements from your dataframe
df_elements = df.sample(n=7)

For either approach above, you can get the rest of the rows by doing:

df_rest = df.loc[~df.index.isin(df_percent.index)]

How do you close/hide the Android soft keyboard using Java?

In AndroidManifest.xml under <activity..> set android:windowSoftInputMode="stateAlwaysHidden"

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

The tutorial has you putting all components and the interface file in the same directory hence the relative import './hero' if you want to move it elsewhere you need to change this.

Edit: The code may still work but the compiler will complain because you are attempting an import from an incorrect location. I'd simply change the import based on your structure. For example:

app/
  component1/
    component1.ts
  compnent2/
    component2.ts
  hero.ts

I would simply change the import to import {Hero} from '../hero'.

Javascript to export html table to Excel

ShieldUI's export to excel functionality should already support all special chars.

how to add script src inside a View when using Layout

If you are using Razor view engine then edit the _Layout.cshtml file. Move the @Scripts.Render("~/bundles/jquery") present in footer to the header section and write the javascript / jquery code as you want:

@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
    $(document).ready(function () {
        var divLength = $('div').length;
        alert(divLength);
    });
</script>

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

C++11 reverse range-based for-loop

This should work in C++11 without boost:

namespace std {
template<class T>
T begin(std::pair<T, T> p)
{
    return p.first;
}
template<class T>
T end(std::pair<T, T> p)
{
    return p.second;
}
}

template<class Iterator>
std::reverse_iterator<Iterator> make_reverse_iterator(Iterator it)
{
    return std::reverse_iterator<Iterator>(it);
}

template<class Range>
std::pair<std::reverse_iterator<decltype(begin(std::declval<Range>()))>, std::reverse_iterator<decltype(begin(std::declval<Range>()))>> make_reverse_range(Range&& r)
{
    return std::make_pair(make_reverse_iterator(begin(r)), make_reverse_iterator(end(r)));
}

for(auto x: make_reverse_range(r))
{
    ...
}

What does --net=host option in Docker command really do?

The --net=host option is used to make the programs inside the Docker container look like they are running on the host itself, from the perspective of the network. It allows the container greater network access than it can normally get.

Normally you have to forward ports from the host machine into a container, but when the containers share the host's network, any network activity happens directly on the host machine - just as it would if the program was running locally on the host instead of inside a container.

While this does mean you no longer have to expose ports and map them to container ports, it means you have to edit your Dockerfiles to adjust the ports each container listens on, to avoid conflicts as you can't have two containers operating on the same host port. However, the real reason for this option is for running apps that need network access that is difficult to forward through to a container at the port level.

For example, if you want to run a DHCP server then you need to be able to listen to broadcast traffic on the network, and extract the MAC address from the packet. This information is lost during the port forwarding process, so the only way to run a DHCP server inside Docker is to run the container as --net=host.

Generally speaking, --net=host is only needed when you are running programs with very specific, unusual network needs.

Lastly, from a security perspective, Docker containers can listen on many ports, even though they only advertise (expose) a single port. Normally this is fine as you only forward the single expected port, however if you use --net=host then you'll get all the container's ports listening on the host, even those that aren't listed in the Dockerfile. This means you will need to check the container closely (especially if it's not yours, e.g. an official one provided by a software project) to make sure you don't inadvertently expose extra services on the machine.

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

I'm just using make with a simple makefile that looks like this:

JAVAC = javac -Xlint:unchecked
sources = $(shell find . -type f -name '*.java')
classes = $(sources:.java=.class)

all : $(classes)

clean :
        rm -f $(classes)

%.class : %.java
        $(JAVAC) $<

It compiles the sources one at a time and only recompiles if necessary.

How can I call PHP functions by JavaScript?

index.php

<body>
...
<input id="Div7" name="Txt_Nombre" maxlenght="100px" placeholder="Nombre" />
<input id="Div8" name="Txt_Correo" maxlenght="100px" placeholder="Correo" />
<textarea id="Div9" name="Txt_Pregunta" placeholder="Pregunta" /></textarea>

<script type="text/javascript" language="javascript">

$(document).ready(function() {
    $(".Txt_Enviar").click(function() { EnviarCorreo(); });
});

function EnviarCorreo()
{
    jQuery.ajax({
        type: "POST",
        url: 'servicios.php',
        data: {functionname: 'enviaCorreo', arguments: [$(".Txt_Nombre").val(), $(".Txt_Correo").val(), $(".Txt_Pregunta").val()]}, 
         success:function(data) {
        alert(data); 
         }
    });
}
</script>

servicios.php

<?php   
    include ("correo.php");

    $nombre = $_POST["Txt_Nombre"];
    $correo = $_POST["Txt_Corro"];
    $pregunta = $_POST["Txt_Pregunta"];

    switch($_POST["functionname"]){ 

        case 'enviaCorreo': 
            EnviaCorreoDesdeWeb($nombre, $correo, $pregunta);
            break;      
    }   
?>

correo.php

<?php
    function EnviaCorreoDesdeWeb($nombre, $correo, $pregunta)
    { 
       ...
    }
?>

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

You need to provide a key.

Try doing this in your ListView Rows if you have a key property:

<TouchableHighlight key={item.key} underlayColor='#dddddd'>

If not, try just adding the item as the key:

<TouchableHighlight key={item} underlayColor='#dddddd'>

How do I combine two dataframes?

I believe you can use the append method

bigdata = data1.append(data2, ignore_index=True)

to keep their indexes just dont use the ignore_index keyword ...

what do <form action="#"> and <form method="post" action="#"> do?

Apparently, action was required prior to HTML5 (and # was just a stand in), but you no longer have to use it.

See The Action Attribute:

When specified with no attributes, as below, the data is sent to the same page that the form is present on:

<form>

How to trigger checkbox click event even if it's checked through Javascript code?

You can use the jQuery .trigger() method. See http://api.jquery.com/trigger/

E.g.:

$('#foo').trigger('click');

How to open/run .jar file (double-click not working)?

Use cmd prompt and type

java -jar exapmple.jar

To run your jar file.

for more information refer to this link it describes how to properly open the jar file. https://superuser.com/questions/745112/how-do-i-run-a-jar-file-without-installing-java

How to force the input date format to dd/mm/yyyy?

DEMO : http://jsfiddle.net/shfj70qp/

//dd/mm/yyyy 

var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();

console.log(month+"/"+day+"/"+year);

How to select a column name with a space in MySQL

Generally the first step is to not do that in the first place, but if this is already done, then you need to resort to properly quoting your column names:

SELECT `Business Name` FROM annoying_table

Usually these sorts of things are created by people who have used something like Microsoft Access and always use a GUI to do their thing.

Is there a way to SELECT and UPDATE rows at the same time?

if it's inside the transaction, the database locking system will take care of concurrency issues. of course, if you use one (the mssql default is that it uses lock, so it states if you don't override that)

Initializing data.frames()

I always just convert a matrix:

x <- as.data.frame(matrix(nrow = 100, ncol = 10))

How to insert data using wpdb

Problem in your SQL :

You can construct your sql like this :

$wpdb->prepare(
 "INSERT INTO `wp_submitted_form` 
   (`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`) 
   values ('$name', '$email', '$phone', '$country', 
         '$course', '$message', '$datesent')"
 );

You can also use $wpdb->insert()

$wpdb->insert('table_name', input_array())

What's the yield keyword in JavaScript?

It's used for iterator-generators. Basically, it allows you to make a (potentially infinite) sequence using procedural code. See Mozilla's documentation.

Putting images with options in a dropdown list

This code will work only in Firefox:

<select>
    <option value="volvo" style="background-image:url(images/volvo.png);">Volvo</option>
    <option value="saab"  style="background-image:url(images/saab.png);">Saab</option>
    <option value="honda" style="background-image:url(images/honda.png);">Honda</option>
    <option value="audi"  style="background-image:url(images/audi.png);">Audi</option>
</select>

Edit (April 2018):

Firefox does not support this anymore.

What is the difference between 'protected' and 'protected internal'?

There is still a lot of confusion in understanding the scope of "protected internal" accessors, though most have the definition defined correctly. This helped me to understand the confusion between "protected" and "protected internal":

public is really public inside and outside the assembly (public internal / public external)

protected is really protected inside and outside the assembly (protected internal / protected external) (not allowed on top level classes)

private is really private inside and outside the assembly (private internal / private external) (not allowed on top level classes)

internal is really public inside the assembly but excluded outside the assembly like private (public internal / excluded external)

protected internal is really public inside the assembly but protected outside the assembly (public internal / protected external) (not allowed on top level classes)

As you can see protected internal is a very strange beast. Not intuitive.

That now begs the question why didn't Microsoft create a (protected internal / excluded external), or I guess some kind of "private protected" or "internal protected"? lol. Seems incomplete?

Added to the confusion is the fact you can nest public or protected internal nested members inside protected, internal, or private types. Why would you access a nested "protected internal" inside an internal class that excludes outside assembly access?

Microsoft says such nested types are limited by their parent type scope, but that's not what the compiler says. You can compiled protected internals inside internal classes which should limit scope to just the assembly.

To me this feels like incomplete design. They should have simplified scope of all types to a system that clearly consider inheritance but also security and hierarchy of nested types. This would have made the sharing of objects extremely intuitive and granular rather than discovering accessibility of types and members based on an incomplete scoping system.

Add a scrollbar to a <textarea>

textarea {
    overflow-y: scroll; /* Vertical scrollbar */
    overflow: scroll; /* Horizontal and vertical scrollbar*/
}

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

Cannot delete directory with Directory.Delete(path, true)

The directory or a file in it is locked and cannot be deleted. Find the culprit who locks it and see if you can eliminate it.

Adding a right click menu to an item

If you are using Visual Studio, there is a GUI solution as well:

  1. From Toolbox add a ContextMenuStrip
  2. Select the context menu and add the right click items
  3. For each item set the click events to the corresponding functions
  4. Select the form / button / image / etc (any item) that the right click menu will be connected
  5. Set its ContextMenuStrip property to the menu you have created.

How to write to a JSON file in the correct format

Require the JSON library, and use to_json.

require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(tempHash.to_json)
end

Your temp.json file now looks like:

{"key_a":"val_a","key_b":"val_b"}

Is there an easy way to return a string repeated X number of times?

Works with strings and chars:

Strings and chars [version 1]

string.Join("", Enumerable.Repeat("text" , 2 ));    
//result: texttext

Strings [version 2]:

String.Concat(Enumerable.Repeat("text", 2));
//result: texttext

Strings and chars [version 3]

new StringBuilder().Insert(0, "text", 2).ToString(); 
//result: texttext

Chars only:

'5' * 3; 
//result: 555

Extension way:

(works FASTER - better for WEB)

public static class RepeatExtensions
{
    public static string Repeat(this string str, int times)
    {
        return (new StringBuilder()).Insert(0, str, times).ToString();
    }
}

usage:

 var a = "Hello".Repeat(3); 
 //result: HelloHelloHello

How to get htaccess to work on MAMP

Go to httpd.conf on /Applications/MAMP/conf/apache and see if the LoadModule rewrite_module modules/mod_rewrite.so line is un-commented (without the # at the beginning)

and change these from ...

<VirtualHost *:80>
    ServerName ...
    DocumentRoot /....
</VirtualHost>

To this:

<VirtualHost *:80>
    ServerAdmin ...
    ServerName ...

    DocumentRoot ...
    <Directory ...>
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory ...>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
</VirtualHost>

Reload the page after ajax success

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});

Get screenshot on Windows with Python?

You can use the ImageGrab module. ImageGrab works on Windows and macOS, and you need PIL (Pillow) to use it. Here is a little example:

from PIL import ImageGrab
snapshot = ImageGrab.grab()
save_path = "C:\\Users\\YourUser\\Desktop\\MySnapshot.jpg"
snapshot.save(save_path)

Setting selected option in laravel form

Try this

<select class="form-control" name="country_code" value="{{ old('country_code') }}">
   @foreach (\App\SystemCountry::orderBy('country')->get() as $country)
       <option value="{{ $country->country_code }}"
           @if ($country->country_code == "LKA")
             {{'selected="selected"'}}
           @endif
       >
          {{ $country->country }}
       </option>
   @endforeach
</select>

simulate background-size:cover on <video> or <img>

This is something I pulled my hair out over for a while, but I came across a great solution that doesn't use any script, and can achieve a perfect cover simulation on video with 5 lines of CSS (9 if you count selectors and brackets). This has 0 edge-cases in which it doesn't work perfectly, short of CSS3-compatibility.

You can see an example here (archived)

The problem with Timothy's solution, is that it doesn't handle scaling correctly. If the surrounding element is smaller than the video file, it isn't scaled down. Even if you give the video tag a tiny initial size, like 16px by 9px, auto ends up forcing it to a minimum of its native file-size. With the current top-voted solution on this page, it was impossible for me to have the video file scale down resulting in a drastic zoom effect.

If the aspect ratio of your video is known, however, such as 16:9, you can do the following:

.parent-element-to-video {
    overflow: hidden;
}
video {
    height: 100%;
    width: 177.77777778vh; /* 100 * 16 / 9 */
    min-width: 100%;
    min-height: 56.25vw; /* 100 * 9 / 16 */
}

If the video's parent element is set to cover the entire page (such as position: fixed; width: 100%; height: 100vh;), then the video will, too.

If you want the video centered as well, you can use the surefire centering approach:

/* merge with above css */
.parent-element-to-video {
    position: relative; /* or absolute or fixed */
}
video {
    position: absolute;
    left: 50%; /* % of surrounding element */
    top: 50%;
    transform: translate(-50%, -50%); /* % of current element */
}

Of course, vw, vh, and transform are CSS3, so if you need compatibility with much older browsers, you'll need to use script.

How can I troubleshoot Python "Could not find platform independent libraries <prefix>"

Try export PYTHONHOME=/usr/local. Python should be installed in /usr/local on OS X.

This answer has received a little more attention than I anticipated, I'll add a little bit more context.

Normally, Python looks for its libraries in the paths prefix/lib and exec_prefix/lib, where prefix and exec_prefix are configuration options. If the PYTHONHOME environment variable is set, then the value of prefix and exec_prefix are inherited from it. If the PYTHONHOME environment variable is not set, then prefix and exec_prefix default to /usr/local (and I believe there are other ways to set prefix/exec_prefix as well, but I'm not totally familiar with them).

Normally, when you receive the error message Could not find platform independent libraries <prefix>, the string <prefix> would be replaced with the actual value of prefix. However, if prefix has an empty value, then you get the rather cryptic messages posted in the question. One way to get an empty prefix would be to set PYTHONHOME to an empty string. More info about PYTHONHOME, prefix, and exec_prefix is available in the official docs.

iOS 7: UITableView shows under status bar

The following solution works well enough in code without using magic constants, and accounts for the user changing the size class, e.g. through rotations or side-by-side apps on ipads:

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    // Fix up content offset to ensure the tableview isn't underlapping the status bar.
    self.tableView.contentInset = UIEdgeInsetsMake(self.topLayoutGuide.length, 0.0, 0.0, 0.0);
}

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

The answers so far are great! But I see a need for a solution with the following constraints:

  1. Plain, concise LINQ;
  2. O(n) complexity;
  3. Do not evaluate the property more than once per element.

Here it is:

public static T MaxBy<T, R>(this IEnumerable<T> en, Func<T, R> evaluate) where R : IComparable<R> {
    return en.Select(t => new Tuple<T, R>(t, evaluate(t)))
        .Aggregate((max, next) => next.Item2.CompareTo(max.Item2) > 0 ? next : max).Item1;
}

public static T MinBy<T, R>(this IEnumerable<T> en, Func<T, R> evaluate) where R : IComparable<R> {
    return en.Select(t => new Tuple<T, R>(t, evaluate(t)))
        .Aggregate((max, next) => next.Item2.CompareTo(max.Item2) < 0 ? next : max).Item1;
}

Usage:

IEnumerable<Tuple<string, int>> list = new[] {
    new Tuple<string, int>("other", 2),
    new Tuple<string, int>("max", 4),
    new Tuple<string, int>("min", 1),
    new Tuple<string, int>("other", 3),
};
Tuple<string, int> min = list.MinBy(x => x.Item2); // "min", 1
Tuple<string, int> max = list.MaxBy(x => x.Item2); // "max", 4

How I can get web page's content and save it into the string variable

Webclient client = new Webclient();
string content = client.DownloadString(url);

Pass the URL of page who you want to get. You can parse the result using htmlagilitypack.

Sublime text 3. How to edit multiple lines?

Thank you for all answers! I found it! It calls "Column selection (for Sublime)" and "Column Mode Editing (for Notepad++)" https://www.sublimetext.com/docs/3/column_selection.html

Favicon: .ico or .png / correct tags?

I know this is an old question.

Here's another option - attending to different platform requirements - Source

<link rel='shortcut icon' type='image/vnd.microsoft.icon' href='/favicon.ico'> <!-- IE -->
<link rel='apple-touch-icon' type='image/png' href='/icon.57.png'> <!-- iPhone -->
<link rel='apple-touch-icon' type='image/png' sizes='72x72' href='/icon.72.png'> <!-- iPad -->
<link rel='apple-touch-icon' type='image/png' sizes='114x114' href='/icon.114.png'> <!-- iPhone4 -->
<link rel='icon' type='image/png' href='/icon.114.png'> <!-- Opera Speed Dial, at least 144×114 px -->

This is the broadest approach I have found so far.

Ultimately the decision depends on your own needs. Ask yourself, who is your target audience?

UPDATE May 27, 2018: As expected, time goes by and things change. But there's good news too. I found a tool called Real Favicon Generator that generates all the required lines for the icon to work on all modern browsers and platforms. It doesn't handle backwards compatibility though.

How to get the sizes of the tables of a MySQL database?

I find the existing answers don't actually give the size of tables on the disk, which is more helpful. This query gives more accurate disk estimate compared to table size based on data_length & index. I had to use this for an AWS RDS instance where you cannot physically examine the disk and check file sizes.

select NAME as TABLENAME,FILE_SIZE/(1024*1024*1024) as ACTUAL_FILE_SIZE_GB
, round(((data_length + index_length) / 1024 / 1024/1024), 2) as REPORTED_TABLE_SIZE_GB 
from INFORMATION_SCHEMA.INNODB_SYS_TABLESPACES s
join INFORMATION_SCHEMA.TABLES t 
on NAME = Concat(table_schema,'/',table_name)
order by FILE_SIZE desc

How to make external HTTP requests with Node.js

node-http-proxy is a great solution as was suggested by @hross above. If you're not deadset on using node, we use NGINX to do the same thing. It works really well with node. We use it for example to process SSL requests before forwarding them to node. It can also handle cacheing and forwarding routes. Yay!

CSS table column autowidth

You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.

You could set

table tr ul.actions {margin: 0; white-space:nowrap;}

(or set this for the last TD as Sander suggested instead).

This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.

This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space-property is applied, stretching its content beyond the calculated boundaries.

So I guess it's not possible without having an element within the last TD with a specific width.

Reading *.wav files in Python

If you want to procces an audio block by block, some of the given solutions are quite awful in the sense that they imply loading the whole audio into memory producing many cache misses and slowing down your program. python-wavefile provides some pythonic constructs to do NumPy block-by-block processing using efficient and transparent block management by means of generators. Other pythonic niceties are context manager for files, metadata as properties... and if you want the whole file interface, because you are developing a quick prototype and you don't care about efficency, the whole file interface is still there.

A simple example of processing would be:

import sys
from wavefile import WaveReader, WaveWriter

with WaveReader(sys.argv[1]) as r :
    with WaveWriter(
            'output.wav',
            channels=r.channels,
            samplerate=r.samplerate,
            ) as w :

        # Just to set the metadata
        w.metadata.title = r.metadata.title + " II"
        w.metadata.artist = r.metadata.artist

        # This is the prodessing loop
        for data in r.read_iter(size=512) :
            data[1] *= .8     # lower volume on the second channel
            w.write(data)

The example reuses the same block to read the whole file, even in the case of the last block that usually is less than the required size. In this case you get an slice of the block. So trust the returned block length instead of using a hardcoded 512 size for any further processing.

How to add a color overlay to a background image?

You can use a pseudo element to create the overlay.

.testclass {
  background-image: url("../img/img.jpg");
  position: relative;
}
.testclass:before {
  content: "";
  position: absolute;
  left: 0; right: 0;
  top: 0; bottom: 0;
  background: rgba(0,0,0,.5);
}

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

phpinfo() - is there an easy way for seeing it?

From your command line you can run..

php -i

I know it's not the browser window, but you can't see the phpinfo(); contents without making the function call. Obviously, the best approach would be to have a phpinfo script in the root of your web server directory, that way you have access to it at all times via http://localhost/info.php or something similar (NOTE: don't do this in a production environment or somewhere that is publicly accessible)

EDIT: As mentioned by binaryLV, its quite common to have two versions of a php.ini per installation. One for the command line interface (CLI) and the other for the web server interface. If you want to see phpinfo output for your web server make sure you specify the ini file path, for example...

php -c /etc/php/apache2/php.ini -i 

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

Find objects between two dates MongoDB

db.collection.find({$and:
  [
    {date_time:{$gt:ISODate("2020-06-01T00:00:00.000Z")}},
     {date_time:{$lt:ISODate("2020-06-30T00:00:00.000Z")}}
   ]
 })

##In case you are making the query directly from your application ##

db.collection.find({$and:
   [
     {date_time:{$gt:"2020-06-01T00:00:00.000Z"}},
     {date_time:{$lt:"2020-06-30T00:00:00.000Z"}}
  ]

 })

What is WebKit and how is it related to CSS?

-webkit- is simply a group that Chrome, Safari, Opera and iOS browsers fit into. They all have a common ancestor, so often their capabilities/limitations (when it comes to running CSS and Javascript) are confined to the group.

A developer will place -webkit- followed by some code, meaning that the code will only run on Chrome, Safari, Opera and iOS browsers. Here is a complete list:

-webkit- (Chrome, Safari, newer versions of Opera, almost all iOS browsers (including Firefox for iOS); basically, any WebKit based browser)

-moz- (Firefox)

-o- (Old, pre-WebKit, versions of Opera)

-ms- (Internet Explorer and Microsoft Edge)

How to run Conda?

If you have just installed MiniConda or Anaconda make sure you re-run your terminal.

From this, I mean close and open your terminal and then try conda list to verify your installation

For me, this worked!!

blur vs focusout -- any real differences?

As stated in the JQuery documentation

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

How to dynamically change the color of the selected menu item of a web page?

It would probably be easiest to implement this using JavaScript ... Here's a JQuery script to demo ... As the others mentioned ... we have a class named 'active' to indicate the active tab - NOT the pseudo-class ':active.' We could have just as easily named it anything though ... selected, current, etc., etc.

/* CSS */

#nav { width:480px;margin:1em auto;}

#nav ul {margin:1em auto; padding:0; font:1em "Arial Black",sans-serif; }

#nav ul li{display:inline;} 

#nav ul li a{text-decoration:none; margin:0; padding:.25em 25px; background:#666; color:#ffffff;} 

#nav ul li a:hover{background:#ff9900; color:#ffffff;} 

#nav ul li a.active {background:#ff9900; color:#ffffff;} 

/* JQuery Example */

<script type="text/javascript">
$(function (){

    $('#nav ul li a').each(function(){
        var path = window.location.href;
        var current = path.substring(path.lastIndexOf('/')+1);
        var url = $(this).attr('href');

        if(url == current){
            $(this).addClass('active');
        };
    });         
});

</script>

 /* HTML */

<div id="nav" >
    <ul>
        <li><a href='index.php?1'>One</a></li>
        <li><a href='index.php?2'>Two</a></li>
        <li><a href='index.php?3'>Three</a></li>
        <li><a href='index.php?4'>Four</a></li>
    </ul>
</div>

How can I add an item to a IEnumerable<T> collection?

you can do this.

//Create IEnumerable    
IEnumerable<T> items = new T[]{new T("msg")};

//Convert to list.
List<T> list = items.ToList();

//Add new item to list.
list.add(new T("msg2"));

//Cast list to IEnumerable
items = (IEnumerable<T>)items;

How do I extract a substring from a string until the second space is encountered?

string testString = "o1 1232.5467 1232.5467.........";

string secondItem = testString.Split(new char[]{' '}, 3)[1];

Open file dialog and select a file using WPF controls and C#

Something like that should be what you need

private void button1_Click(object sender, RoutedEventArgs e)
{
    // Create OpenFileDialog 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();



    // Set filter for file extension and default file extension 
    dlg.DefaultExt = ".png";
    dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"; 


    // Display OpenFileDialog by calling ShowDialog method 
    Nullable<bool> result = dlg.ShowDialog();


    // Get the selected file name and display in a TextBox 
    if (result == true)
    {
        // Open document 
        string filename = dlg.FileName;
        textBox1.Text = filename;
    }
}

Check if application is installed - Android

You can use this in Kotlin extentions.kt

fun Context.isPackageInstalled(packageName: String): Boolean {
    return try {
        packageManager.getPackageInfo(packageName, 0)
        true
    } catch (e: PackageManager.NameNotFoundException) {
        false
    }
}

Usage

context.isPackageInstalled("com.somepackage.name")

How to sort dates from Oldest to Newest in Excel?

You need to convert all the values in the column to date in order to sort by date.

jQuery detect if string contains something

use Contains of jquery Contains like this

if ($('.type:contains("> <")').length > 0)
{
 //do stuffs to change 
}

get data from mysql database to use in javascript

Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php,

$result = mysql_query("SELECT field_name, field_value
                       FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
  $to_encode[] = $row;
}
echo json_encode($to_encode);

If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />. You can reference that field with this jQuery: $("#field1").val().

Here's a complete example with the HTML. If we're assuming your fields are called field1 and field2, then

<!DOCTYPE html>
<html>
  <head>
    <title>That's about it</title>
  </head>
  <body>
    <form>
      <input type="text" id="field1" />
      <input type="text" id="field2" />
    </form>
  </body>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
  <script>
    $.getJSON('data.php', function(data) {
      $.each(data, function(fieldName, fieldValue) {
        $("#" + fieldName).val(fieldValue);
      });
    });
  </script>
</html>

That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value attribute.

how to check if a datareader is null or empty

I also use OleDbDataReader.IsDBNull()

if ( myReader.IsDBNull(colNum) ) { retrievedValue = ""; }
else { retrievedValue = myReader.GetString(colNum); }

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

The problem is that salesAmount is being set to a string. If you enter the variable in the python interpreter and hit enter, you'll see the value entered surrounded by quotes. For example, if you entered 56.95 you'd see:

>>> sales_amount = raw_input("[Insert sale amount]: ")
[Insert sale amount]: 56.95
>>> sales_amount
'56.95'

You'll want to convert the string into a float before multiplying it by sales tax. I'll leave that for you to figure out. Good luck!

Removing leading zeroes from a field in a SQL statement

You can try this - it takes special care to only remove leading zeroes if needed:

DECLARE @LeadingZeros    VARCHAR(10) ='-000987000'

SET @LeadingZeros =
      CASE WHEN PATINDEX('%-0', @LeadingZeros) = 1   THEN 
           @LeadingZeros
      ELSE 
           CAST(CAST(@LeadingZeros AS INT) AS VARCHAR(10)) 
      END   

SELECT @LeadingZeros

Or you can simply call

CAST(CAST(@LeadingZeros AS INT) AS VARCHAR(10)) 

How to know installed Oracle Client is 32 bit or 64 bit?

A simple way to find this out in Windows is to run SQLPlus from your Oracle homes's bin directory and then check Task Manager. If it is a 32-bit version of SQLPlus, you'll see a process on the Processes tab that looks like this:

sqlplus.exe *32

If it is 64-bit, the process will look like this:

sqlplus.exe

AssertNull should be used or AssertNotNull

The assertNotNull() method means "a passed parameter must not be null": if it is null then the test case fails.
The assertNull() method means "a passed parameter must be null": if it is not null then the test case fails.

String str1 = null;
String str2 = "hello";              

// Success.
assertNotNull(str2);

// Fail.
assertNotNull(str1);

// Success.
assertNull(str1);

// Fail.
assertNull(str2);