Programs & Examples On #Loaded

0

AngularJs event to call after content is loaded

var myTestApp = angular.module("myTestApp", []); 
myTestApp.controller("myTestController", function($scope, $window) {
$window.onload = function() {
 alert("is called on page load.");
};
});

The system cannot find the file specified. in Visual Studio

The system cannot find the file specified usually means the build failed (which it will for your code as you're missing a # infront of include, you have a stray >> at the end of your cout line and you need std:: infront of cout) but you have the 'run anyway' option checked which means it runs an executable that doesn't exist. Hit F7 to just do a build and make sure it says '0 errors' before you try running it.

Code which builds and runs:

#include <iostream>

int main()
{
   std::cout << "Hello World";
   system("pause");
   return 0;
}

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Instead of:

input:not(disabled)not:[type="submit"]:focus {}

Use:

input:not([disabled]):not([type="submit"]):focus {}

disabled is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not() selector.

Demo: http://jsfiddle.net/HSKPx/

One thing to note: I may be wrong, but I don't think disabled inputs can normally receive focus, so that part may be redundant.

Alternatively, use :enabled

input:enabled:not([type="submit"]):focus { /* styles here */ }

Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.

Performance of FOR vs FOREACH in PHP

I'm not sure this is so surprising. Most people who code in PHP are not well versed in what PHP is actually doing at the bare metal. I'll state a few things, which will be true most of the time:

  1. If you're not modifying the variable, by-value is faster in PHP. This is because it's reference counted anyway and by-value gives it less to do. It knows the second you modify that ZVAL (PHP's internal data structure for most types), it will have to break it off in a straightforward way (copy it and forget about the other ZVAL). But you never modify it, so it doesn't matter. References make that more complicated with more bookkeeping it has to do to know what to do when you modify the variable. So if you're read-only, paradoxically it's better not the point that out with the &. I know, it's counter intuitive, but it's also true.

  2. Foreach isn't slow. And for simple iteration, the condition it's testing against — "am I at the end of this array" — is done using native code, not PHP opcodes. Even if it's APC cached opcodes, it's still slower than a bunch of native operations done at the bare metal.

  3. Using a for loop "for ($i=0; $i < count($x); $i++) is slow because of the count(), and the lack of PHP's ability (or really any interpreted language) to evaluate at parse time whether anything modifies the array. This prevents it from evaluating the count once.

  4. But even once you fix it with "$c=count($x); for ($i=0; $i<$c; $i++) the $i<$c is a bunch of Zend opcodes at best, as is the $i++. In the course of 100000 iterations, this can matter. Foreach knows at the native level what to do. No PHP opcodes needed to test the "am I at the end of this array" condition.

  5. What about the old school "while(list(" stuff? Well, using each(), current(), etc. are all going to involve at least 1 function call, which isn't slow, but not free. Yes, those are PHP opcodes again! So while + list + each has its costs as well.

For these reasons foreach is understandably the best option for simple iteration.

And don't forget, it's also the easiest to read, so it's win-win.

How to store a list in a column of a database table

No, there is no "better" way to store a sequence of items in a single column. Relational databases are designed specifically to store one value per row/column combination. In order to store more than one value, you must serialize your list into a single value for storage, then deserialize it upon retrieval. There is no other way to do what you're talking about (because what you're talking about is a bad idea that should, in general, never be done).

I understand that you think it's silly to create another table to store that list, but this is exactly what relational databases do. You're fighting an uphill battle and violating one of the most basic principles of relational database design for no good reason. Since you state that you're just learning SQL, I would strongly advise you to avoid this idea and stick with the practices recommended to you by more seasoned SQL developers.

The principle you're violating is called first normal form, which is the first step in database normalization.

At the risk of oversimplifying things, database normalization is the process of defining your database based upon what the data is, so that you can write sensible, consistent queries against it and be able to maintain it easily. Normalization is designed to limit logical inconsistencies and corruption in your data, and there are a lot of levels to it. The Wikipedia article on database normalization is actually pretty good.

Basically, the first rule (or form) of normalization states that your table must represent a relation. This means that:

  • You must be able to differentiate one row from any other row (in other words, you table must have something that can serve as a primary key. This also means that no row should be duplicated.
  • Any ordering of the data must be defined by the data, not by the physical ordering of the rows (SQL is based upon the idea of a set, meaning that the only ordering you should rely on is that which you explicitly define in your query)
  • Every row/column intersection must contain one and only one value

The last point is obviously the salient point here. SQL is designed to store your sets for you, not to provide you with a "bucket" for you to store a set yourself. Yes, it's possible to do. No, the world won't end. You have, however, already crippled yourself in understanding SQL and the best practices that go along with it by immediately jumping into using an ORM. LINQ to SQL is fantastic, just like graphing calculators are. In the same vein, however, they should not be used as a substitute for knowing how the processes they employ actually work.

Your list may be entirely "atomic" now, and that may not change for this project. But you will, however, get into the habit of doing similar things in other projects, and you'll eventually (likely quickly) run into a scenario where you're now fitting your quick-n-easy list-in-a-column approach where it is wholly inappropriate. There is not much additional work in creating the correct table for what you're trying to store, and you won't be derided by other SQL developers when they see your database design. Besides, LINQ to SQL is going to see your relation and give you the proper object-oriented interface to your list automatically. Why would you give up the convenience offered to you by the ORM so that you can perform nonstandard and ill-advised database hackery?

Cannot connect to SQL Server named instance from another SQL Server

I need to do 2 things to connect with instance name

1. Enable SQL Server Browser (in SQL server config manager)
2. Enable UDP, port 1434 trong file wall (if you using amazon EC2 or other service you need open port in their setting too)

Restart sql and done

Express.js: how to get remote client address

  1. Add app.set('trust proxy', true)
  2. Use req.ip or req.ips in the usual way

Special characters like @ and & in cURL POST data

cURL > 7.18.0 has an option --data-urlencode which solves this problem. Using this, I can simply send a POST request as

curl -d name=john --data-urlencode passwd=@31&3*J https://www.mysite.com

How to get address location from latitude and longitude in Google Map.?

Simply pass latitude, longitude and your Google API Key to the following query string, you will get a json array, fetch your city from there.

https://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&key=YOUR_API_KEY

Note: Ensure that no space exists between the latitude and longitude values when passed in the latlng parameter.

Click here to get an API key

Warning comparison between pointer and integer

This: "\0" is a string, not a character. A character uses single quotes, like '\0'.

T-SQL: Selecting rows to delete via joins

It's almost the same in MySQL, but you have to use the table alias right after the word "DELETE":

DELETE a
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]

Check element exists in array

You may be able to use the built-in function dir() to produce similar behavior to PHP's isset(), something like:

if 'foo' in dir():  # returns False, foo is not defined yet.
    pass

foo = 'b'

if 'foo' in dir():  # returns True, foo is now defined and in scope.
   pass

dir() returns a list of the names in the current scope, more information can be found here: http://docs.python.org/library/functions.html#dir.

How many times a substring occurs

s = input('enter the main string: ')
p=input('enter the substring: ')
l=[]
for i in range(len(s)):
    l.append(s[i:i+len(p)])
print(l.count(p))

How do I add an element to array in reducer of React native redux?

If you need to insert into a specific position in the array, you can do this:

case ADD_ITEM :
    return { 
        ...state,
        arr: [
            ...state.arr.slice(0, action.pos),
            action.newItem,
            ...state.arr.slice(action.pos),
        ],
    }

How to get the first five character of a String

Try below code

 string Name = "Abhishek";
 string firstfour = Name.Substring(0, 4);
 Response.Write(firstfour);

When to use NSInteger vs. int

Why use int at all?

Apple uses int because for a loop control variable (which is only used to control the loop iterations) int datatype is fine, both in datatype size and in the values it can hold for your loop. No need for platform dependent datatype here. For a loop control variable even a 16-bit int will do most of the time.

Apple uses NSInteger for a function return value or for a function argument because in this case datatype [size] matters, because what you are doing with a function is communicating/passing data with other programs or with other pieces of code; see the answer to When should I be using NSInteger vs int? in your question itself...

they [Apple] use NSInteger (or NSUInteger) when passing a value as an argument to a function or returning a value from a function.

Why do you have to link the math library in C?

I think it's kind of arbitrary. You have to draw a line somewhere (which libraries are default and which need to be specified).

It gives you the opportunity to replace it with a different one that has the same functions, but I don't think it's very common to do so.

EDIT: (from my own comments): I think gcc does this to maintain backwards compatibility with the original cc. My guess for why cc does this is because of build time -- cc was written for machines with far less power than we have now. A lot of programs have no floating-point math and they probably took every library that wasn't commonly used out of the default. I'm guessing that the build time of the UNIX OS and the tools that go along with it were the driving force.

Difference between Activity Context and Application Context

This obviously is deficiency of the API design. In the first place, Activity Context and Application context are totally different objects, so the method parameters where context is used should use ApplicationContext or Activity directly, instead of using parent class Context. In the second place, the doc should specify which context to use or not explicitly.

Confirm postback OnClientClick button ASP.NET

Try this:

<asp:Button runat="server" ID="btnDelete" Text="Delete"
   onClientClick="javascript:return confirm('Are you sure you want to delete this user?');" OnClick="BtnDelete_Click" />

Adjusting the Xcode iPhone simulator scale and size

You can set any scale you wish. It`s became actual after 6+ simulator been presented

To obtain it follow next easy steps:

  1. quit simulator if open
  2. open terminal (from spotlight for example)
  3. paste next text to terminal and press enter

defaults write ~/Library/Preferences/com.apple.iphonesimulator SimulatorWindowLastScale "0.4"

You can try any scales changing 0.4 to desired value.

To reset this custom scale, just apply any standard scale from simulator menu in way described above.

How to sort an array of objects in Java?

With Java 8, you can use a reference method.

You could add compare method to your Book class

class Book {
     public static int compare(Book a, Book b)
     {
         return a.name.compareTo(b.name);
     }
}

And then you could do this :

Arrays.sort(books , Book::compare);

Here is the full example:

class Book {
    String name;
    String author;

    public Book(String name, String author) {
        this.name = name;
        this.author = author;
    }

    public static int compareBooks(Book a , Book b)
    {
        return a.name.compareTo(b.name);
    }

    @Override
    public String toString() {
        return "name : " + name + "\t" + "author : " + author;
    }


    public static void main(String[] args) {

        Book[] books = {
                new Book("Book 3" , "Author 1"),
                new Book("Book 2" , "Author 2"),
                new Book("Book 1" , "Author 3"),
                new Book("Book 4" , "Author 4")
        };

        Arrays.sort(books , Book::compareBooks);
        Arrays.asList(books).forEach(System.out::println);

    }
}

JavaScript/jQuery - How to check if a string contain specific words

_x000D_
_x000D_
var str1 = "STACKOVERFLOW";_x000D_
var str2 = "OVER";_x000D_
if(str1.indexOf(str2) != -1){_x000D_
    console.log(str2 + " found");_x000D_
}
_x000D_
_x000D_
_x000D_

PHP mail not working for some reason

This is probably a configuration error. If you insist on using PHP mail function, you will have to edit php.ini.

If you are looking for an easier and more versatile option (in my opinion), you should use PHPMailer.

How can I convert a stack trace to a string?

The solution is to convert the stackTrace of array to string data type. See the following example:

import java.util.Arrays;

try{

}catch(Exception ex){
    String stack = Arrays.toString(ex.getStackTrace());
    System.out.println("stack "+ stack);
}

JavaScript Regular Expression Email Validation

I have been using this one....

/^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/

It allows that + before @ ([email protected])

Spring Boot @Value Properties

I had the same issue get value for my property in my service class. I resolved it by using @ConfigurationProperties instead of @Value.

  1. create a class like this:
    import org.springframework.boot.context.properties.ConfigurationProperties;

    @ConfigurationProperties(prefix = "file")
    public class FileProperties {
        private String directory;

        public String getDirectory() {
            return directory;
        }

        public void setDirectory(String dir) {
            this.directory = dir;
        }
    }

  1. add the following to your BootApplication class:
    @EnableConfigurationProperties({
        FileProperties.class
    })
  1. Inject FileProperties to your PrintProperty class, then you can get hold of the property through the getter method.

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

For Perfect DateTime Match in SQL Server

SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

Settings to Windows Firewall to allow Docker for Windows to share drive

In my case, I disabled "Block TCP 445" on Windows Defender Firewall with Advanced Security and it worked. Then enabled it again after setting shared drives on Docker.

setting of Block TCP 445

setting of Shared drives

Setting a max height on a table

Use divs with max height and min height around the content that needs to scroll.

<tr>
    <td>
        <div>content</div>
    </td>
</tr>

td div{
    max-height:20px;
}

https://jsfiddle.net/ethanabrace/4w0ksczr/

Clearing state es6 React

First, you'll need to store your initial state when using the componentWillMount() function from the component lifecycle:

componentWillMount() {
    this.initialState = this.state
}

This stores your initial state and can be used to reset the state whenever you need by calling

this.setState(this.initialState)

Updating .class file in jar

Simply drag and drop your new class file to the JAR using 7-Zip or Winzip. You can even modify a JAR file that is included in a WAR file using the parent folder icon, and click Ok when 7zip detects that the inside file has been modified

Netbeans how to set command line arguments in Java

This worked for me, use the VM args in NetBeans:

@Value("${a.b.c:#{abc}}"
...

@Value("${e.f.g:#{efg}}"
...

Netbeans:

-Da.b.c="..." -De.f.g="..."

Properties -> Run -> VM Options -> -De.f.g=efg -Da.b.c=abc

From the commandline

java -jar <yourjar> --Da.b.c="abc" 

"The page has expired due to inactivity" - Laravel 5.5

If you're coming to this answer directly from a search, make sure you have already added the csrf token to your form with {{ csrf_field() }} like the OP.


If you have your session driver set to file:

May have something to do with the storage_path not being writable. This is where it stores session data regarding tokens if you're using file based sessions. The can be verified with is_writable(config('session.files'))


For the OP, the session driver was set to array. Array is for testing only. Since data is not persisted, it will not be able to compare the token on the next request.

The array driver is used during testing and prevents the data stored in the session from being persisted.

https://laravel.com/docs/5.5/session#configuration


Check config/session.php

Lastly, an issue I just had, we had a project which has the session domain and secure settings in config/session.php but the development site was not using HTTPS (SSL/TLS). This caused this generic error since sessions.secure was set to true by default.

trace a particular IP and port

Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.

You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).

Get Path from another app (WhatsApp)

Using the code example below will return to you the bitmap :

BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/128752")))

After that you all know what you have to do.

Converting a value to 2 decimal places within jQuery

Try to use this

parseFloat().toFixed(2)

How do I send a POST request as a JSON?

This one works fine for me with apis

import requests

data={'Id':id ,'name': name}
r = requests.post( url = 'https://apiurllink', data = data)

Netbeans - class does not have a main method

This destroyed me for a while.... I knew that there HAD to be an easier way with a world class IDE like Netbeans.

The easiest method is to press Shift+F11 (Clean and Build Project), then hit F6 to run it.

It refreshes Netbeans appropriately and finds your main without all the manual labor; and if you have multiple mains, it will give you the option to select the correct one.

Using XPATH to search text containing &nbsp;

I cannot get a match using Xpather, but the following worked for me with plain XML and XSL files in Microsoft's XML Notepad:

<xsl:value-of select="count(//td[text()='&nbsp;'])" />

The value returned is 1, which is the correct value in my test case.

However, I did have to declare nbsp as an entity within my XML and XSL using the following:

<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#160;"> ]>

I'm not sure if that helps you, but I was able to actually find nbsp using an XPath expression.

Edit: My code sample actually contains the characters '&nbsp;' but the JavaScript syntax highlight converts it to the space character. Don't be mislead!

Laravel - Form Input - Multiple select for a one to many relationship

This might be a better approach than top answer if you need to compare 2 output arrays to each other but use the first array to populate the options.

This is also helpful when you have a non-numeric or offset index (key) in your array.

<select name="roles[]" multiple>
    @foreach($roles as $key => $value)
        <option value="{{$key}}" @if(in_array($value, $compare_roles))selected="selected"@endif>
            {{$value}}
        </option>
    @endforeach
</select>

Where can I read the Console output in Visual Studio 2015

What may be happening is that your console is closing before you get a chance to see the output. I would add Console.ReadLine(); after your Console.WriteLine("Hello World"); so your code would look something like this:

static void Main(string[] args)
    {
        Console.WriteLine("Hello World");
        Console.ReadLine();

    }

This way, the console will display "Hello World" and a blinking cursor underneath. The Console.ReadLine(); is the key here, the program waits for the users input before closing the console window.

What is the HTML tabindex attribute?

In Simple words, tabindex is used to focus on elements. Syntax: tabindex="numeric_value" This numeric_value is the weight of element. Lower value will be accessed first.

How to create a JSON object

Although the other answers posted here work, I find the following approach more natural:

$obj = (object) [
    'aString' => 'some string',
    'anArray' => [ 1, 2, 3 ]
];

echo json_encode($obj);

not:first-child selector

not(:first-child) does not seem to work anymore. At least with the more recent versions of Chrome and Firefox.

Instead, try this:

ul:not(:first-of-type) {}

Difference between Node object and Element object?

Node : http://www.w3schools.com/js/js_htmldom_nodes.asp

The Node object represents a single node in the document tree. A node can be an element node, an attribute node, a text node, or any other of the node types explained in the Node Types chapter.

Element : http://www.w3schools.com/js/js_htmldom_elements.asp

The Element object represents an element in an XML document. Elements may contain attributes, other elements, or text. If an element contains text, the text is represented in a text-node.

duplicate :

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

Send Message in C#

You don't need to send messages.

Add an event to the one form and an event handler to the other. Then you can use a third project which references the other two to attach the event handler to the event. The two DLLs don't need to reference each other for this to work.

How to check if a line is blank using regex

The pattern you want is something like this in multiline mode:

^\s*$

Explanation:

  • ^ is the beginning of string anchor.
  • $ is the end of string anchor.
  • \s is the whitespace character class.
  • * is zero-or-more repetition of.

In multiline mode, ^ and $ also match the beginning and end of the line.

References:


A non-regex alternative:

You can also check if a given string line is "blank" (i.e. containing only whitespaces) by trim()-ing it, then checking if the resulting string isEmpty().

In Java, this would be something like this:

if (line.trim().isEmpty()) {
    // line is "blank"
}

The regex solution can also be simplified without anchors (because of how matches is defined in Java) as follows:

if (line.matches("\\s*")) {
    // line is "blank"
}

API references

Project has no default.properties file! Edit the project properties to set one

Right click on project --> properties --> Android.

Change the checkbox for project build target.

Press apply.

Change it back to your original build target.

Press apply --> ok

Worked for me

CSS strikethrough different color from text?

This CSS3 will make you line through property more easier, and working fine.

span{
    text-decoration: line-through;
    text-decoration-color: red;
}

Encrypt and decrypt a password in Java

Jasypt can do it for you easy and simple

jQuery - selecting elements from inside a element

You can use any one these [starting from the fastest]

$("#moo") > $("#foo #moo") > $("div#foo span#moo") > $("#foo span") > $("#foo > #moo")

Take a look

php, mysql - Too many connections to database error

If you are reaching the mac connection limit go to /etc/my.cnf and under the [mysqld] section add max_connections = 500

and restart MySQL.

What are the -Xms and -Xmx parameters when starting JVM?

You can specify it in your IDE. For example, for Eclipse in Run Configurations ? VM arguments. You can enter -Xmx800m -Xms500m as

Enter image description here

Quickest way to convert XML to JSON in Java

I don't know what your exact problem is, but if you're receiving XML and want to return JSON (or something) you could also look at JAX-B. This is a standard for marshalling/unmarshalling Java POJO's to XML and/or Json. There are multiple libraries that implement JAX-B, for example Apache's CXF.

Setting std=c99 flag in GCC

Instead of calling /usr/bin/gcc, use /usr/bin/c99. This is the Single-Unix-approved way of invoking a C99 compiler. On an Ubuntu system, this points to a script which invokes gcc after having added the -std=c99 flag, which is precisely what you want.

Scroll / Jump to id without jQuery

Add the function:

function scrollToForm() {
  document.querySelector('#form').scrollIntoView({behavior: 'smooth'});
}

Trigger the function:

<a href="javascript: scrollToForm();">Jump to form</a>

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

How to create a list of objects?

Storing a list of object instances is very simple

class MyClass(object):
    def __init__(self, number):
        self.number = number

my_objects = []

for i in range(100):
    my_objects.append(MyClass(i))

# later

for obj in my_objects:
    print obj.number

Creating threads - Task.Factory.StartNew vs new Thread()

The task gives you all the goodness of the task API:

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

Note that in both cases you can make your code slightly simpler with method group conversions:

DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);

Difference between thread's context class loader and normal classloader

There is an article on javaworld.com that explains the difference => Which ClassLoader should you use

(1)

Thread context classloaders provide a back door around the classloading delegation scheme.

Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.

(2) from the same source:

This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:

  • JNDI uses context classloaders
  • Class.getResource() and Class.forName() use the current classloader
  • JAXP uses context classloaders (as of J2SE 1.4)
  • java.util.ResourceBundle uses the caller's current classloader
  • URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
  • Java Serialization API uses the caller's current classloader by default

How to transfer data from JSP to servlet when submitting HTML form

Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet and inside it you will have two methods that look like

public void doPost(HttpServletRequest req, HttpServletResponse resp){

}

and

public void doGet(HttpServletRequest req, HttpServletResponse resp){

}

One of them is called to handle GET operations and another is used to handle POST operations. You will then use the HttpServletRequest object to get the parameters that were passed as part of the form like so:

String name = req.getParameter("name");

Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.

Cleanest way to write retry logic?

This method allows retries on certain exception types (throws others immediately).

public static void DoRetry(
    List<Type> retryOnExceptionTypes,
    Action actionToTry,
    int retryCount = 5,
    int msWaitBeforeEachRety = 300)
{
    for (var i = 0; i < retryCount; ++i)
    {
        try
        {
            actionToTry();
            break;
        }
        catch (Exception ex)
        {
            // Retries exceeded
            // Throws on last iteration of loop
            if (i == retryCount - 1) throw;

            // Is type retryable?
            var exceptionType = ex.GetType();
            if (!retryOnExceptionTypes.Contains(exceptionType))
            {
                throw;
            }

            // Wait before retry
            Thread.Sleep(msWaitBeforeEachRety);
        }
    }
}
public static void DoRetry(
    Type retryOnExceptionType,
    Action actionToTry,
    int retryCount = 5,
    int msWaitBeforeEachRety = 300)
        => DoRetry(new List<Type> {retryOnExceptionType}, actionToTry, retryCount, msWaitBeforeEachRety);

Example usage:

DoRetry(typeof(IOException), () => {
    using (var fs = new FileStream(requestedFilePath, FileMode.Create, FileAccess.Write))
    {
        fs.Write(entryBytes, 0, entryBytes.Length);
    }
});

How do I convert from BLOB to TEXT in MySQL?

If you are using MYSQL-WORKBENCH, then you can select blob column normally and right click on column and click open value in editor. refer screenshot:

screenshot

How do I collapse sections of code in Visual Studio Code for Windows?

v1.42 is adding some nice refinements to how folds look and function. See https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_42.md#folded-range-highlighting:

Folded Range Highlighting

Folded ranges now are easier to discover thanks to a background color for all folded ranges.

fold highlight

Fold highlight color Theme: Dark+

The feature is controled by the setting editor.foldingHighlight and the color can be customized with the color editor.foldBackground.

"workbench.colorCustomizations": { "editor.foldBackground": "#355000" }

Folding Refinements

Shift + Click on the folding indicator first only folds the inner ranges. Shift + Click again (when all inner ranges are already folded) will also fold the parent. Shift + Click again unfolds all.

fold shift click

When using the Fold command (kb(editor.fold))] on an already folded range, the next unfolded parent range will be folded.

Overlay with spinner

And for a spinner like iOs I use this:

enter image description here

html:

  <div class='spinner'>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>

Css:

.spinner {
  font-size: 30px;
  position: relative;
  display: inline-block;
  width: 1em;
  height: 1em;
}

.spinner div {
  position: absolute;
  left: 0.4629em;
  bottom: 0;
  width: 0.074em;
  height: 0.2777em;
  border-radius: 0.5em;
  background-color: transparent;
  -webkit-transform-origin: center -0.2222em;
      -ms-transform-origin: center -0.2222em;
          transform-origin: center -0.2222em;
  -webkit-animation: spinner-fade 1s infinite linear;
          animation: spinner-fade 1s infinite linear;
}
.spinner div:nth-child(1) {
  -webkit-animation-delay: 0s;
          animation-delay: 0s;
  -webkit-transform: rotate(0deg);
      -ms-transform: rotate(0deg);
          transform: rotate(0deg);
}
.spinner div:nth-child(2) {
  -webkit-animation-delay: 0.083s;
          animation-delay: 0.083s;
  -webkit-transform: rotate(30deg);
      -ms-transform: rotate(30deg);
          transform: rotate(30deg);
}
.spinner div:nth-child(3) {
  -webkit-animation-delay: 0.166s;
          animation-delay: 0.166s;
  -webkit-transform: rotate(60deg);
      -ms-transform: rotate(60deg);
          transform: rotate(60deg);
}
.spinner div:nth-child(4) {
  -webkit-animation-delay: 0.249s;
          animation-delay: 0.249s;
  -webkit-transform: rotate(90deg);
      -ms-transform: rotate(90deg);
          transform: rotate(90deg);
}
.spinner div:nth-child(5) {
  -webkit-animation-delay: 0.332s;
          animation-delay: 0.332s;
  -webkit-transform: rotate(120deg);
      -ms-transform: rotate(120deg);
          transform: rotate(120deg);
}
.spinner div:nth-child(6) {
  -webkit-animation-delay: 0.415s;
          animation-delay: 0.415s;
  -webkit-transform: rotate(150deg);
      -ms-transform: rotate(150deg);
          transform: rotate(150deg);
}
.spinner div:nth-child(7) {
  -webkit-animation-delay: 0.498s;
          animation-delay: 0.498s;
  -webkit-transform: rotate(180deg);
      -ms-transform: rotate(180deg);
          transform: rotate(180deg);
}
.spinner div:nth-child(8) {
  -webkit-animation-delay: 0.581s;
          animation-delay: 0.581s;
  -webkit-transform: rotate(210deg);
      -ms-transform: rotate(210deg);
          transform: rotate(210deg);
}
.spinner div:nth-child(9) {
  -webkit-animation-delay: 0.664s;
          animation-delay: 0.664s;
  -webkit-transform: rotate(240deg);
      -ms-transform: rotate(240deg);
          transform: rotate(240deg);
}
.spinner div:nth-child(10) {
  -webkit-animation-delay: 0.747s;
          animation-delay: 0.747s;
  -webkit-transform: rotate(270deg);
      -ms-transform: rotate(270deg);
          transform: rotate(270deg);
}
.spinner div:nth-child(11) {
  -webkit-animation-delay: 0.83s;
          animation-delay: 0.83s;
  -webkit-transform: rotate(300deg);
      -ms-transform: rotate(300deg);
          transform: rotate(300deg);
}
.spinner div:nth-child(12) {
  -webkit-animation-delay: 0.913s;
          animation-delay: 0.913s;
  -webkit-transform: rotate(330deg);
      -ms-transform: rotate(330deg);
          transform: rotate(330deg);
}

@-webkit-keyframes spinner-fade {
  0% {
    background-color: #69717d;
  }
  100% {
    background-color: transparent;
  }
}

@keyframes spinner-fade {
  0% {
    background-color: #69717d;
  }
  100% {
    background-color: transparent;
  }
}

get from this website : https://365webresources.com/10-best-pure-css-loading-spinners-front-end-developers/

Reading data from DataGridView in C#

string[,] myGridData = new string[dataGridView1.Rows.Count,3];

int i = 0;

foreach(DataRow row in dataGridView1.Rows)

{

    myGridData[i][0] = row.Cells[0].Value.ToString();
    myGridData[i][1] = row.Cells[1].Value.ToString();
    myGridData[i][2] = row.Cells[2].Value.ToString();

    i++;
}

Hope this helps....

make: *** [ ] Error 1 error

Sometimes you will get lots of compiler outputs with many warnings and no line of output that says "error: you did something wrong here" but there was still an error. An example of this is a missing header file - the compiler says something like "no such file" but not "error: no such file", then it exits with non-zero exit code some time later (perhaps after many more warnings). Make will bomb out with an error message in these cases!

Change the maximum upload file size

Perhaps this should be a comment to @seanb123 and @Fredrick Gauss commenting on his comment, but for me in Drupal 8.1 with PHP 7 the file I needed to modify was located here:

/etc/php/7.0/apache2/php.ini

I modded probably four other php.ini files, including the one my system called the "Loaded Configuration File" (php -i | grep -i "loaded configuration file") and the one found on the info.php page but none of them helped. The key to discovering the correct path was found on a site from 2012. They said the path "/etc/php5/apache2/php.ini" was deprecated even BACK THEN but it gave me a clue where to find it. For PHP7 it's a little different than in PHP5 but the concept is the same.

Maybe this will help some otherwise helpless schmuck like myself.

That being said, the answer to the OP in my case would be that someone with admin privileges on the box would have to do it.

The site that helped me: http://www.evilbox.ro/linux/remove-ispconfig-maximum-upload-size-of-2m-for-wordpress/

This is also addressed here: Import file size limit in PHPMyAdmin

EDIT: the full text of my note to myself:

In order to change the max upload size, edit upload_max_filesize and [if needed?] post_max_size in /etc/php/7.0/apache2/php.ini (or in older versions: /etc/php5/apache2/php.ini )

/etc/init.d/apache2 restart

EDIT AGAIN: since you're importing big files you may need to change the timeout for processing them. In my case, the file named, "config.default.php" was found at /usr/share/phpmyadmin/libraries/config.default.php with the variable $cfg['ExecTimeLimit'] = 300; I changed mine to 900 for a huge import, for instance. Afterward you need to restart apache

Get connection string from App.config

I referenced System.Configuration library and I have the same error. The debug files had not their app.config, create manually this file. The error is, I solved this copying the file "appname.exe.config" in debug folder. The IDE was not create the file.

app.config for a class library

Actually, for some rare case you could store app.config in class libraries (by adding manually) and parse it by OpenExeConfiguration.

 var fileMap =
    new ExeConfigurationFileMap {ExeConfigFilename = 
    @"C:\..somePath..\someName.config"};
 System.Configuration.Configuration config =
    ConfigurationManager.OpenMappedExeConfiguration(fileMap, 
    ConfigurationUserLevel.None);

You should really estimate the real need of this. For abstract data its not the best solution, but "Config Sections" could be very usefull!!

For example, we organised our N-Tier WCF architecture decoupled, without any metadata, simply by using Unity Container and Injection Factory based on Channel Factory T. We added externall ClassLibrary dll with just [Service Contract] Interfaces and common app.config in order to read endpoints from clientsection, and easily add/change them at one place.

Is there any way to prevent input type="number" getting negative values?

For me the solution was:

_x000D_
_x000D_
<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
_x000D_
_x000D_
_x000D_

Edit

As suggested on the comments with a minor change to work if 0 is the min value.

_x000D_
_x000D_
<input type="number" min="0" oninput="this.value = 
 !!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
_x000D_
_x000D_
_x000D_

git still shows files as modified after adding to .gitignore

Using git rm --cached *file* is not working fine for me (I'm aware this question is 8 years old, but it still shows at the top of the search for this topic), it does remove the file from the index, but it also deletes the file from the remote.

I have no idea why that is. All I wanted was keeping my local config isolated (otherwise I had to comment the localhost base url before every commit), not delete the remote equivalent to config.

Reading some more I found what seems to be the proper way to do this, and the only way that did what I needed, although it does require more attention, especially during merges.

Anyway, all it requires is git update-index --assume-unchanged *path/to/file*.

As far as I understand, this is the most notable thing to keep in mind:

Git will fail (gracefully) in case it needs to modify this file in the index e.g. when merging in a commit; thus, in case the assumed-untracked file is changed upstream, you will need to handle the situation manually.

Rotate camera in Three.js with mouse

Here's a project with a rotating camera. Looking through the source it seems to just move the camera position in a circle.

function onDocumentMouseMove( event ) {

    event.preventDefault();

    if ( isMouseDown ) {

        theta = - ( ( event.clientX - onMouseDownPosition.x ) * 0.5 )
                + onMouseDownTheta;
        phi = ( ( event.clientY - onMouseDownPosition.y ) * 0.5 )
              + onMouseDownPhi;

        phi = Math.min( 180, Math.max( 0, phi ) );

        camera.position.x = radious * Math.sin( theta * Math.PI / 360 )
                            * Math.cos( phi * Math.PI / 360 );
        camera.position.y = radious * Math.sin( phi * Math.PI / 360 );
        camera.position.z = radious * Math.cos( theta * Math.PI / 360 )
                            * Math.cos( phi * Math.PI / 360 );
        camera.updateMatrix();

    }

    mouse3D = projector.unprojectVector(
        new THREE.Vector3(
            ( event.clientX / renderer.domElement.width ) * 2 - 1,
            - ( event.clientY / renderer.domElement.height ) * 2 + 1,
            0.5
        ),
        camera
    );
    ray.direction = mouse3D.subSelf( camera.position ).normalize();

    interact();
    render();

}

Here's another demo and in this one I think it just creates a new THREE.TrackballControls object with the camera as a parameter, which is probably the better way to go.

controls = new THREE.TrackballControls( camera );
controls.target.set( 0, 0, 0 )

Group By Multiple Columns

group x by new { x.Col, x.Col}

What is the difference between parseInt() and Number()?

Because none mentioned, when using Number and parseInt with numeric separator, they also behave differently:

const num1 = 5_0; // 50
const num2 = Number(5_0); // 50
const num3 = Number("5_0"); // NaN
const num4 = parseInt(5_0); // 50
const num5 = parseInt("5_0"); // 5

Parse error: Syntax error, unexpected end of file in my PHP code

In my case the culprit was the lone opening <?php tag in the last line of the file. Apparently it works on some configurations with no problems but causes problems on others.

Crop image in PHP

$image = imagecreatefromjpeg($_GET['src']);

Needs to be replaced with this:

$image = imagecreatefromjpeg('images/thumbnails/myimage.jpg');

Because imagecreatefromjpeg() is expecting a string.
This worked for me.

ref:
http://php.net/manual/en/function.imagecreatefromjpeg.php

Excel how to fill all selected blank cells with text

Here's a tricky way to do this - select the cells that you want to replace and in Excel 2010 select F5 to bring up the "goto" box. Hit the "special" button. Select "blanks" - this should select all the cells that are blank. Enter NULL or whatever you want in the formula box and hit ctrl + enter to apply to all selected cells. Easy!

How to convert C# nullable int to int

As far as I'm concerned the best solution is using GetValueOrDefault() method.

v2 = v1.GetValueOrDefault();

How do I detect if I am in release or debug mode?

Build.IS_DEBUGGABLE could be all right. It comes from "ro.debuggable"

How to check if Location Services are enabled?

To check for network provider you just need to change the string passed to isProviderEnabled to LocationManager.NETWORK_PROVIDER if you check the return values for both GPS provider and NETwork provider - both false means no location services

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

Change Background color (css property) using Jquery

1.Remove onclick method from div element

2.Remove function change() from jQuery code and in place of that create an anonymous function like:

$(document).ready(function()
{

  $('#co').click(function()
   {

  $('body').css('background-color','blue');
  });
});

phpMyAdmin - Error > Incorrect format parameter?

Note: If you're using MAMP you MUST edit the file using the built-in editor.

Select PHP in the languages section (LH Menu Column) Next, in the main panel next to the default version drop-down click the small arrow pointing to the right. This will launch the php.ini file using the MAMP text editor. Any changes you make to this file will persist after you restart the servers.

Editing the file through Application->MAMP->bin->php->{choosen the version}->php.ini would not work. Since the application overwrites any changes you make.

Needless to say: "Here be dragons!" so please cut and paste a copy of the original and store it somewhere safe in case of disaster.enter image description here

How do I empty an input value with jQuery?

Usual way to empty textbox using jquery is:

$('#txtInput').val('');

If above code is not working than please check that you are able to get the input element.

console.log($('#txtInput')); // should return element in the console.

If still facing the same problem, please post your code.

How to generate an openSSL key using a passphrase from the command line?

If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.

You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar):

openssl genrsa -aes128 -passout pass:foobar 3072

However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.

A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:

openssl genrsa -aes128 -passout file:passphrase.txt 3072

Or supply the passphrase on standard input:

openssl genrsa -aes128 -passout stdin 3072

You can also used a named pipe with the file: option, or a file descriptor.


To then obtain the matching public key, you need to use openssl rsa, supplying the same passphrase with the -passin parameter as was used to encrypt the private key:

openssl rsa -passin file:passphrase.txt -pubout

(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>).


Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar:

openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub

What is LD_LIBRARY_PATH and how to use it?

Well, the error message tells you what to do: add the path where Jacob.dll resides to java.library.path. You can do that on the command line like this:

java -Djava.library.path="dlls" ...

(assuming Jacob.dll is in the "dlls" folder)

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

How to prevent scrollbar from repositioning web page?

I use to have that problem, but the simples way to fix it is this (this works for me):

on the CSS file type:

body{overflow-y:scroll;}

as that simple! :)

Python, how to check if a result set is empty?

You can do like this :

count = 0
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=serverName;"
                      "Trusted_Connection=yes;")
cursor = cnxn.cursor()
cursor.execute(SQL query)
for row in cursor:
    count = 1
    if true condition:
        print("True")
    else:
        print("False")
if count == 0:
    print("No Result")

Thanks :)

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

How to store an output of shell script to a variable in Unix?

You should probably re-write the script to return a value rather than output it. Instead of:

a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
   success) echo script succeeded;;
   Failed) echo script failed;;
esac

you would be able to do:

if script.sh > /dev/null; then
    echo script succeeded
else
    echo script failed
fi

It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0 instead of printing success, and exit 1 instead of printing Failed. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.

Hibernate Error executing DDL via JDBC Statement

I guess you are using an old version of hibernate. You can download the latest version, 5.2, from here.

Is there a conditional ternary operator in VB.NET?

If() is the closest equivalent but beware of implicit conversions going on if you have set "Option Strict off"

For example, if your not careful you may be tempted to try something like:

Dim foo As Integer? = If(someTrueExpression, Nothing, 2)

Will give "foo" a value of 0!

I think the '?' operator equivalent in C# would instead fail compilation

How to rotate portrait/landscape Android emulator?

Yes. Thanks

Ctrl + F11 for Portrait

and

Ctrl + F12 for Landscape

How to run stored procedures in Entity Framework Core?

"(SqlConnection)context" -- This type-casting no longer works. You can do: "SqlConnection context;

".AsSqlServer()" -- Does not Exist.

"command.ExecuteNonQuery();" -- Does not return results. reader=command.ExecuteReader() does work.

With dt.load(reader)... then you have to switch the framework out of 5.0 and back to 4.51, as 5.0 does not support datatables/datasets, yet. Note: This is VS2015 RC.

READ_EXTERNAL_STORAGE permission for Android

Please Check below code that using that You can find all Music Files from sdcard :

public class MainActivity extends Activity{

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

}

public void getAllSongsFromSDCARD() {
    String[] STAR = { "*" };
    Cursor cursor;
    Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

    cursor = managedQuery(allsongsuri, STAR, selection, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                String song_name = cursor
                        .getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                int song_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media._ID));

                String fullpath = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.DATA));

                String album_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM));
                int album_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));

                String artist_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST));
                int artist_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
                System.out.println("sonng name"+fullpath);
            } while (cursor.moveToNext());

        }
        cursor.close();
    }
}


}

I have also added following line in the AndroidManifest.xml file as below:

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to sort an array of ints using a custom comparator?

Here is some code (it's actually not Timsort as I originally thought, but it does work well) that does the trick without any boxing/unboxing. In my tests, it works 3-4 times faster than using Collections.sort with a List wrapper around the array.

// This code has been contributed by 29AjayKumar 
// from: https://www.geeksforgeeks.org/sort/

static final int sortIntArrayWithComparator_RUN = 32; 

// this function sorts array from left index to  
// to right index which is of size atmost RUN  
static void sortIntArrayWithComparator_insertionSort(int[] arr, IntComparator comparator, int left, int right) { 
    for (int i = left + 1; i <= right; i++)  
    { 
        int temp = arr[i]; 
        int j = i - 1; 
        while (j >= left && comparator.compare(arr[j], temp) > 0)
        { 
            arr[j + 1] = arr[j]; 
            j--; 
        } 
        arr[j + 1] = temp; 
    } 
} 

// merge function merges the sorted runs  
static void sortIntArrayWithComparator_merge(int[] arr, IntComparator comparator, int l, int m, int r) { 
    // original array is broken in two parts  
    // left and right array  
    int len1 = m - l + 1, len2 = r - m; 
    int[] left = new int[len1]; 
    int[] right = new int[len2]; 
    for (int x = 0; x < len1; x++)  
    { 
        left[x] = arr[l + x]; 
    } 
    for (int x = 0; x < len2; x++)  
    { 
        right[x] = arr[m + 1 + x]; 
    } 

    int i = 0; 
    int j = 0; 
    int k = l; 

    // after comparing, we merge those two array  
    // in larger sub array  
    while (i < len1 && j < len2)  
    { 
        if (comparator.compare(left[i], right[j]) <= 0)
        { 
            arr[k] = left[i]; 
            i++; 
        } 
        else 
        { 
            arr[k] = right[j]; 
            j++; 
        } 
        k++; 
    } 

    // copy remaining elements of left, if any  
    while (i < len1) 
    { 
        arr[k] = left[i]; 
        k++; 
        i++; 
    } 

    // copy remaining element of right, if any  
    while (j < len2)  
    { 
        arr[k] = right[j]; 
        k++; 
        j++; 
    } 
} 

// iterative sort function to sort the  
// array[0...n-1] (similar to merge sort)  
static void sortIntArrayWithComparator(int[] arr, IntComparator comparator) { sortIntArrayWithComparator(arr, lIntArray(arr), comparator); }
static void sortIntArrayWithComparator(int[] arr, int n, IntComparator comparator) { 
    // Sort individual subarrays of size RUN  
    for (int i = 0; i < n; i += sortIntArrayWithComparator_RUN)  
    { 
        sortIntArrayWithComparator_insertionSort(arr, comparator, i, Math.min((i + 31), (n - 1))); 
    } 

    // start merging from size RUN (or 32). It will merge  
    // to form size 64, then 128, 256 and so on ....  
    for (int size = sortIntArrayWithComparator_RUN; size < n; size = 2 * size)  
    { 
          
        // pick starting point of left sub array. We  
        // are going to merge arr[left..left+size-1]  
        // and arr[left+size, left+2*size-1]  
        // After every merge, we increase left by 2*size  
        for (int left = 0; left < n; left += 2 * size)  
        { 
              
            // find ending point of left sub array  
            // mid+1 is starting point of right sub array  
            int mid = Math.min(left + size - 1, n - 1);
            int right = Math.min(left + 2 * size - 1, n - 1); 

            // merge sub array arr[left.....mid] &  
            // arr[mid+1....right]  
            sortIntArrayWithComparator_merge(arr, comparator, left, mid, right); 
        } 
    } 
}

static int lIntArray(int[] a) {
  return a == null ? 0 : a.length;
}

static interface IntComparator {
  int compare(int a, int b);
}

Run all SQL files in a directory

You could use ApexSQL Propagate. It is a free tool which executes multiple scripts on multiple databases. You can select as many scripts as you need and execute them against one or multiple databases (even multiple servers). You can create scripts list and save it, then just select that list each time you want to execute those same scripts in the created order (multiple script lists can be added also):

Select scripts

When scripts and databases are selected, they will be shown in the main window and all you have to do is to click the “Execute” button and all scripts will be executed on selected databases in the given order:

Scripts execution

How to check cordova android version of a cordova/phonegap project?

For getting all the info about the cordova package use this command:

npm info cordova

Does java.util.List.isEmpty() check if the list itself is null?

Yes, it will throw an Exception. maybe you are used to PHP code, where empty($element) does also check for isset($element)? In Java this is not the case.

You can memorize that easily because the method is directly called on the list (the method belongs to the list). So if there is no list, then there is no method. And Java will complain that there is no list to call this method on.

Remove credentials from Git

  1. Go to C:\Users\<current-user>
  2. check for .git-credentials file
  3. Delete content or modify as per your requirement
  4. Restart your terminal

How do you attach and detach from Docker's process?

For anyone who ran into the same problem I did (can't detach without killing the container, even when setting the detach key)......

When starting your containers with docker-compose up -d

instead of using docker attach {container name} to view the tailing log ....

try docker-compose logs -f {service name} ctrl-c kills the log tail without killing your container

{service name} being the service listed in side of your docker-compose.yml file.. (e.g. while container name=elk_logstash_1 -> service name=logstash

HTH

Failed to authenticate on SMTP server error using gmail

Did you turn on the "Allow less secure apps" on? go to this link

https://myaccount.google.com/security#connectedapps

Take a look at the Sign-in & security -> Apps with account access menu.

You must turn the option "Allow less secure apps" ON.

If is still doesn't work try one of these:

And change your .env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=xxxxxx
MAIL_ENCRYPTION=tls

because the one's you have specified in the mail.php will only be used if the value is not available in the .env file.

Maven dependencies are failing with a 501 error

The following link got me out of the trouble,

https://support.sonatype.com/hc/en-us/articles/360041287334-Central-501-HTTPS-Required

You could make the changes either in your maven, apache-maven/conf/settings.xml. Or, if you are specifying in your pom.xml, make the change there.

Before,

<repository>
            <id>maven_central_repo</id>
            <url>http://repo.maven.apache.org/maven2</url>
</repository>

Now,

<repository>
            <id>maven_central_repo</id>
            <url>https://repo.maven.apache.org/maven2</url>
</repository>

How to evaluate a math expression given in string form?

I've written this eval method for arithmetic expressions to answer this question. It does addition, subtraction, multiplication, division, exponentiation (using the ^ symbol), and a few basic functions like sqrt. It supports grouping using (...), and it gets the operator precedence and associativity rules correct.

public static double eval(final String str) {
    return new Object() {
        int pos = -1, ch;

        void nextChar() {
            ch = (++pos < str.length()) ? str.charAt(pos) : -1;
        }

        boolean eat(int charToEat) {
            while (ch == ' ') nextChar();
            if (ch == charToEat) {
                nextChar();
                return true;
            }
            return false;
        }

        double parse() {
            nextChar();
            double x = parseExpression();
            if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
            return x;
        }

        // Grammar:
        // expression = term | expression `+` term | expression `-` term
        // term = factor | term `*` factor | term `/` factor
        // factor = `+` factor | `-` factor | `(` expression `)`
        //        | number | functionName factor | factor `^` factor

        double parseExpression() {
            double x = parseTerm();
            for (;;) {
                if      (eat('+')) x += parseTerm(); // addition
                else if (eat('-')) x -= parseTerm(); // subtraction
                else return x;
            }
        }

        double parseTerm() {
            double x = parseFactor();
            for (;;) {
                if      (eat('*')) x *= parseFactor(); // multiplication
                else if (eat('/')) x /= parseFactor(); // division
                else return x;
            }
        }

        double parseFactor() {
            if (eat('+')) return parseFactor(); // unary plus
            if (eat('-')) return -parseFactor(); // unary minus

            double x;
            int startPos = this.pos;
            if (eat('(')) { // parentheses
                x = parseExpression();
                eat(')');
            } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
                while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
                x = Double.parseDouble(str.substring(startPos, this.pos));
            } else if (ch >= 'a' && ch <= 'z') { // functions
                while (ch >= 'a' && ch <= 'z') nextChar();
                String func = str.substring(startPos, this.pos);
                x = parseFactor();
                if (func.equals("sqrt")) x = Math.sqrt(x);
                else if (func.equals("sin")) x = Math.sin(Math.toRadians(x));
                else if (func.equals("cos")) x = Math.cos(Math.toRadians(x));
                else if (func.equals("tan")) x = Math.tan(Math.toRadians(x));
                else throw new RuntimeException("Unknown function: " + func);
            } else {
                throw new RuntimeException("Unexpected: " + (char)ch);
            }

            if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation

            return x;
        }
    }.parse();
}

Example:

System.out.println(eval("((4 - 2^3 + 1) * -sqrt(3*3+4*4)) / 2"));

Output: 7.5 (which is correct)


The parser is a recursive descent parser, so internally uses separate parse methods for each level of operator precedence in its grammar. I kept it short so it's easy to modify, but here are some ideas you might want to expand it with:

  • Variables:

    The bit of the parser that reads the names for functions can easily be changed to handle custom variables too, by looking up names in a variable table passed to the eval method, such as a Map<String,Double> variables.

  • Separate compilation and evaluation:

    What if, having added support for variables, you wanted to evaluate the same expression millions of times with changed variables, without parsing it every time? It's possible. First define an interface to use to evaluate the precompiled expression:

    @FunctionalInterface
    interface Expression {
        double eval();
    }
    

    Now change all the methods that return doubles, so instead they return an instance of that interface. Java 8's lambda syntax works great for this. Example of one of the changed methods:

    Expression parseExpression() {
        Expression x = parseTerm();
        for (;;) {
            if (eat('+')) { // addition
                Expression a = x, b = parseTerm();
                x = (() -> a.eval() + b.eval());
            } else if (eat('-')) { // subtraction
                Expression a = x, b = parseTerm();
                x = (() -> a.eval() - b.eval());
            } else {
                return x;
            }
        }
    }
    

    That builds a recursive tree of Expression objects representing the compiled expression (an abstract syntax tree). Then you can compile it once and evaluate it repeatedly with different values:

    public static void main(String[] args) {
        Map<String,Double> variables = new HashMap<>();
        Expression exp = parse("x^2 - x + 2", variables);
        for (double x = -20; x <= +20; x++) {
            variables.put("x", x);
            System.out.println(x + " => " + exp.eval());
        }
    }
    
  • Different datatypes:

    Instead of double, you could change the evaluator to use something more powerful like BigDecimal, or a class that implements complex numbers, or rational numbers (fractions). You could even use Object, allowing some mix of datatypes in expressions, just like a real programming language. :)


All code in this answer released to the public domain. Have fun!

How to send post request to the below post method using postman rest client

I had same issue . I passed my data as key->value in "Body" section by choosing "form-data" option and it worked fine.

Computing cross-correlation function?

To cross-correlate 1d arrays use numpy.correlate.

For 2d arrays, use scipy.signal.correlate2d.

There is also scipy.stsci.convolve.correlate2d.

There is also matplotlib.pyplot.xcorr which is based on numpy.correlate.

See this post on the SciPy mailing list for some links to different implementations.

Edit: @user333700 added a link to the SciPy ticket for this issue in a comment.

How to upgrade Python version to 3.7?

On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7

Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa

See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)

If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:

tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install        <-- sudo is required.

This might take a while

What is SOA "in plain english"?

I would suggest you read articles by Thomas Erl and Roger Sessions, this will give you a firm handle on what SOA is all about. These are also good resources, look at the SOA explained for your boss one for a layman explanation

Building a SOA

SOA Design Pattern

Achieving integrity in a SOA

Why your SOA should be like a VW Beetle

SOA explained for your boss

WCF Service Performance

Does --disable-web-security Work In Chrome Anymore?

If you want to automate this: Kill chrome from task Manager First. In Windows - Right Click (or Shift+right click, in-case of taskbar) on Chrome Icon. Select Properties. In "Target" text-box, add --disable-web-security flag.

So text in text-box should look like

C:\Users\njadhav\AppData\Local\Google\Chrome SxS\Application\chrome.exe" --disable-web-security

Click Ok and launch chrome.

Execute a shell script in current shell with sudo permission

Even the first answer is absolutely brilliant, you probably want to only run script under sudo.

You have to specify the absolute path like:

sudo /home/user/example.sh
sudo ~/example.sh

(both are working)

THIS WONT WORK!

sudo /bin/sh example.sh
sudo example.sh

It will always return

sudo: bin/sh: command not found
sudo: example.sh: command not found

pip3: command not found but python3-pip is already installed

You can make symbolic link to you pip3:

sudo ln -s $(which pip3) /usr/bin/pip3

It helps me in RHEL 7.6

Calculating the SUM of (Quantity*Price) from 2 different tables

Use:

  SELECT oi.orderid,
         SUM(oi.quantity * p.price) AS grand_total,
    FROM ORDERITEM oi
    JOIN PRODUCT p ON p.id = oi.productid
   WHERE oi.orderid = @OrderId
GROUP BY oi.orderid

Mind that if either oi.quantity or p.price is null, the SUM will return NULL.

Zoom to fit all markers in Mapbox or Leaflet

The best way is to use the next code

var group = new L.featureGroup([marker1, marker2, marker3]);

map.fitBounds(group.getBounds());

click() event is calling twice in jquery

I had the same problem, but you can try changing this code

$("#link_button")
.button()
.click(function () {
   $("#attachmentForm").slideToggle("fast");
});

to this:

$("#link_button").button();
$("#link_button").unbind("click").click(function () {
   $("#attachmentForm").slideToggle("fast");
});

For me, this code solved the problem. But take care not to accidentally include your script twice in your HTML page. I think that if you are doing these two things correctly, your code will work correctly. Thanks

IF... OR IF... in a windows batch file

There is no IF <arg> OR or ELIF or ELSE IF in Batch, however...

Try nesting the other IF's inside the ELSE of the previous IF.

IF <arg> (
    ....
) ELSE (
    IF <arg> (
        ......
    ) ELSE (
        IF <arg> (
            ....
        ) ELSE (
    )
)

Getting char from string at specified index

char = split_string_to_char(text)(index)

------

Function split_string_to_char(text) As String()

   Dim chars() As String
   For char_count = 1 To Len(text)
      ReDim Preserve chars(char_count - 1)
      chars(char_count - 1) = Mid(text, char_count, 1)
   Next
   split_string_to_char = chars
End Function

How to insert a string which contains an "&"

The correct syntax is

set def off;
insert into tablename values( 'J&J');

How to decrypt Hash Password in Laravel

For compare hashed password with the plain text password string you can use the PHP password_verify

if(password_verify('1234567', $crypt_password_string)) {
    // in case if "$crypt_password_string" actually hides "1234567"
}

Run a php app using tomcat?

Yes it is Possible Will Den. we can run PHP code in tomcat server using it's own port number localhost:8080

here I'm writing some step which is so much useful for you.

How to install or run PHP on Tomcat 6 in windows

  1. download and unzip PHP 5 to a directory, c:\php-5.2.6-Win32 - php-5.2.9-2-Win32.zip Download

  2. download PECL 5.2.5 Win32 binaries - PECL 5.2.5 Win32 Download

  3. rename php.ini-dist to php.ini in c:\php-5.2.6-Win32

  4. Uncomment or add the line (remove semi-colon at the beginning) in php.ini: ;extension=php_java.dll

  5. copy php5servlet.dll from PECL 5.2.5 to c:\php-5.2.6-Win32

  6. copy php_java.dll from PECL 5.2.5 to c:\php-5.2.6-Win32\ext

  7. copy php_java.jar from PECL 5.2.5 to tomcat\lib

  8. create a directory named "php" (or what ever u like) in tomcat\webapps directory

  9. copy phpsrvlt.jar from PECL 5.2.5 to tomcat\webapps\php\WEB-INF\lib

  10. Unjar or unzip phpsrvlt.jar for unzip use winrar or winzip for unjar use : jar xfv phpsrvlt.jar

  11. change both net\php\reflect.properties and net\php\servlet.properties to library=php5servlet

  12. Recreate the jar file -> jar cvf php5srvlt.jar net/php/. PS: if the jar file doesnt run you have to add the Path to system variables for me I added C:\Program Files\Java\jdk1.6.0\bin; to System variables/Path

  13. create web.xml in tomcat\webapps\php\WEB-INF with this content:

    <web-app version="2.4" 
      xmlns="http://java.sun.com/xml/ns/j2ee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">
      <servlet>
        <servlet-name>php</servlet-name>
        <servlet-class>net.php.servlet</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>php-formatter</servlet-name>
        <servlet-class>net.php.formatter</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>php</servlet-name>
        <url-pattern>*.php</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>php-formatter</servlet-name>
        <url-pattern>*.phps</url-pattern>
      </servlet-mapping>
    </web-app>
    
  14. Add PHP path( c:\php-5.2.6-Win32) to your System or User Path in Windows enironment (Hint: Right-click and select Properties from My Computer

  15. create test.php for testing under tomcat\webapps\php like

  16. Restart tomcat

  17. browse localhost:8080/php/test.php

What is best tool to compare two SQL Server databases (schema and data)?

SQL Admin Studio from http://www.simego.com/Products/SQL-Admin-Studio is now free, lets you manage your SQL Database, SQL Compare and Synchronise, Data Compare and Synchronise and much more. Also supports SQL Azure and some MySQL Support too.

[UPDATE: Yes I am the Author of the above program, as it's now Free I just wanted to Share it with the community]

Serialize an object to string

Serialize and Deserialize (XML/JSON):

public static T XmlDeserialize<T>(this string toDeserialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using(StringReader textReader = new StringReader(toDeserialize))
    {      
        return (T)xmlSerializer.Deserialize(textReader);
    }
}

public static string XmlSerialize<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using(StringWriter textWriter = new StringWriter())
    {
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

public static T JsonDeserialize<T>(this string toDeserialize)
{
    return JsonConvert.DeserializeObject<T>(toDeserialize);
}

public static string JsonSerialize<T>(this T toSerialize)
{
    return JsonConvert.SerializeObject(toSerialize);
}

WebDriver - wait for element using Java

We're having a lot of race conditions with elementToBeClickable. See https://github.com/angular/protractor/issues/2313. Something along these lines worked reasonably well even if a little brute force

Awaitility.await()
        .atMost(timeout)
        .ignoreException(NoSuchElementException.class)
        .ignoreExceptionsMatching(
            Matchers.allOf(
                Matchers.instanceOf(WebDriverException.class),
                Matchers.hasProperty(
                    "message",
                    Matchers.containsString("is not clickable at point")
                )
            )
        ).until(
            () -> {
                this.driver.findElement(locator).click();
                return true;
            },
            Matchers.is(true)
        );

Finding all positions of substring in a larger string in C#

Why don't you use the built in RegEx class:

public static IEnumerable<int> GetAllIndexes(this string source, string matchString)
{
   matchString = Regex.Escape(matchString);
   foreach (Match match in Regex.Matches(source, matchString))
   {
      yield return match.Index;
   }
}

If you do need to reuse the expression then compile it and cache it somewhere. Change the matchString param to a Regex matchExpression in another overload for the reuse case.

PyLint "Unable to import" error - how to set PYTHONPATH?

1) sys.path is a list.

2) The problem is sometimes the sys.path is not your virtualenv.path and you want to use pylint in your virtualenv

3) So like said, use init-hook (pay attention in ' and " the parse of pylint is strict)

[Master]
init-hook='sys.path = ["/path/myapps/bin/", "/path/to/myapps/lib/python3.3/site-packages/", ... many paths here])'

or

[Master]
init-hook='sys.path = list(); sys.path.append("/path/to/foo")'

.. and

pylint --rcfile /path/to/pylintrc /path/to/module.py

How to set the size of button in HTML

This cannot be done with pure HTML/JS, you will need CSS

CSS:

button {
     width: 100%;
     height: 100%;
}

Substitute 100% with required size

This can be done in many ways

Disable Laravel's Eloquent timestamps

You either have to declare public $timestamps = false; in every model, or create a BaseModel, define it there, and have all your models extend it instead of eloquent. Just bare in mind pivot tables MUST have timestamps if you're using Eloquent.

Update: Note that timestamps are no longer REQUIRED in pivot tables after Laravel v3.

Update: You can also disable timestamps by removing $table->timestamps() from your migration.

Where does Hive store files in HDFS?

If you look at the hive-site.xml file you will see something like this

<property>
   <name>hive.metastore.warehouse.dir</name>
   <value>/usr/hive/warehouse </value>
   <description>location of the warehouse directory</description>
 </property>

/usr/hive/warehouse is the default location for all managed tables. External tables may be stored at a different location.

describe formatted <table_name> is the hive shell command which can be use more generally to find the location of data pertaining to a hive table.

Set a cookie to never expire

All cookies expire as per the cookie specification, so this is not a PHP limitation.

Use a far future date. For example, set a cookie that expires in ten years:

setcookie(
  "CookieName",
  "CookieValue",
  time() + (10 * 365 * 24 * 60 * 60)
);

Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.

Vertical divider doesn't work in Bootstrap 3

I find using the pipe character with some top and bottom padding works well. Using a div with a border will require more CSS to vertically align it and get the horizontal spacing even with the other elements.

CSS

.divider-vertical {
    padding-top: 14px;
    padding-bottom: 14px;
}

HTML

<ul class="nav navbar-nav">
    <li class="active"><a href="#">Home</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Faq</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">News</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Contact</a></li>
</ul>

Encoding as Base64 in Java

I tried with the following code snippet. It worked well. :-)

com.sun.org.apache.xml.internal.security.utils.Base64.encode("The string to encode goes here");

Testing Spring's @RequestBody using Spring MockMVC

The issue is that you are serializing your bean with a custom Gson object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper (within MappingJackson2HttpMessageConverter).

If you open up your server logs, you should see something like

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source: java.io.StringReader@baea1ed; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])

among other stack traces.

One solution is to set your Gson date format to one of the above (in the stacktrace).

The alternative is to register your own MappingJackson2HttpMessageConverter by configuring your own ObjectMapper to have the same date format as your Gson.

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

How to dynamically add a class to manual class names?

You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.

// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], { 
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />

Classpath including JAR within a JAR

You do NOT want to use those "explode JAR contents" solutions. They definitely make it harder to see stuff (since everything is exploded at the same level). Furthermore, there could be naming conflicts (should not happen if people use proper packages, but you cannot always control this).

The feature that you want is one of the top 25 Sun RFEs: RFE 4648386, which Sun, in their infinite wisdom, has designated as being of low priority. We can only hope that Sun wakes up...

In the meanwhile, the best solution that I have come across (which I wish that Sun would copy in the JDK) is to use the custom class loader JarClassLoader.

Measuring the distance between two coordinates in PHP

Quite old question, but for those interested in a PHP code that returns the same results as Google Maps, the following does the job:

/**
 * Computes the distance between two coordinates.
 *
 * Implementation based on reverse engineering of
 * <code>google.maps.geometry.spherical.computeDistanceBetween()</code>.
 *
 * @param float $lat1 Latitude from the first point.
 * @param float $lng1 Longitude from the first point.
 * @param float $lat2 Latitude from the second point.
 * @param float $lng2 Longitude from the second point.
 * @param float $radius (optional) Radius in meters.
 *
 * @return float Distance in meters.
 */
function computeDistance($lat1, $lng1, $lat2, $lng2, $radius = 6378137)
{
    static $x = M_PI / 180;
    $lat1 *= $x; $lng1 *= $x;
    $lat2 *= $x; $lng2 *= $x;
    $distance = 2 * asin(sqrt(pow(sin(($lat1 - $lat2) / 2), 2) + cos($lat1) * cos($lat2) * pow(sin(($lng1 - $lng2) / 2), 2)));

    return $distance * $radius;
}

I've tested with various coordinates and it works perfectly.

I think it should be faster then some alternatives too. But didn't test that.

Hint: Google Maps uses 6378137 as Earth radius. So using it with other algorithms might work as well.

How do I make a Docker container start automatically on system boot?

You can run a container that restart always by:

$ docker run -dit --restart unless-stopped <image name OR image hash>

If you want to change a running container's configs, you should update it by:

$ docker update --restart=<options> <container ID OR name>

And if you want to see current policy of the container, run the following command before above at the first place:

docker inspect gateway | grep RestartPolicy -A 3

After all, Not to forget to make installed docker daemon enable at system boot by:

$ systemctl enable docker

To see a full list of restart policies, see: Restart Policies

Converting byte array to string in javascript

Simply apply your byte array to String.fromCharCode. For example

String.fromCharCode.apply(null, [102, 111, 111]) equals 'foo'.

Caveat: works for arrays shorter than 65535. MDN docs here.

How can I check if a Perl array contains a particular value?

my @badparams = (1,2,5,7,'a','zzz');

my $badparams = join('|',@badparams);   # '|' or any other character not present in params

foreach my $par (4,5,6,7,'a','z','zzz')
{
    if ($badparams =~ /\b$par\b/)
    {
        print "$par is present\n";
    }
    else
    {
        print "$par is not present\n";
    }
}

You may want to check for numerical leading spaces consistancy

Relative path in HTML

The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.

If the URL of your website is: http://www.example.com/mywebsite/ then starting at the root level starts above the "mywebsite" folder path.

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

  1. Download jar file containing the JavaDocs.
  2. Open the Build Path page of the project (right click, properties, Java build path).
  3. Open the Libraries tab.
  4. Expand the node of the library in question (JavaFX).
  5. Select JavaDoc location and click edit.
  6. Enter the location to the file which contains the Javadoc (the one you just downloaded).

bash: shortest way to get n-th column of output

Note, that file path does not have to be in second column of svn st output. For example if you modify file, and modify it's property, it will be 3rd column.

See possible output examples in:

svn help st

Example output:

 M     wc/bar.c
A  +   wc/qax.c

I suggest to cut first 8 characters by:

svn st | cut -c8- | while read FILE; do echo whatever with "$FILE"; done

If you want to be 100% sure, and deal with fancy filenames with white space at the end for example, you need to parse xml output:

svn st --xml | grep -o 'path=".*"' | sed 's/^path="//; s/"$//'

Of course you may want to use some real XML parser instead of grep/sed.

Make child div stretch across width of page

Yes you can, set the position: relative for the container and position: absolute for the help_panel

Java - How to find the redirected url of a url?

I'd actually suggest using a solid open-source library as an http client. If you take a look at http client by ASF you'll find life a lot easier. It is an easy-to-use,scalable and robust client for http.

How do I get Month and Date of JavaScript in 2 digit format?

If it might spare some time I was looking to get:

YYYYMMDD

for today, and got along with:

const dateDocumentID = new Date()
  .toISOString()
  .substr(0, 10)
  .replace(/-/g, '');

Sort Pandas Dataframe by Date

@JAB's answer is fast and concise. But it changes the DataFrame you are trying to sort, which you may or may not want.

(Note: You almost certainly will want it, because your date columns should be dates, not strings!)

In the unlikely event that you don't want to change the dates into dates, you can also do it a different way.

First, get the index from your sorted Date column:

In [25]: pd.to_datetime(df.Date).order().index
Out[25]: Int64Index([0, 2, 1], dtype='int64')

Then use it to index your original DataFrame, leaving it untouched:

In [26]: df.ix[pd.to_datetime(df.Date).order().index]
Out[26]: 
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

Magic!

Note: for Pandas versions 0.20.0 and later, use loc instead of ix, which is now deprecated.

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

To add ANDROID_HOME value permanently,

gedit ~/.bashrc

and add the following lines

export ANDROID_HOME=/root/Android/Sdk
PATH=$PATH:$ANDROID_HOME/tools

Save the file and you need not update ANDROID_HOME value everytime.

Javascript loading CSV file into an array

I highly recommend looking into this plugin:

http://github.com/evanplaice/jquery-csv/

I used this for a project handling large CSV files and it handles parsing a CSV into an array quite well. You can use this to call a local file that you specify in your code, also, so you are not dependent on a file upload.

Once you include the plugin above, you can essentially parse the CSV using the following:

$.ajax({
    url: "pathto/filename.csv",
    async: false,
    success: function (csvd) {
        data = $.csv.toArrays(csvd);
    },
    dataType: "text",
    complete: function () {
        // call a function on complete 
    }
});

Everything will then live in the array data for you to manipulate as you need. I can provide further examples for handling the array data if you need.

There are a lot of great examples available on the plugin page to do a variety of things, too.

IntelliJ does not show project folders

I had the problem after an upgrade from intellij 15 (v143) to 2016.3 (v163). I also had an intermittent error on startup about a "Load error: undefined path variables" with a cryptic variable name.

After countless attempts at most solutions presented here (reimport the project, invalidate caches & restart, checks of project structure and paths...), the only thing that worked was to completely reinstall Intellij (removing the ~/.idea* ~/.IntellijIdea*) and selecting "No" at the question "would you like to migrate previous settings".

This finally worked.

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

To post JSON, you will need to stringify it. JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

What is the difference between mocking and spying when using Mockito?

Spy can be useful when you want to create unit tests for legacy code.

I have created a runable example here https://www.surasint.com/mockito-with-spy/ , I copy some of it here.

If you have something like this code:

public void transfer(  DepositMoneyService depositMoneyService, WithdrawMoneyService withdrawMoneyService, 
             double amount, String fromAccount, String toAccount){
    withdrawMoneyService.withdraw(fromAccount,amount);
    depositMoneyService.deposit(toAccount,amount);
}

You may don't need spy because you can just mock DepositMoneyService and WithdrawMoneyService.

But with some, legacy code, dependency is in the code like this:

    public void transfer(String fromAccount, String toAccount, double amount){

        this.depositeMoneyService = new DepositMoneyService();
        this.withdrawMoneyService = new WithdrawMoneyService();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }

Yes, you can change to the first code but then API is changed. If this method is being used by many places, you have to change all of them.

Alternative is that you can extract the dependency out like this:

    public void transfer(String fromAccount, String toAccount, double amount){
        this.depositeMoneyService = proxyDepositMoneyServiceCreator();
        this.withdrawMoneyService = proxyWithdrawMoneyServiceCreator();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }
    DepositMoneyService proxyDepositMoneyServiceCreator() {
        return new DepositMoneyService();
    }

    WithdrawMoneyService proxyWithdrawMoneyServiceCreator() {
        return new WithdrawMoneyService();
    }

Then you can use the spy the inject the dependency like this:

DepositMoneyService mockDepositMoneyService = mock(DepositMoneyService.class);
        WithdrawMoneyService mockWithdrawMoneyService = mock(WithdrawMoneyService.class);

    TransferMoneyService target = spy(new TransferMoneyService());

    doReturn(mockDepositMoneyService)
            .when(target).proxyDepositMoneyServiceCreator();

    doReturn(mockWithdrawMoneyService)
            .when(target).proxyWithdrawMoneyServiceCreator();

More detail in the link above.

jQuery autoComplete view all on click?

I can't see an obvious way to do that in the docs, but you try triggering the focus (or click) event on the autocomplete enabled textbox:

$('#myButton').click(function() {
   $('#autocomplete').trigger("focus"); //or "click", at least one should work
});

How to create a library project in Android Studio and an application project that uses the library project

Documentation Way

This is the recommended way as per the advice given in the Android Studio documentation.

Create a library module

Create a new project to make your library in. Click File > New > New Module > Android Library > Next > (choose name) > Finish. Then add whatever classes and resourced you want to your library.

When you build the module an AAR file will be created. You can find it in project-name/module-name/build/outputs/aar/.

Add your library as a dependency

You can add your library as a dependency to another project like this:

  1. Import your library AAR file with File > New Module > Import .JAR/.AAR Package > Next > (choose file location) > Finish. (Don't import the code, otherwise it will be editable in too many places.)
  2. In the settings.gradle file, make sure your library name is there.

    include ':app', ':my-library-module'
    
  3. In the app's build.gradle file, add the compile line to the dependencies section:

    dependencies {
        compile project(":my-library-module")
    }
    
  4. You will be prompted to sync your project with gradle. Do it.

That's it. You should be able to use your library now.

Notes

If you want to make your library easily available to a larger audience, consider using JitPac or JCenter.

How to change the background-color of jumbrotron?

In the HTML file itself, modify the background-color of the jumbotron using the style attribute:
<div class="jumbotron" style="background-color:#CFD8DC;"></div>

twitter bootstrap 3.0 typeahead ajax example

Here is my step by step experience, inspired by typeahead examples, from a Scala/PlayFramework app we are working on.

In a script LearnerNameTypeAhead.coffee (convertible of course to JS) I have:

$ ->
  learners = new Bloodhound(
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value")
    queryTokenizer: Bloodhound.tokenizers.whitespace
    remote: "/learner/namelike?nameLikeStr=%QUERY"
  )
  learners.initialize()
  $("#firstName").typeahead 
    minLength: 3
    hint: true
    highlight:true
   ,
    name: "learners"
    displayKey: "value"
    source: learners.ttAdapter()

I included the typeahead bundle and my script on the page, and there is a div around my input field as follows:

<script [email protected]("javascripts/typeahead.bundle.js")></script>
<script [email protected]("javascripts/LearnerNameTypeAhead.js") type="text/javascript" ></script>
<div>
  <input name="firstName" id="firstName" class="typeahead" placeholder="First Name" value="@firstName">
</div>

The result is that for each character typed in the input field after the first minLength (3) characters, the page issues a GET request with a URL looking like /learner/namelike?nameLikeStr= plus the currently typed characters. The server code returns a json array of objects containing fields "id" and "value", for example like this:

[ {
    "id": "109",
    "value": "Graham Jones"
  },
  {
    "id": "5833",
    "value": "Hezekiah Jones"
} ]

For play I need something in the routes file:

GET /learner/namelike controllers.Learners.namesLike(nameLikeStr:String)

And finally, I set some of the styling for the dropdown, etc. in a new typeahead.css file which I included in the page's <head> (or accessible .css)

.tt-dropdown-menu {
  width: 252px;
  margin-top: 12px;
  padding: 8px 0;
  background-color: #fff;
  border: 1px solid #ccc;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-border-radius: 8px;
     -moz-border-radius: 8px;
          border-radius: 8px;
  -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
     -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
          box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.typeahead {
  background-color: #fff;
}
.typeahead:focus {
  border: 2px solid #0097cf;
}
.tt-query {
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
     -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
  color: #999
}
.tt-suggestion {
  padding: 3px 20px;
  font-size: 18px;
  line-height: 24px;
}
.tt-suggestion.tt-cursor {
  color: #fff;
  background-color: #0097cf;
}
.tt-suggestion p {
  margin: 0;
}

Java Multiple Inheritance

Ehm, your class can be the subclass for only 1 other, but still, you can have as many interfaces implemented, as you wish.

A Pegasus is in fact a horse (it is a special case of a horse), which is able to fly (which is the "skill" of this special horse). From the other hand, you can say, the Pegasus is a bird, which can walk, and is 4legged - it all depends, how it is easier for you to write the code.

Like in your case you can say:

abstract class Animal {
   private Integer hp = 0; 
   public void eat() { 
      hp++; 
   }
}
interface AirCompatible { 
   public void fly(); 
}
class Bird extends Animal implements AirCompatible { 
   @Override
   public void fly() {  
       //Do something useful
   }
} 
class Horse extends Animal {
   @Override
   public void eat() { 
      hp+=2; 
   }

}
class Pegasus extends Horse implements AirCompatible {
   //now every time when your Pegasus eats, will receive +2 hp  
   @Override
   public void fly() {  
       //Do something useful
   }
}

How to execute Table valued function

You can execute it just as you select a table using SELECT clause. In addition you can provide parameters within parentheses.

Try with below syntax:

SELECT * FROM yourFunctionName(parameter1, parameter2)

document.getelementbyId will return null if element is not defined?

getElementById is defined by DOM Level 1 HTML to return null in the case no element is matched.

!==null is the most explicit form of the check, and probably the best, but there is no non-null falsy value that getElementById can return - you can only get null or an always-truthy Element object. So there's no practical difference here between !==null, !=null or the looser if (document.getElementById('xx')).

JavaScript Array splice vs slice

Splice - MDN reference - ECMA-262 spec

Syntax
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Parameters

  • start: required. Initial index.
    If start is negative it is treated as "Math.max((array.length + start), 0)" as per spec (example provided below) effectively from the end of array.
  • deleteCount: optional. Number of elements to be removed (all from start if not provided).
  • item1, item2, ...: optional. Elements to be added to the array from start index.

Returns: An array with deleted elements (empty array if none removed)

Mutate original array: Yes

Examples:

_x000D_
_x000D_
const array = [1,2,3,4,5];

// Remove first element
console.log('Elements deleted:', array.splice(0, 1), 'mutated array:', array);
// Elements deleted: [ 1 ] mutated array: [ 2, 3, 4, 5 ]

// array = [ 2, 3, 4, 5]
// Remove last element (start -> array.length+start = 3)
console.log('Elements deleted:', array.splice(-1, 1), 'mutated array:', array);
// Elements deleted: [ 5 ] mutated array: [ 2, 3, 4 ]
_x000D_
_x000D_
_x000D_

More examples in MDN Splice examples


Slice - MDN reference - ECMA-262 spec

Syntax
array.slice([begin[, end]])
Parameters

  • begin: optional. Initial index (default 0).
    If begin is negative it is treated as "Math.max((array.length + begin), 0)" as per spec (example provided below) effectively from the end of array.
  • end: optional. Last index for extraction but not including (default array.length). If end is negative it is treated as "Math.max((array.length + begin),0)" as per spec (example provided below) effectively from the end of array.

Returns: An array containing the extracted elements.

Mutate original: No

Examples:

_x000D_
_x000D_
const array = [1,2,3,4,5];

// Extract first element
console.log('Elements extracted:', array.slice(0, 1), 'array:', array);
// Elements extracted: [ 1 ] array: [ 1, 2, 3, 4, 5 ]

// Extract last element (start -> array.length+start = 4)
console.log('Elements extracted:', array.slice(-1), 'array:', array);
// Elements extracted: [ 5 ] array: [ 1, 2, 3, 4, 5 ]
_x000D_
_x000D_
_x000D_

More examples in MDN Slice examples

Performance comparison

Don't take this as absolute truth as depending on each scenario one might be performant than the other.
Performance test

Testing two JSON objects for equality ignoring child order in Java

Using GSON

JsonParser parser = new JsonParser();
JsonElement o1 = parser.parse("{a : {a : 2}, b : 2}");
JsonElement o2 = parser.parse("{b : 2, a : {a : 2}}");
assertEquals(o1, o2);

Edit: Since GSON v2.8.6 the instance method JsonParser.parse is deprecated. You have to use the static method JsonParser.parseString:

JsonElement o1 = JsonParser.parseString("{a : {a : 2}, b : 2}");
JsonElement o2 = JsonParser.parseString("{b : 2, a : {a : 2}}");
assertEquals(o1, o2);

What is the difference between an abstract function and a virtual function?

An abstract function has no implemention and it can only be declared on an abstract class. This forces the derived class to provide an implementation.

A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class.

So for example:

public abstract class myBase
{
    //If you derive from this class you must implement this method. notice we have no method body here either
    public abstract void YouMustImplement();

    //If you derive from this class you can change the behavior but are not required to
    public virtual void YouCanOverride()
    { 
    }
}

public class MyBase
{
   //This will not compile because you cannot have an abstract method in a non-abstract class
    public abstract void YouMustImplement();
}

How can I decrypt MySQL passwords

You can't decrypt password in mysql, because password is hashed by using md5 hash algorithm, which is not an encoding algorithm.

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

The ideal situation for resolving conflicts is when you know ahead of time which way you want to resolve them and can pass the -Xours or -Xtheirs recursive merge strategy options. Outside of this I can see three scenarious:

  1. You want to just keep a single version of the file (this should probably only be used on unmergeable binary files, since otherwise conflicted and non-conflicted files may get out of sync with each other).
  2. You want to simply decide all of the conflicts in a particular direction.
  3. You need to resolve some conflicts manually and then resolve all of the rest in a particular direction.

To address these three scenarios you can add the following lines to your .gitconfig file (or equivalent):

[merge]
  conflictstyle = diff3
[mergetool.getours]
  cmd = git-checkout --ours ${MERGED}
  trustExitCode = true
[mergetool.mergeours]
  cmd = git-merge-file --ours ${LOCAL} ${BASE} ${REMOTE} -p > ${MERGED}
  trustExitCode = true
[mergetool.keepours]
  cmd = sed -i '' -e '/^<<<<<<</d' -e '/^|||||||/,/^>>>>>>>/d' ${MERGED}
  trustExitCode = true
[mergetool.gettheirs]
  cmd = git-checkout --theirs ${MERGED}
  trustExitCode = true
[mergetool.mergetheirs]
  cmd = git-merge-file --theirs ${LOCAL} ${BASE} ${REMOTE} -p > ${MERGED}
  trustExitCode = true
[mergetool.keeptheirs]
  cmd = sed -i '' -e '/^<<<<<<</,/^=======/d' -e '/^>>>>>>>/d' ${MERGED}
  trustExitCode = true

The get(ours|theirs) tool just keeps the respective version of the file and throws away all of the changes from the other version (so no merging occurs).

The merge(ours|theirs) tool re-does the three way merge from the local, base, and remote versions of the file, choosing to resolve conflicts in the given direction. This has some caveats, specifically: it ignores the diff options that were passed to the merge command (such as algorithm and whitespace handling); does the merge cleanly from the original files (so any manual changes to the file are discarded, which could be good or bad); and has the advantage that it cannot be confused by diff markers that are supposed to be in the file.

The keep(ours|theirs) tool simply edits out the diff markers and enclosed sections, detecting them by regular expression. This has the advantage that it preserves the diff options from the merge command and allows you to resolve some conflicts by hand and then automatically resolve the rest. It has the disadvantage that if there are other conflict markers in the file it could get confused.

These are all used by running git mergetool -t (get|merge|keep)(ours|theirs) [<filename>] where if <filename> is not supplied it processes all conflicted files.

Generally speaking, assuming you know there are no diff markers to confuse the regular expression, the keep* variants of the command are the most powerful. If you leave the mergetool.keepBackup option unset or true then after the merge you can diff the *.orig file against the result of the merge to check that it makes sense. As an example, I run the following after the mergetool just to inspect the changes before committing:

for f in `find . -name '*.orig'`; do vimdiff $f ${f%.orig}; done

Note: If the merge.conflictstyle is not diff3 then the /^|||||||/ pattern in the sed rule needs to be /^=======/ instead.

Send Email to multiple Recipients with MailMessage?

I've tested this using the following powershell script and using (,) between the addresses. It worked for me!

$EmailFrom = "<[email protected]>";
$EmailPassword = "<password>";
$EmailTo = "<[email protected]>,<[email protected]>";
$SMTPServer = "<smtp.server.com>";
$SMTPPort = <port>;
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,$SMTPPort);
$SMTPClient.EnableSsl = $true;
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $EmailPassword);
$Subject = "Notification from XYZ";
$Body = "this is a notification from XYZ Notifications..";
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body);

How to compute the similarity between two text documents?

To find sentence similarity with very less dataset and to get high accuracy you can use below python package which is using pre-trained BERT models,

pip install similar-sentences

Getting a list of files in a directory with a glob

Very Simplest Method:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager contentsOfDirectoryAtPath:documentsDirectory 
                                                 error:nil];
//--- Listing file by name sort
NSLog(@"\n File list %@",fileList);

//---- Sorting files by extension    
NSArray *filePathsArray = 
  [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  
                                                      error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF EndsWith '.png'"];
filePathsArray =  [filePathsArray filteredArrayUsingPredicate:predicate];
NSLog(@"\n\n Sorted files by extension %@",filePathsArray);

Java double comparison epsilon

Cents? If you're calculationg money values you really shouldn't use float values. Money is actually countable values. The cents or pennys etc. could be considered the two (or whatever) least significant digits of an integer. You could store, and calculate money values as integers and divide by 100 (e.g. place dot or comma two before the two last digits). Using float's can lead to strange rounding errors...

Anyway, if your epsilon is supposed to define the accuracy, it looks a bit too small (too accurate)...

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

Here's a start.. Open to suggestions/improvements.

Server

public class ChatHub : Hub
{
    public void SendChatMessage(string who, string message)
    {
        string name = Context.User.Identity.Name;
        Clients.Group(name).addChatMessage(name, message);
        Clients.Group("[email protected]").addChatMessage(name, message);
    }

    public override Task OnConnected()
    {
        string name = Context.User.Identity.Name;
        Groups.Add(Context.ConnectionId, name);

        return base.OnConnected();
    }
}

JavaScript

(Notice how addChatMessage and sendChatMessage are also methods in the server code above)

    $(function () {
    // Declare a proxy to reference the hub.
    var chat = $.connection.chatHub;
    // Create a function that the hub can call to broadcast messages.
    chat.client.addChatMessage = function (who, message) {
        // Html encode display name and message.
        var encodedName = $('<div />').text(who).html();
        var encodedMsg = $('<div />').text(message).html();
        // Add the message to the page.
        $('#chat').append('<li><strong>' + encodedName
            + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
    };

    // Start the connection.
    $.connection.hub.start().done(function () {
        $('#sendmessage').click(function () {
            // Call the Send method on the hub.
            chat.server.sendChatMessage($('#displayname').val(), $('#message').val());
            // Clear text box and reset focus for next comment.
            $('#message').val('').focus();
        });
    });
});

Testing enter image description here

What's the best way to get the last element of an array without deleting it?

As of PHP version 7.3 the functions array_key_first and array_key_last has been introduced.

Since arrays in PHP are not strict array types, i.e. fixed sized collections of fixed sized fields starting at index 0, but dynamically extended associative array, the handling of positions with unknown keys is hard and workarounds do not perform very well. In contrast real arrays would be internally addressed via pointer arithmethics very rapidly and the last index is already known at compile-time by declaration.

At least the problem with the first and last position is solved by builtin functions now since version 7.3. This even works without any warnings on array literals out of the box:

$first = array_key_first( [1, 2, 'A'=>65, 'B'=>66, 3, 4 ] );
$last  = array_key_last ( [1, 2, 'A'=>65, 'B'=>66, 3, 4 ] );

Obviously the last value is:

$array[array_key_last($array)];

How to play or open *.mp3 or *.wav sound file in c++ program?

http://sfml-dev.org/documentation/2.0/classsf_1_1Music.php

SFML does not have mp3 support as another has suggested. What I always do is use Audacity and make all my music into ogg, and leave all my sound effects as wav.

Loading and playing a wav is simple (crude example):

http://www.sfml-dev.org/tutorials/2.0/audio-sounds.php

#include <SFML/Audio.hpp>
...
sf::SoundBuffer buffer;
if (!buffer.loadFromFile("sound.wav")){
    return -1;
}
sf::Sound sound;
sound.setBuffer(buffer);
sound.play();

Streaming an ogg music file is also simple:

#include <SFML/Audio.hpp>
...
sf::Music music;
if (!music.openFromFile("music.ogg"))
    return -1; // error
music.play();

What are "res" and "req" parameters in Express functions?

Request and response.

To understand the req, try out console.log(req);.

How can I remove a character from a string using JavaScript?

var mystring = "crt/r2002_2";
mystring = mystring.replace('/r','/');

will replace /r with / using String.prototype.replace.

Alternatively you could use regex with a global flag (as suggested by Erik Reppen & Sagar Gala, below) to replace all occurrences with

mystring = mystring.replace(/\/r/g, '/');

EDIT: Since everyone's having so much fun here and user1293504 doesn't seem to be coming back any time soon to answer clarifying questions, here's a method to remove the Nth character from a string:

String.prototype.removeCharAt = function (i) {
    var tmp = this.split(''); // convert to an array
    tmp.splice(i - 1 , 1); // remove 1 element from the array (adjusting for non-zero-indexed counts)
    return tmp.join(''); // reconstruct the string
}

console.log("crt/r2002_2".removeCharAt(4));

Since user1293504 used the normal count instead of a zero-indexed count, we've got to remove 1 from the index, if you wish to use this to replicate how charAt works do not subtract 1 from the index on the 3rd line and use tmp.splice(i, 1) instead.

Re-ordering columns in pandas dataframe based on column name

df = df.reindex(sorted(df.columns), axis=1)

This assumes that sorting the column names will give the order you want. If your column names won't sort lexicographically (e.g., if you want column Q10.3 to appear after Q9.1), you'll need to sort differently, but that has nothing to do with pandas.

Format output string, right alignment

Here is another way how you can format using 'f-string' format:

print(
    f"{'Trades:':<15}{cnt:>10}",
    f"\n{'Wins:':<15}{wins:>10}",
    f"\n{'Losses:':<15}{losses:>10}",
    f"\n{'Breakeven:':<15}{evens:>10}",
    f"\n{'Win/Loss Ratio:':<15}{win_r:>10}",
    f"\n{'Mean Win:':<15}{mean_w:>10}",
    f"\n{'Mean Loss:':<15}{mean_l:>10}",
    f"\n{'Mean:':<15}{mean_trd:>10}",
    f"\n{'Std Dev:':<15}{sd:>10}",
    f"\n{'Max Loss:':<15}{max_l:>10}",
    f"\n{'Max Win:':<15}{max_w:>10}",
    f"\n{'Sharpe Ratio:':<15}{sharpe_r:>10}",
)

This will provide the following output:

Trades:              2304
Wins:                1232
Losses:              1035
Breakeven:             37
Win/Loss Ratio:      1.19
Mean Win:           0.381
Mean Loss:         -0.395
Mean:               0.026
Std Dev:             0.56
Max Loss:          -3.406
Max Win:             4.09
Sharpe Ratio:      0.7395

What you are doing here is you are saying that the first column is 15 chars long and it's left justified and second column (values) is 10 chars long and it's right justified.

Stop UIWebView from "bouncing" vertically?

I was annoyed to find out that UIWebView is not a scroll view, so I made a custom subclass to get at the web view's scroll view. This suclass contains a scroll view so you can customize the behavior of your web view. The punchlines of this class are:

@class CustomWebView : UIWebview
...

- (id) initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
// WebViews are subclass of NSObject and not UIScrollView and therefore don't allow customization.
// However, a UIWebView is a UIScrollViewDelegate, so it must CONTAIN a ScrollView somewhere.
// To use a web view like a scroll view, let's traverse the view hierarchy to find the scroll view inside the web view.
for (UIView* v in self.subviews){
    if ([v isKindOfClass:[UIScrollView class]]){
        _scrollView = (UIScrollView*)v; 
        break;
    }
}
return self;

}

Then, when you create a custom web view, you can disable bouncing with:

customWebView.scrollView.bounces = NO; //(or customWebView.scrollView.alwaysBounceVertically = NO)

This is a great general purpose way to make a web view with customizable scrolling behavior. There are just a few things to watch out for:

  • as with any view, you'll also need to override -(id)initWithCoder: if you use it in Interface Builder
  • when you initially create a web view, its content size is always the same as the size of the view's frame. After you scroll the web, the content size represents the size of the actual web contents inside the view. To get around this, I did something hacky - calling -setContentOffset:CGPointMake(0,1)animated:YES to force an unnoticeable change that will set the proper content size of the web view.

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

Check the Namespace.

You might assign System.Web.Webpages.Html.SelectListItem in the Controller, instead of System.Web.Mvc.SelectListItem.

List of Stored Procedures/Functions Mysql Command Line

A variation on Praveenkumar_V's post:

SELECT `name` FROM mysql.proc WHERE db = 'dbname' AND `type` = 'PROCEDURE';
SELECT `name` FROM mysql.proc WHERE db = 'dbname' AND `type` = 'FUNCTION';

..and this because I needed to save time after some housekeeping:

SELECT CONCAT(
     "GRANT EXECUTE ON PROCEDURE `"
    ,`name`
    ,"` TO username@'%'; -- "
    ,`comment`
)
FROM mysql.proc
WHERE db = 'dbname'
AND `type` = 'PROCEDURE';

SELECT CONCAT(
     "GRANT EXECUTE ON FUNCTION `"
    ,`name`
    ,"` TO username@'%'; -- "
    ,`comment`
)
FROM mysql.proc
WHERE db = 'dbname'
AND `type` = 'FUNCTION';

How can I recover the return value of a function passed to multiprocessing.Process?

Thought I'd simplify the simplest examples copied from above, working for me on Py3.6. Simplest is multiprocessing.Pool:

import multiprocessing
import time

def worker(x):
    time.sleep(1)
    return x

pool = multiprocessing.Pool()
print(pool.map(worker, range(10)))

You can set the number of processes in the pool with, e.g., Pool(processes=5). However it defaults to CPU count, so leave it blank for CPU-bound tasks. (I/O-bound tasks often suit threads anyway, as the threads are mostly waiting so can share a CPU core.) Pool also applies chunking optimization.

(Note that the worker method cannot be nested within a method. I initially defined my worker method inside the method that makes the call to pool.map, to keep it all self-contained, but then the processes couldn't import it, and threw "AttributeError: Can't pickle local object outer_method..inner_method". More here. It can be inside a class.)

(Appreciate the original question specified printing 'represent!' rather than time.sleep(), but without it I thought some code was running concurrently when it wasn't.)


Py3's ProcessPoolExecutor is also two lines (.map returns a generator so you need the list()):

from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor() as executor:
    print(list(executor.map(worker, range(10))))

With plain Processes:

import multiprocessing
import time

def worker(x, queue):
    time.sleep(1)
    queue.put(x)

queue = multiprocessing.SimpleQueue()
tasks = range(10)

for task in tasks:
    multiprocessing.Process(target=worker, args=(task, queue,)).start()

for _ in tasks:
    print(queue.get())

Use SimpleQueue if all you need is put and get. The first loop starts all the processes, before the second makes the blocking queue.get calls. I don't think there's any reason to call p.join() too.

Javascript string/integer comparisons

You can use Number() function also since it converts the object argument to a number that represents the object's value.

Eg: javascript:alert( Number("2") > Number("10"))

How to write lists inside a markdown table?

another solution , you can add <br> tag to your table

    |Method name| Behavior |
    |--|--|
    | OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|

enter image description here

How an 'if (A && B)' statement is evaluated?

Yes, it is called Short-circuit Evaluation.

If the validity of the boolean statement can be assured after part of the statement, the rest is not evaluated.

This is very important when some of the statements have side-effects.

Difference between core and processor

An image may say more than a thousand words:

An image may say more than a thousand words

* Figure describing the complexity of a modern multi-processor, multi-core system.

Source:

https://software.intel.com/en-us/articles/intel-performance-counter-monitor-a-better-way-to-measure-cpu-utilization

ant build.xml file doesn't exist

Please install at ubuntu openjdk-7-jdk

sudo apt-get install openjdk-7-jdk

on Windows try find find openjdk

display HTML page after loading complete

you can also go for this.... this will only show the HTML section once javascript has loaded.

<!-- Adds the hidden style and removes it when javascript has loaded -->
<style type="text/css">
    .hideAll  {
        visibility:hidden;
     }
</style>

<script type="text/javascript">
    $(window).load(function () {
        $("#tabs").removeClass("hideAll");
    });
</script>

<div id="tabs" class="hideAll">
   ##Content##
</div>

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

IntelliJ IDEA does not have an action to add imports. Rather it has the ability to do such as you type. If you enable the "Add unambiguous imports on the fly" in Settings > Editor > General > Auto Import, IntelliJ IDEA will add them as you type without the need for any shortcuts. You can also add classes and packages to exclude from auto importing to make a class you use heavily, that clashes with other classes of the same name, unambiguous.

For classes that are ambiguous (or is you prefer to have the "Add unambiguous imports on the fly" option turned off), just type the name of the class (just the name is OK, no need to fully qualify). Use code completion and select the particular class you want:

enter image description here

Notice the fully qualified names to the right. When I select the one I want and hit enter, IDEA will automatically add the import statement. This works the same if I was typing the name of a constructor. For static methods, you can even just keep typing the method you want. In the following screenshot, no "StringUtils" class is imported yet.

enter image description here

Alternatively, type the class name and then hit Alt+Enter or ?+Enter to "Show intention actions and quick-fixes" and then select the import option.

Although I've never used it, I think the Eclipse Code Formatter third party plug-in will do what you want. It lists "emulates Eclipse's imports optimizing" as a feature. See its instructions for more information. But in the end, I suspect you'll find the built in IDEA features work fine once you get use to their paradigm. In general, IDEA uses a "develop by intentions" concept. So rather than interrupting my development work to add an import statement, I just type the class I want (my intention) and IDEA automatically adds the import statement for the class for me.

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

You must add it to entryComponents, as specified in the docs.

@NgModule({
  imports: [
    // ...
  ],
  entryComponents: [
    DialogInvokingComponent, 
    DialogResultExampleDialog
  ],
  declarations: [
    DialogInvokingComponent,   
    DialogResultExampleDialog
  ],
  // ...
})

Here is a full example for an app module file with a dialog defined as entryComponents.

regex string replace

Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:

str = str.replace(/[^-a-z0-9]+/g, "");

Also, if you need to match upper-case letters along with lower case, you should use:

str = str.replace(/[^-a-zA-Z0-9]+/g, "");

Trusting all certificates with okHttp

I made an extension function for Kotlin. Paste it where ever you like and import it while creating OkHttpClient.

fun OkHttpClient.Builder.ignoreAllSSLErrors(): OkHttpClient.Builder {
    val naiveTrustManager = object : X509TrustManager {
        override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
        override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
        override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
    }

    val insecureSocketFactory = SSLContext.getInstance("TLSv1.2").apply {
        val trustAllCerts = arrayOf<TrustManager>(naiveTrustManager)
        init(null, trustAllCerts, SecureRandom())
    }.socketFactory

    sslSocketFactory(insecureSocketFactory, naiveTrustManager)
    hostnameVerifier(HostnameVerifier { _, _ -> true })
    return this
}

use it like this:

val okHttpClient = OkHttpClient.Builder().apply {
    // ...
    if (BuildConfig.DEBUG) //if it is a debug build ignore ssl errors
        ignoreAllSSLErrors()
    //...
}.build()

Google Maps API v3 marker with label

I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.

 .labels {
   color: red;
   background-color: white;
   font-family: "Lucida Grande", "Arial", sans-serif;
   font-size: 10px;
   font-weight: bold;
   text-align: center;
   width: 60px;     
   border: 2px solid black;
   white-space: nowrap;
 }

JavaScript:

 var marker = new MarkerWithLabel({
   position: homeLatLng,
   draggable: true,
   map: map,
   labelContent: "$425K",
   labelAnchor: new google.maps.Point(22, 0),
   labelClass: "labels", // the CSS class for the label
   labelStyle: {opacity: 0.75}
 });

The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50).

In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|

Convert numpy array to tuple

>>> arr = numpy.array(((2,2),(2,-2)))
>>> tuple(map(tuple, arr))
((2, 2), (2, -2))

segmentation fault : 11

What system are you running on? Do you have access to some sort of debugger (gdb, visual studio's debugger, etc.)?

That would give us valuable information, like the line of code where the program crashes... Also, the amount of memory may be prohibitive.

Additionally, may I recommend that you replace the numeric limits by named definitions?

As such:

#define DIM1_SZ 1000
#define DIM2_SZ 1000000

Use those whenever you wish to refer to the array dimension limits. It will help avoid typing errors.

HTML embedded PDF iframe

Iframe

<iframe id="fred" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="PDFData.pdf" frameborder="1" scrolling="auto" height="1100" width="850" ></iframe>

Object

<object data="your_url_to_pdf" type="application/pdf">
  <embed src="your_url_to_pdf" type="application/pdf" />
</object>

How can I use Helvetica Neue Condensed Bold in CSS?

You would have to turn your font into a web font as shown in these SO questions:

However, you may run into copyright issues with this: Not every font allows distribution as a web font. Check your font license to see whether it is allowed.

One of the easiest free and legal ways to use web fonts is Google Web Fonts. However, sadly, they don't have Helvetica Neue in their portfolio.

One of the easiest non-free and legal ways is to purchase the font from a foundry that offers web licenses. I happen to know that the myFonts foundry does this; they even give you a full package with all the JavaScript and CSS pre-prepared. I'm sure other foundries do the same.

Edit: MyFonts have Helvetica neue in Stock, but apparently not with a web license. Check out this list of similar fonts of which some have a web license. Also, Ray Larabie has some nice fonts there, with web licenses, some of them are free.

Use jQuery to navigate away from page

window.location.href = "/somewhere/else";

Do we have router.reload in vue-router?

Resolve the route to a URL and navigate the window with Javascript.

_x000D_
_x000D_
        let r = this.$router.resolve({_x000D_
        name: this.$route.name, // put your route information in_x000D_
        params: this.$route.params, // put your route information in_x000D_
        query: this.$route.query // put your route information in_x000D_
      });_x000D_
      window.location.assign(r.href)
_x000D_
_x000D_
_x000D_

This method replaces the URL and causes the page to do a full request (refresh) rather than relying on Vue.router. $router.go does not work the same for me even though it is theoretically supposed to.