Programs & Examples On #Activexobject

ActiveXObject is the key/initial function to enable and reference an "Automation object" in a Microsoft programming environment or the Internet Explorer browser. It is used when the object should be accessed entirely in script with no visual components. See also the activeX tag.

ActiveXObject in Firefox or Chrome (not IE!)

ActiveX is supported by Chrome.

Chrome check parameters defined in : control panel/Internet option/Security.

Nevertheless,if it's possible to define four different area with IE, Chrome only check "Internet" area.

Javascript - User input through HTML input tag to set a Javascript variable?

Late reading this, but.. The way I read your question, you only need to change two lines of code:

Accept user input, function writes back on screen.

<input type="text" id="userInput"=> give me input</input>
<button onclick="test()">Submit</button>

<!-- add this line for function to write into -->
<p id="demo"></p>   

<script type="text/javascript">
function test(){
    var userInput = document.getElementById("userInput").value;
    document.getElementById("demo").innerHTML = userInput;
}
</script>

Running Facebook application on localhost

In my case the issue revealed to be chrome blocking the CORS request from localhost:4200 to facebook api website. Running Chrome with this setting: "YOUR_PATH_TO_CHROME\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chrome worked like a charm while developing. Even with no localhost added to facebook app's settings.

Disable HttpClient logging

This took me ages to figure out once, you need this:

log4j.logger.httpclient.wire=ERROR

I guess HttpClient uses "httpclient.wire" as its logger name, not "org.apache.commons.httpclient".

Sneaky buggers.

How to define optional methods in Swift protocol?

To define Optional Protocol in swift you should use @objc keyword before Protocol declaration and attribute/method declaration inside that protocol. Below is a sample of Optional Property of a protocol.

@objc protocol Protocol {

  @objc optional var name:String?

}

class MyClass: Protocol {

   // No error

}

Objective-C for Windows

WinObjC? Windows Bridge for iOS (previously known as ‘Project Islandwood’).

Windows Bridge for iOS (also referred to as WinObjC) is a Microsoft open source project that provides an Objective-C development environment for Visual Studio/Windows. In addition, WinObjC provides support for iOS API compatibility. While the final release will happen later this fall (allowing the bridge to take advantage of new tooling capabilities that will ship with the upcoming Visual Studio 2015 Update),

The bridge is available to the open-source community now in its current state. Between now and the fall. The iOS bridge as an open-source project under the MIT license. Given the ambition of the project, making it easy for iOS developers to build and run apps on Windows.

Salmaan Ahmed has an in-depth post on the Windows Bridge for iOS http://blogs.windows.com/buildingapps/2015/08/06/windows-bridge-for-ios-lets-open-this-up/ discussing the compiler, runtime, IDE integration, and what the bridge is and isn’t. Best of all, the source code for the iOS bridge is live on GitHub right now.

The iOS bridge supports both Windows 8.1 and Windows 10 apps built for x86 and x64 processor architectures, and soon we will add compiler optimizations and support for ARM, which adds mobile support.

Get first and last day of month using threeten, LocalDate

If anyone comes looking for first day of previous month and last day of previous month:

public static LocalDate firstDayOfPreviousMonth(LocalDate date) {
        return date.minusMonths(1).withDayOfMonth(1);
    }


public static LocalDate lastDayOfPreviousMonth(LocalDate date) {
        return date.withDayOfMonth(1).minusDays(1);
    }

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

Configuring a working email client from localhost is quite a chore, I have spent hours of frustration attempting it. At last I have found this way to send mails (using WAMP, XAMPP, etc.):

Install hMailServer

Configure this hMailServer setting:

  1. Open hMailServer Administrator.
  2. Click the "Add domain ..." button to create a new domain.
  3. Under the domain text field, enter your computer's localhost IP.
    • Example: 127.0.0.1 is your localhost IP.
  4. Click the "Save" button.
  5. Now go to Settings > Protocols > SMTP and select the "Delivery of Email" tab.
  6. Find the localhost field enter "localhost".
  7. Click the Save button.

Configure your Gmail account, perform following modification:

  1. Go to Settings > Protocols > SMTP and select "Delivery of Email" tab.
  2. Enter "smtp.gmail.com" in the Remote Host name field.
  3. Enter "465" as the port number.
  4. Check "Server requires authentication".
  5. Enter your Google Mail address in the Username field.
  6. Enter your Google Mail password in the password field.
  7. Check mark "Use SSL"
  8. Save all changes.

Optional

If you want to send email from another computer you need to allow deliveries from External to External accounts by following steps:

  1. Go to Settings > Advanced > IP Ranges and double click on "My Computer" which should have IP address of 127.0.0.1
  2. Check the Allow Deliveries from External to External accounts Checkbox.
  3. Save settings using Save button.

Call to a member function fetch_assoc() on boolean in <path>

OK, i just fixed this error.

This happens when there is an error in query or table doesn't exist.

Try debugging the query buy running it directly on phpmyadmin to confirm the validity of the mysql Query

Convert double/float to string

Go and look at the printf() implementation with "%f" in some C library.

How do I use the Simple HTTP client in Android?

You can use this code:

int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.setConnectTimeout(TIME_OUT);
                conection.connect();
                // Getting file length
                int lenghtOfFile = conection.getContentLength();
                // Create a Input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);
                // Output stream to write file
                OutputStream output = new FileOutputStream(
                        "/sdcard/9androidnet.jpg");

                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    // writing data to file
                    output.write(data, 0, count);
                }
                // flushing output
                output.flush();
                // closing streams
                output.close();
                input.close();
            } catch (SocketTimeoutException e) {
                connectionTimeout=true;
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

Editing dictionary values in a foreach loop

You can't modify the collection, not even the values. You could save these cases and remove them later. It would end up like this:

Dictionary<string, int> colStates = new Dictionary<string, int>();
// ...
// Some code to populate colStates dictionary
// ...

int OtherCount = 0;
List<string> notRelevantKeys = new List<string>();

foreach (string key in colStates.Keys)
{

    double Percent = colStates[key] / colStates.Count;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key];
        notRelevantKeys.Add(key);
    }
}

foreach (string key in notRelevantKeys)
{
    colStates[key] = 0;
}

colStates.Add("Other", OtherCount);

Get root password for Google Cloud Engine VM

Figured it out. The VM's in cloud engine don't come with a root password setup by default so you'll first need to change the password using

sudo passwd

If you do everything correctly, it should do something like this:

user@server[~]# sudo passwd
Changing password for user root.
New password: 
Retype new password: 
passwd: all authentication tokens updated successfully.

Sharing link on WhatsApp from mobile website (not application) for Android

This code worked for me.

After clicking on the link, it will ask you to choose the contact to share a message.

_x000D_
_x000D_
<a href="https://api.whatsapp.com/send?text=enter message here">Click here to share on Whatsapp</a>
_x000D_
_x000D_
_x000D_

You can add target="_blank" attribute to open it in a new window or tab.

I don't think the phone number is needed when someone wants to share a particular message or article.

Resizing SVG in html?

I have found it best to add viewBox and preserveAspectRatio attributes to my SVGs. The viewbox should describe the full width and height of the SVG in the form 0 0 w h:

<svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 700 550"></svg>

How to preserve request url with nginx proxy_pass

In case something modifies the location that you're trying to serve, e.g. try_files, this preserves the request for the back-end:

location / {
  proxy_pass http://127.0.0.1:8080$request_uri;
}

How do you set a JavaScript onclick event to a class with css

You can do this by thinking of it a little bit differently. Detect when the body is clicked (document.body.onclick - i.e. anything on the page) and then check if the element clicked (event.srcElement / e.target) has a class and that that class name is the one you want:

document.body.onclick = function(e) {   //when the document body is clicked
    if (window.event) {
        e = event.srcElement;           //assign the element clicked to e (IE 6-8)
    }
    else {
        e = e.target;                   //assign the element clicked to e
    }

    if (e.className && e.className.indexOf('someclass') != -1) {
        //if the element has a class name, and that is 'someclass' then...
        alert('hohoho');
    }
}

Or a more concise version of the above:

document.body.onclick= function(e){
   e=window.event? event.srcElement: e.target;
   if(e.className && e.className.indexOf('someclass')!=-1)alert('hohoho');
}

Foreign Key to multiple tables

You have a few options, all varying in "correctness" and ease of use. As always, the right design depends on your needs.

  • You could simply create two columns in Ticket, OwnedByUserId and OwnedByGroupId, and have nullable Foreign Keys to each table.

  • You could create M:M reference tables enabling both ticket:user and ticket:group relationships. Perhaps in future you will want to allow a single ticket to be owned by multiple users or groups? This design does not enforce that a ticket must be owned by a single entity only.

  • You could create a default group for every user and have tickets simply owned by either a true Group or a User's default Group.

  • Or (my choice) model an entity that acts as a base for both Users and Groups, and have tickets owned by that entity.

Heres a rough example using your posted schema:

create table dbo.PartyType
(   
    PartyTypeId tinyint primary key,
    PartyTypeName varchar(10)
)

insert into dbo.PartyType
    values(1, 'User'), (2, 'Group');


create table dbo.Party
(
    PartyId int identity(1,1) primary key,
    PartyTypeId tinyint references dbo.PartyType(PartyTypeId),
    unique (PartyId, PartyTypeId)
)

CREATE TABLE dbo.[Group]
(
    ID int primary key,
    Name varchar(50) NOT NULL,
    PartyTypeId as cast(2 as tinyint) persisted,
    foreign key (ID, PartyTypeId) references Party(PartyId, PartyTypeID)
)  

CREATE TABLE dbo.[User]
(
    ID int primary key,
    Name varchar(50) NOT NULL,
    PartyTypeId as cast(1 as tinyint) persisted,
    foreign key (ID, PartyTypeId) references Party(PartyID, PartyTypeID)
)

CREATE TABLE dbo.Ticket
(
    ID int primary key,
    [Owner] int NOT NULL references dbo.Party(PartyId),
    [Subject] varchar(50) NULL
)

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

When generating mapping files using doctrine I ran into same issue. I fixed it by removing all comments that some fields had in the database.

When to use which design pattern?

Learn them and slowly you'll be able to reconize and figure out when to use them. Start with something simple as the singleton pattern :)

if you want to create one instance of an object and just ONE. You use the singleton pattern. Let's say you're making a program with an options object. You don't want several of those, that would be silly. Singleton makes sure that there will never be more than one. Singleton pattern is simple, used a lot, and really effective.

Does a `+` in a URL scheme/host/path represent a space?

Thou shalt always encode URLs.

Here is how Ruby encodes your URL:

irb(main):008:0> CGI.escape "a.com/a+b"
=> "a.com%2Fa%2Bb"

Constructor overloading in Java - best practice

While there are no "official guidelines" I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(...). That way you only need to check and handle the parameters once and only once.

public class Simple {

    public Simple() {
        this(null);
    }

    public Simple(Resource r) {
        this(r, null);
    }

    public Simple(Resource r1, Resource r2) {
        // Guard statements, initialize resources or throw exceptions if
        // the resources are wrong
        if (r1 == null) {
            r1 = new Resource();
        }
        if (r2 == null) {
            r2 = new Resource();
        }

        // do whatever with resources
    }

}

From a unit testing standpoint, it'll become easy to test the class since you can put in the resources into it. If the class has many resources (or collaborators as some OO-geeks call it), consider one of these two things:

Make a parameter class

public class SimpleParams {
    Resource r1;
    Resource r2;
    // Imagine there are setters and getters here but I'm too lazy 
    // to write it out. you can make it the parameter class 
    // "immutable" if you don't have setters and only set the 
    // resources through the SimpleParams constructor
}

The constructor in Simple only either needs to split the SimpleParams parameter:

public Simple(SimpleParams params) {
    this(params.getR1(), params.getR2());
}

…or make SimpleParams an attribute:

public Simple(Resource r1, Resource r2) {
    this(new SimpleParams(r1, r2));
}

public Simple(SimpleParams params) {
    this.params = params;
}

Make a factory class

Make a factory class that initializes the resources for you, which is favorable if initializing the resources is a bit difficult:

public interface ResourceFactory {
    public Resource createR1();
    public Resource createR2();
}

The constructor is then done in the same manner as with the parameter class:

public Simple(ResourceFactory factory) {
    this(factory.createR1(), factory.createR2());
} 

Make a combination of both

Yeah... you can mix and match both ways depending on what is easier for you at the time. Parameter classes and simple factory classes are pretty much the same thing considering the Simple class that they're used the same way.

How do I get the total number of unique pairs of a set in the database?

TLDR; The formula is n(n-1)/2 where n is the number of items in the set.

Explanation:

To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA), you can calculate the summation of 1 + 2 + ... + (n-1) where n is the number of items in the set.

The reasoning is as follows, say you have 4 items:

A
B
C
D

The number of items that can be paired with A is 3, or n-1:

AB
AC
AD

It follows that the number of items that can be paired with B is n-2 (because B has already been paired with A):

BC
BD

and so on...

(n-1) + (n-2) + ... + (n-(n-1))

which is the same as

1 + 2 + ... + (n-1)

or

n(n-1)/2

Convert date to another timezone in JavaScript

quick and dirty manual hour changer and return:

return new Date(new Date().setHours(new Date().getHours()+3)).getHours()

AngularJS does not send hidden field value

Just in case someone still struggles with this, I had similar problem when trying to keep track of user session/userid on multipage form

Ive fixed that by adding

.when("/q2/:uid" in the routing:

    .when("/q2/:uid", {
        templateUrl: "partials/q2.html",
        controller: 'formController',
        paramExample: uid
    })

And added this as a hidden field to pass params between webform pages

<< input type="hidden" required ng-model="formData.userid" ng-init="formData.userid=uid" />

Im new to Angular so not sure its the best possible solution but it seems to work ok for me now

In angular $http service, How can I catch the "status" of error?

Since $http.get returns a 'promise' with the extra convenience methods success and error (which just wrap the result of then) you should be able to use (regardless of your Angular version):

$http.get('/someUrl')
    .then(function success(response) {
        console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
    }, function error(response) {
        console.log('failed', response); // supposed to have: data, status, headers, config, statusText
    })

Not strictly an answer to the question, but if you're getting bitten by the "my version of Angular is different than the docs" issue you can always dump all of the arguments, even if you don't know the appropriate method signature:

$http.get('/someUrl')
  .success(function(data, foo, bar) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  })
  .error(function(baz, foo, bar, idontknow) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  });

Then, based on whatever you find, you can 'fix' the function arguments to match.

Switch to another branch without changing the workspace files

Edit: I just noticed that you said you had already created some commits. In that case, use git merge --squash to make a single commit:

git checkout cleanchanges
git merge --squash master
git commit -m "nice commit comment for all my changes"

(Edit: The following answer applies if you have uncommitted changes.)

Just switch branches with git checkout cleanchanges. If the branches refer to the same ref, then all your uncommitted changes will be preserved in your working directory when you switch.

The only time you would have a conflict is if some file in the repository is different between origin/master and cleanchanges. If you just created the branch, then no problem.

As always, if you're at all concerned about losing work, make a backup copy first. Git is designed to not throw away work without asking you first.

HTTP Error 404 when running Tomcat from Eclipse

Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.34\webapps, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like your-eclipse-workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or .../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

How to get label text value form a html page?

You can use textContent attribute to retrieve data from a label.

 <script>
       var datas = document.getElementById("excel-data-div").textContent;
    </script>


<label id="excel-data-div" style="display: none;">
     Sample text
</label>

Merge some list items in a Python List

my telepathic abilities are not particularly great, but here is what I think you want:

def merge(list_of_strings, indices):
    list_of_strings[indices[0]] = ''.join(list_of_strings[i] for i in indices)
    list_of_strings = [s for i, s in enumerate(list_of_strings) if i not in indices[1:]]
    return list_of_strings

I should note, since it might be not obvious, that it's not the same as what is proposed in other answers.

Getting 404 Not Found error while trying to use ErrorDocument

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

ErrorDocument 404 /hellothere/error/404page.html

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

You need to CAST the ParentId as an nvarchar, so that the output is always the same data type.

SELECT Id   'PatientId',
       ISNULL(CAST(ParentId as nvarchar(100)),'')  'ParentId'
FROM Patients

Assigning variables with dynamic names in Java

This is not how you do things in Java. There are no dynamic variables in Java. Java variables have to be declared in the source code1.

Depending on what you are trying to achieve, you should use an array, a List or a Map; e.g.

int n[] = new int[3];
for (int i = 0; i < 3; i++) {
    n[i] = 5;
}

List<Integer> n = new ArrayList<Integer>();
for (int i = 1; i < 4; i++) {
    n.add(5);
}

Map<String, Integer> n = new HashMap<String, Integer>();
for (int i = 1; i < 4; i++) {
    n.put("n" + i, 5);
}

It is possible to use reflection to dynamically refer to variables that have been declared in the source code. However, this only works for variables that are class members (i.e. static and instance fields). It doesn't work for local variables. See @fyr's "quick and dirty" example.

However doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and since you are relying on runtime checking it is more fragile. And this is not "variables with dynamic names". It is better described as dynamic access to variables with static names.


1 - That statement is slightly inaccurate. If you use BCEL or ASM, you can "declare" the variables in the bytecode file. But don't do it! That way lies madness!

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

For CSS, I found that max height of 180 is better for mobile phones landscape 320 when showing browser chrome.

.scrollable-menu {
    height: auto;
    max-height: 180px;
    overflow-x: hidden;
}

Also, to add visible scrollbars, this CSS should do the trick:

.scrollable-menu::-webkit-scrollbar {
    -webkit-appearance: none;
    width: 4px;        
}    
.scrollable-menu::-webkit-scrollbar-thumb {
    border-radius: 3px;
    background-color: lightgray;
    -webkit-box-shadow: 0 0 1px rgba(255,255,255,.75);        
}

The changes are reflected here: https://www.bootply.com/BhkCKFEELL

Why is printing "B" dramatically slower than printing "#"?

Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.

  1. First Matrix: O and # = 6.03 seconds
  2. Second Matrix: O and B = 50.97 seconds

Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("B");
        }
        if(j%100==0){               //Adding a line break in second loop      
            System.out.println();
        }                    
    }
    System.out.println("");                
}

Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.

NetBeans Editor Settings

Get HTML code using JavaScript with a URL

You can use fetch to do that:

fetch('some_url')
    .then(function (response) {
        switch (response.status) {
            // status "OK"
            case 200:
                return response.text();
            // status "Not Found"
            case 404:
                throw response;
        }
    })
    .then(function (template) {
        console.log(template);
    })
    .catch(function (response) {
        // "Not Found"
        console.log(response.statusText);
    });

Asynchronous with arrow function version:

(async () => {
    var response = await fetch('some_url');
    switch (response.status) {
        // status "OK"
        case 200:
            var template = await response.text();

            console.log(template);
            break;
        // status "Not Found"
        case 404:
            console.log('Not Found');
            break;
    }
})();

How to sort a HashMap in Java

Seems like you might want a treemap.

http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

You can pass in a custom comparator to it if that applies.

JS strings "+" vs concat method

  • We can't concatenate a string variable to an integer variable using concat() function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.
  • As we know, functions are pretty slower than operators. functions needs to pass values to the predefined functions and need to gather the results of the functions. which is slower than doing operations using operators because operators performs operations in-line but, functions used to jump to appropriate memory locations... So, As mentioned in previous answers the other difference is obviously the speed of operation.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
_x000D_
<script>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
</script>_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I append a node to an existing XML file in java

You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));

Element root = document.getDocumentElement();

for (Server newServer : Collection<Server> bunchOfNewServers){
  Element server = Document.createElement("server");
  /* create and setup the server node...*/

 root.appendChild(server);
}

/* use whatever method to output DOM to XML (for example, using transformer like you did).*/

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

java.lang.NoClassDefFoundError in junit

These steps worked for me when the error showed that the Filter class was missing (as reported in this false-diplicated question: JUnit: NoClassDefFoundError: org/junit/runner/manipulation/Filter ):

  1. Make sure to have JUnit 4 referenced only once in your project (I also removed the Maven nature, but I am not sure if this step has any influence in solving the problem).
  2. Right click the file containing unit tests, select Properties, and under the Run/Debug settings, remove any entries from the Launch Configurations for that file. Hit Apply and close.
  3. Right click the project containing unit tests, select Properties, and under the Run/Debug settings, remove any entries involving JUnit from the Launch Configurations. Hit Apply and close.
  4. Clean the project, and run the test.

Thanks to these answers for giving me the hint for this solution: https://stackoverflow.com/a/34067333/5538923 and https://stackoverflow.com/a/39987979/5538923).

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

Google Mobile Ads SDK FAQ states that:

I keep getting the error 'The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.'

You can safely ignore this message. Your app will still fetch and serve banner ads.

So if you included the google-play-services_lib correctly, and you're getting ads, you have nothing to worry about (I guess...)

Passing arguments to C# generic new() of templated type

I found that I was getting an error "cannot provide arguments when creating an instance of type parameter T" so I needed to do this:

var x = Activator.CreateInstance(typeof(T), args) as T;

How to toggle a boolean?

In a case where you may be storing true / false as strings, such as in localStorage where the protocol flipped to multi object storage in 2009 & then flipped back to string only in 2011 - you can use JSON.parse to interpret to boolean on the fly:

this.sidebar = !JSON.parse(this.sidebar);

Get a DataTable Columns DataType

if (dr[dc.ColumnName].GetType().ToString() == "System.DateTime")

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

If you are working on PC of a company that uses a proxy you must turn on your VPN

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.

You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.

So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".


That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.

REST:

REST is a design concept.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.

It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Flickr's REST API goes further and lets you return images as well.


JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

With Github's official new command line interface:

gh repo create

See additional details and options and installation instructions.


For instance, to complete your git workflow:

mkdir project
cd project
git init
touch file
git add file
git commit -m 'Initial commit'
gh repo create
git push -u origin master

PHP function to get the subdomain of a URL

As the only reliable source for domain suffixes are the domain registrars, you can't find the subdomain without their knowledge. There is a list with all domain suffixes at https://publicsuffix.org. This site also links to a PHP library: https://github.com/jeremykendall/php-domain-parser.

Please find an example below. I also added the sample for en.test.co.uk which is a domain with a multi suffix (co.uk).

<?php

require_once 'vendor/autoload.php';

$pslManager = new Pdp\PublicSuffixListManager();
$parser = new Pdp\Parser($pslManager->getList());
$host = 'http://en.example.com';
$url = $parser->parseUrl($host);

echo $url->host->subdomain;


$host = 'http://en.test.co.uk';
$url = $parser->parseUrl($host);

echo $url->host->subdomain;

How to annotate MYSQL autoincrement field with JPA annotations

To use a MySQL AUTO_INCREMENT column, you are supposed to use an IDENTITY strategy:

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

Which is what you'd get when using AUTO with MySQL:

@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

Which is actually equivalent to

@Id @GeneratedValue
private Long id;

In other words, your mapping should work. But Hibernate should omit the id column in the SQL insert statement, and it is not. There must be a kind of mismatch somewhere.

Did you specify a MySQL dialect in your Hibernate configuration (probably MySQL5InnoDBDialect or MySQL5Dialect depending on the engine you're using)?

Also, who created the table? Can you show the corresponding DDL?

Follow-up: I can't reproduce your problem. Using the code of your entity and your DDL, Hibernate generates the following (expected) SQL with MySQL:

insert 
into
    Operator
    (active, password, username) 
values
    (?, ?, ?)

Note that the id column is absent from the above statement, as expected.

To sum up, your code, the table definition and the dialect are correct and coherent, it should work. If it doesn't for you, maybe something is out of sync (do a clean build, double check the build directory, etc) or something else is just wrong (check the logs for anything suspicious).

Regarding the dialect, the only difference between MySQL5Dialect or MySQL5InnoDBDialect is that the later adds ENGINE=InnoDB to the table objects when generating the DDL. Using one or the other doesn't change the generated SQL.

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

JavaType javaType = objectMapper.getTypeFactory().constructParameterizedType(Map.class, Key.class, Value.class);
Map<Key, Value> map=objectMapper.readValue(jsonStr, javaType);

i think this will solve your problem.

How to make exe files from a node.js app?

By default, Windows associates .js files with the Windows Script Host, Microsoft's stand-alone JS runtime engine. If you type script.js at a command prompt (or double-click a .js file in Explorer), the script is executed by wscript.exe.

This may be solving a local problem with a global setting, but you could associate .js files with node.exe instead, so that typing script.js at a command prompt or double-clicking/dragging items onto scripts will launch them with Node.

Of course, if—like me—you've associated .js files with an editor so that double-clicking them opens up your favorite text editor, this suggestion won't do much good. You could also add a right-click menu entry of "Execute with Node" to .js files, although this alternative doesn't solve your command-line needs.


The simplest solution is probably to just use a batch file – you don't have to have a copy of Node in the folder your script resides in. Just reference the Node executable absolutely:

"C:\Program Files (x86)\nodejs\node.exe" app.js %*

Another alternative is this very simple C# app which will start Node using its own filename + .js as the script to run, and pass along any command line arguments.

class Program
{
    static void Main(string[] args)
    {
        var info = System.Diagnostics.Process.GetCurrentProcess();
        var proc = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\nodejs\node.exe", "\"" + info.ProcessName + ".js\" " + String.Join(" ", args));
        proc.UseShellExecute = false;
        System.Diagnostics.Process.Start(proc);
    }
}

So if you name the resulting EXE "app.exe", you can type app arg1 ... and Node will be started with the command line "app.js" arg1 .... Note the C# bootstrapper app will immediately exit, leaving Node in charge of the console window.

Since this is probably of relatively wide interest, I went ahead and made this available on GitHub, including the compiled exe if getting in to vans with strangers is your thing.

How to get the string size in bytes?

While sizeof works for this specific type of string:

char str[] = "content";
int charcount = sizeof str - 1; // -1 to exclude terminating '\0'

It does not work if str is pointer (sizeof returns size of pointer, usually 4 or 8) or array with specified length (sizeof will return the byte count matching specified length, which for char type are same).

Just use strlen().

How to call gesture tap on UIView programmatically in swift

I worked out on Xcode 7.3.1 on Swift 2.2. See below.

func addTapGesture() {
    let tap = UITapGestureRecognizer(target: self, action: #selector(MyViewController.handleTap))
    tap.numberOfTapsRequired = 1
    self.myView.addGestureRecognizer(tap)
}

func handleTap() {
    // Your code here...
}

How do I know which version of Javascript I'm using?

All of todays browsers use at least version 1.5:
http://en.wikipedia.org/wiki/ECMAScript#Dialect

Concerning your tutorial site, the information there seems to be extremely outdated, I beg you to head over to MDC and read their Guide:
https://developer.mozilla.org/en/JavaScript/Guide

You may still want to watch out for features which require version 1.6 or above, as this might give Internet Explorer some troubles.

What are the different NameID format used for?

1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:

Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:

urn:oasis:names:tc:SAML:1.0:
urn:oasis:names:tc:SAML:1.1:
urn:oasis:names:tc:SAML:2.0:

Apply jQuery datepicker to multiple instances

A little note to the SeanJA answer.

Interestingly, if you use KnockoutJS and jQuery together the following inputs with different IDs, but with the same data-bind observable:

<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: first_dt" id="date_2" class="datepick" />

will bind one (the same) datepicker to both of the inputs (even though they have different ids or names).

Use separate observables in your ViewModel to bind a separate datepicker to each input:

<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: second_dt" id="date_2" class="datepick" />

Initialization:

$('.datepick').each(function(){
    $(this).datepicker();
});

Update Eclipse with Android development tools v. 23

I have followed instructions found here and tried to fix my old Eclipse + SDK + ADT, but with no luck. The basic problem keeps beeing the same; I still get the error message:

This Android SDK requires Android Developer Toolkit version 23.0.0 or above. Current version is 22.6.3.v201404151837-1123206. Please update ADT to the latest version.

But my eclipse can't find updates and can't install ADT 23 as new software. So I can't compile my old project in my workspace.

I tested a fresh eclipode bundle for Windows 8, followed instructions found from Android's developers page, step by step, and it worked fine. So it seems that the Windows Eclipse build is not broken. But I wan't use my Linux installation, my old Ubuntu 10. It seems obvious, that to getting the Linux Eclipse environment working again, I must install a new Eclipse bundle, my old Eclipse won't ever see updates for ADT 23 to get things working. Again, these intructions are for Linux developers that wan't to get their old workspace projects working again without changes in the developing environment, except you must install a new Eclipse bundle, but after that your projects will work as well as before the version 23 SDK/ADT-mess.

  1. If you are an Android developer you want to be sure, that you developing environment won't be messed up. Backup:
    • ~./android (Here are your developer keys)
    • Your old SDK dirrectory
    • Your workspace
  2. Download the Eclipse bundle, Get the Android SDK.
  3. Follow instructions, create directory ~/Development and unzip bundle there. You get Eclipse and SDK directories.
  4. Start Eclipse from that directory
  5. Eclipse asks for a workspace. You can give it the old one.
  6. In Eclipse settings set SDK as downloaded SDK.
  7. Start Android SDK manager and download tools, Android versions you use and extras said in the Android developer tool page instructions
  8. You should now be ready to compile your old projects again, but for me it was not that simple. My old projects had errors. So open problems windows and you get to know that annotation.jar is missing. So you must copy annotations.jar from your old SDK, from, the backup you made, or from the older sdk.zip explained in this thread to <new SDK>/tools/support/annotations.jar

After that I could use my old workspace in Ubuntu and compile and launch applications to Android devices. It was that simple. Thanks Google ;-(

Return a value if no rows are found in Microsoft tSQL

Something like:

if exists (select top 1 * from Sites S where S.Id IS NOT NULL AND S.Status = 1 AND (S.WebUserId = @WebUserId OR S.AllowUploads = 1))
    select 1
else
    select 0

Displaying a webcam feed using OpenCV and Python

change import cv to import cv2.cv as cv See also the post here.

Why can't I initialize non-const static member or static array in class?

I think it's to prevent you from mixing declarations and definitions. (Think about the problems that could occur if you include the file in multiple places.)

Find if variable is divisible by 2

Hope this helps.

let number = 7;

if(number%2 == 0){      

  //do something;
  console.log('number is Even');  

}else{

  //do otherwise;
  console.log('number is Odd');

}

Here is a complete function that will log to the console the parity of your input.

const checkNumber = (x) => {
  if(number%2 == 0){      

    //do something;
    console.log('number is Even');  

  }else{

    //do otherwise;
    console.log('number is Odd');

  }
}

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

Searching in a ArrayList with custom objects for certain strings

Probably something like:

ArrayList<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points

//Traversal
for(DataPoint myPoint : myList) {
    if(myPoint.getName() != null && myPoint.getName().equals("Michael Hoffmann")) {
        //Process data do whatever you want
        System.out.println("Found it!");
     }
}

How to get the unix timestamp in C#

You can also use Ticks. I'm coding for Windows Mobile so don't have the full set of methods. TotalSeconds is not available to me.

long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);

or

TimeSpan epochTicks = new TimeSpan(new DateTime(1970, 1, 1).Ticks);
TimeSpan unixTicks = new TimeSpan(DateTime.UtcNow.Ticks) - epochTicks;
double unixTime = unixTicks.TotalSeconds;

Cancel a vanilla ECMAScript 6 Promise chain

If your code is placed in a class you could use a decorator for that. You have such decorator in the utils-decorators (npm install --save utils-decorators). It will cancel the previous invocation of the decorated method if before the resolving of the previous call there was made another call for that specific method.

import {cancelPrevious} from 'utils-decorators';

class SomeService {

   @cancelPrevious()
   doSomeAsync(): Promise<any> {
    ....
   }
}

or you could use a wrapper function:

import {cancelPreviousify} from 'utils-decorators';

const cancelable = cancelPreviousify(originalMethod)

https://github.com/vlio20/utils-decorators#cancelprevious-method

ASP.Net Download file to client browser

Try changing it to.

 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
 Response.AddHeader("Content-Length", file.Length.ToString());
 Response.ContentType = "text/plain";
 Response.Flush();
 Response.TransmitFile(file.FullName);
 Response.End();

How to download and save a file from Internet using Java?

When using Java 7+ use the following method to download a file from the Internet and save it to some directory:

private static Path download(String sourceURL, String targetDirectory) throws IOException
{
    URL url = new URL(sourceURL);
    String fileName = sourceURL.substring(sourceURL.lastIndexOf('/') + 1, sourceURL.length());
    Path targetPath = new File(targetDirectory + File.separator + fileName).toPath();
    Files.copy(url.openStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

    return targetPath;
}

Documentation here.

Clone private git repo with dockerfile

Another option is to use a multi-stage docker build to ensure that your SSH keys are not included in the final image.

As described in my post you can prepare your intermediate image with the required dependencies to git clone and then COPY the required files into your final image.

Additionally if we LABEL our intermediate layers, we can even delete them from the machine when finished.

# Choose and name our temporary image.
FROM alpine as intermediate
# Add metadata identifying these images as our build containers (this will be useful later!)
LABEL stage=intermediate

# Take an SSH key as a build argument.
ARG SSH_KEY

# Install dependencies required to git clone.
RUN apk update && \
    apk add --update git && \
    apk add --update openssh

# 1. Create the SSH directory.
# 2. Populate the private key file.
# 3. Set the required permissions.
# 4. Add github to our list of known hosts for ssh.
RUN mkdir -p /root/.ssh/ && \
    echo "$SSH_KEY" > /root/.ssh/id_rsa && \
    chmod -R 600 /root/.ssh/ && \
    ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts

# Clone a repository (my website in this case)
RUN git clone [email protected]:janakerman/janakerman.git

# Choose the base image for our final image
FROM alpine

# Copy across the files from our `intermediate` container
RUN mkdir files
COPY --from=intermediate /janakerman/README.md /files/README.md

We can then build:

MY_KEY=$(cat ~/.ssh/id_rsa)
docker build --build-arg SSH_KEY="$MY_KEY" --tag clone-example .

Prove our SSH keys are gone:

docker run -ti --rm clone-example cat /root/.ssh/id_rsa

Clean intermediate images from the build machine:

docker rmi -f $(docker images -q --filter label=stage=intermediate)

How to inspect FormData?

Updated Method:

As of March 2016, recent versions of Chrome and Firefox now support using FormData.entries() to inspect FormData. Source.

// Create a test FormData object
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

// Display the key/value pairs
for (var pair of formData.entries()) {
    console.log(pair[0]+ ', ' + pair[1]); 
}

Thanks to Ghost Echo and rloth for pointing this out!

Old Answer:

After looking at these Mozilla articles, it looks like there is no way to get data out of a FormData object. You can only use them for building FormData to send via an AJAX request.

I also just found this question that states the same thing: FormData.append("key", "value") is not working.

One way around this would be to build up a regular dictionary and then convert it to FormData:

var myFormData = {
    key1: 300,
    key2: 'hello world'
};

var fd = new FormData();
for (var key in myFormData) {
    console.log(key, myFormData[key]);
    fd.append(key, myFormData[key]);
}

If you want to debug a plain FormData object, you could also send it in order to examine it in the network request console:

var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(fd);

The page cannot be displayed because an internal server error has occurred on server

it seems it works after I commented this line in web.config

<compilation debug="true" targetFramework="4.5.2" />

How do I to insert data into an SQL table using C# as well as implement an upload function?

using System;
using System.Data;
using System.Data.SqlClient;

namespace InsertingData
{
    class sqlinsertdata
    {
        static void Main(string[] args)
        {
            try
            { 
            SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                cmd.ExecuteNonQuery();
                Console.WriteLine("Inserting Data Successfully");
                conn.Close();
        }
            catch(Exception e)
            {
                Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
            }
            Console.ReadKey();

    }
    }
}

'sudo gem install' or 'gem install' and gem locations

You can install gems into a specific folder (example vendor/) in your Rails app using :

bundle install --path vendor

One line if-condition-assignment

Here is what i can suggest. Use another variable to derive the if clause and assign it to num1.

Code:

num2 =20 if someBoolValue else num1
num1=num2

Finding the second highest number in array

Find the second largest number:

public class SecondMaxNumbers {

    public void printTwoMaxNumbers(int[] nums){
        int maxOne = 0;
        int maxTwo = 0;
        for(int n:nums){
            if(maxOne < n){
                maxTwo = maxOne;
                maxOne =n;
            } else if(maxTwo < n){
                maxTwo = n;
            }
        }
        System.out.println("Second Max Number: "+maxTwo);
    }

    public static void main(String a[]){
        int num[] = {10,20,30,40,50,60,70};
        SecondMaxNumbers sec = new SecondMaxNumbers();
        tmn.printTwoMaxNumbers(num);
    }
}

Understanding the ngRepeat 'track by' expression

You can track by $index if your data source has duplicate identifiers

e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]

You can't iterate this collection while using 'id' as identifier (duplicate id:1).

WON'T WORK:

<element ng-repeat="item.id as item.name for item in dataSource">
  // something with item ...
</element>

but you can, if using track by $index:

<element ng-repeat="item in dataSource track by $index">
  // something with item ...
</element>

jQuery how to find an element based on a data-attribute value?

When searching with [data-x=...], watch out, it doesn't work with jQuery.data(..) setter:

$('<b data-x="1">'  ).is('[data-x=1]') // this works
> true

$('<b>').data('x', 1).is('[data-x=1]') // this doesn't
> false

$('<b>').attr('data-x', 1).is('[data-x=1]') // this is the workaround
> true

You can use this instead:

$.fn.filterByData = function(prop, val) {
    return this.filter(
        function() { return $(this).data(prop)==val; }
    );
}

$('<b>').data('x', 1).filterByData('x', 1).length
> 1

if (boolean condition) in Java

This is how the if behaves.

if(turnedOn) // This turnedOn should be a boolean or you could have a condition here which would give a boolean result.
{
// It will come here if turnedOn is true (i.e) the condition in the "if" evaluates to true
}
else
{
// It will come here if turnedOn is false (i.e) the condition in the "if" evaluates to false
}

HashSet vs. List performance

Depends on a lot of factors... List implementation, CPU architecture, JVM, loop semantics, complexity of equals method, etc... By the time the list gets big enough to effectively benchmark (1000+ elements), Hash-based binary lookups beat linear searches hands-down, and the difference only scales up from there.

Hope this helps!

Add carriage return to a string

string s2 = s1.Replace(",", ",\r\n");

jQuery find events handlers registered with an object

Events can be retrieved using:

jQuery(elem).data('events');

or jQuery 1.8+:

jQuery._data(elem, 'events');

Note: Events bounded using $('selector').live('event', handler) can be retrieved using:

jQuery(document).data('events')

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

Just adding on top of Jacob's answer, for img in td,

body {line-height: 0;}
img {display: block; vertical-align: bottom;}

This works for most email clients, including Gmail. But not Outlook. For outlook, you need to do two steps more:

table {border-collapse: collapse;}

and set every td elements to have the same height and width as its contained images. For example,

<td width="600" height="80" style="line-height: 80px;">
    <img height="80" src="http://www.website.com/images/Nature_01.jpg" width="600" />
</td>

How to save Excel Workbook to Desktop regardless of user?

Not sure if this is still relevant, but I use this way

Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean   'put this at the top of the module

 Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
    GetUserID = Left$(strUserName, lngLen - 1)
Else
    GetUserID = ""
End If
Exit Function
End Function

This next bit I save file as PDF, but can change to suit

Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)

ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
    True
End Sub

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

Inside a code you if you use a variable without using var, then what happens is the automatically var var_name is placed in the global scope eg:

someFunction() {
    var a = some_value; /*a has local scope and it cannot be accessed when this
    function is not active*/
    b = a; /*here it places "var b" at top of script i.e. gives b global scope or
    uses already defined global variable b */
}

How do I compile and run a program in Java on my Mac?

I will give you steps to writing and compiling code. Use this example:

 public class Paycheck {
    public static void main(String args[]) {
        double amountInAccount;
        amountInAccount = 128.57;
        System.out.print("You earned $");
        System.out.print(amountInAccount);
        System.out.println(" at work today.");
    }
}
  1. Save the code as Paycheck.java
  2. Go to terminal and type cd Desktop
  3. Type javac Paycheck.java
  4. Type java Paycheck
  5. Enjoy your program!

HTML - Display image after selecting filename

You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/

Laravel migration default value

Put the default value in single quote and it will work as intended. An example of migration:

$table->increments('id');
            $table->string('name');
            $table->string('url');
            $table->string('country');
            $table->tinyInteger('status')->default('1');
            $table->timestamps();

EDIT : in your case ->default('100.0');

What should I set JAVA_HOME environment variable on macOS X 10.6?

Also, it`s interesting to set your PATH to reflect the JDK. After adding JAVA_HOME (which can be done with the example cited by 'mipadi'):

export JAVA_HOME=$(/usr/libexec/java_home)

Add also in ~/.profile:

export PATH=${JAVA_HOME}/bin:$PATH

P.S.: For OSX, I generally use .profile in the HOME dir instead of .bashrc

psycopg2: insert multiple rows with one query

Finally in SQLalchemy1.2 version, this new implementation is added to use psycopg2.extras.execute_batch() instead of executemany when you initialize your engine with use_batch_mode=True like:

engine = create_engine(
    "postgresql+psycopg2://scott:tiger@host/dbname",
    use_batch_mode=True)

http://docs.sqlalchemy.org/en/latest/changelog/migration_12.html#change-4109

Then someone would have to use SQLalchmey won't bother to try different combinations of sqla and psycopg2 and direct SQL together..

How to grep with a list of words

You need to use the option -f:

$ grep -f A B

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B

You may also want the -w option for matching whole words only:

$ grep -wFf A B

Read man grep for a description of all the possible arguments and what they do.

how to hide a vertical scroll bar when not needed

overflow: auto (or overflow-y: auto) is the correct way to go.

The problem is that your text area is taller than your div. The div ends up cutting off the textbox, so even though it looks like it should start scrolling when the text is taller than 159px it won't start scrolling until the text is taller than 400px which is the height of the textbox.

Try this: http://jsfiddle.net/G9rfq/1/

I set overflow:auto on the text box, and made the textbox the same size as the div.

Also I don't believe it's valid to have a div inside a label, the browser will render it, but it might cause some funky stuff to happen. Also your div isn't closed.

jQuery Mobile: document ready vs. page events

While you use .on(), it's basically a live query that you are using.

On the other hand, .ready (as in your case) is a static query. While using it, you can dynamically update data and do not have to wait for the page to load. You can simply pass on the values into your database (if required) when a particular value is entered.

The use of live queries is common in forms where we enter data (account or posts or even comments).

Using Node.JS, how do I read a JSON file into (server) memory?

At least in Node v8.9.1, you can just do

var json_data = require('/path/to/local/file.json');

and access all the elements of the JSON object.

Ignoring upper case and lower case in Java

The .equalsIgnoreCase() method should help with that.

What is the difference between a Docker image and a container?

Workflow

Here is the end-to-end workflow showing the various commands and their associated inputs and outputs. That should clarify the relationship between an image and a container.

+------------+  docker build   +--------------+  docker run -dt   +-----------+  docker exec -it   +------+
| Dockerfile | --------------> |    Image     | --------------->  | Container | -----------------> | Bash |
+------------+                 +--------------+                   +-----------+                    +------+
                                 ^
                                 | docker pull
                                 |
                               +--------------+
                               |   Registry   |
                               +--------------+

To list the images you could run, execute:

docker image ls

To list the containers you could execute commands on:

docker ps

How to dynamic new Anonymous Class?

You can create an ExpandoObject like this:

IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;

And after casting it to dynamic, those values will look like properties:

dynamic d = expando;
Console.WriteLine(d.Name);

However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:

d.GetType().GetProperty("Name") 

Creating a range of dates in Python

Get range of dates between specified start and end date (Optimized for time & space complexity):

import datetime

start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")
end = datetime.datetime.strptime("07-07-2014", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]

for date in date_generated:
    print date.strftime("%d-%m-%Y")

How to call a shell script from python code?

import os
import sys

Assuming test.sh is the shell script that you would want to execute

os.system("sh test.sh")

Disable-web-security in Chrome 48+

For Mac, using Safari is a good alternate option for local development purpose and the feature is built into the browser (so no need to add browser extension or launch Chrome using bash command like [open -a Google\ Chrome --args --disable-web-security --user-data-dir=""].

To disable cross origin restriction using Safari (v11+): From menu click “Develop > Disable Cross Origin Restriction”.

This does not require relaunching the browser and since its a toggle you can easily switch to secure mode.

Batch file. Delete all files and folders in a directory

del *.* will only delete files, but not subdirectories. To nuke the contents of a directory, you can use this script:

@echo off
setlocal enableextensions
if {%1}=={} goto :HELP
if {%1}=={/?} goto :HELP
goto :START

:HELP
echo Usage: %~n0 directory-name
echo.
echo Empties the contents of the specified directory,
echo WITHOUT CONFIRMATION. USE EXTREME CAUTION!
goto :DONE

:START
pushd %1 || goto :DONE
rd /q /s . 2> NUL
popd

:DONE
endlocal

The pushd changes into the directory of which you want to delete the children. Then when rd asks to delete the current directory and all sub directories, the deletion of the sub directories succeed, but the deletion of the current directory fails - because we are in it. This produces an error which 2> NUL swallows. (2 being the error stream).

What is the SQL command to return the field names of a table?

Just for completeness, since MySQL and Postgres have already been mentioned: With SQLite, use "pragma table_info()"

sqlite> pragma table_info('table_name');
cid         name        type        notnull     dflt_value  pk        
----------  ----------  ----------  ----------  ----------  ----------
0           id          integer     99                      1         
1           name                    0                       0         

Can we add div inside table above every <tr>?

"div" tag can not be used above "tr" tag. Instead you can use "tbody" tag to do your work. If you are planning to give id attribute to div tag and doing some processing, same purpose you can achieve through "tbody" tag. Div and Table are both block level elements. so they can not be nested. For further information visit this page

For example:

<table>
    <tbody class="green">
        <tr>
            <td>Data</td>
        </tr>
    </tbody>
    <tbody class="blue">
        <tr>
            <td>Data</td>
        </tr>
    </tbody>
</table>

secondly, you can put "div" tag inside "td" tag.

<table>
    <tr>
        <td>
            <div></div>
        </td>
    </tr>
</table>

Further questions are always welcome.

"sed" command in bash

sed is the Stream EDitor. It can do a whole pile of really cool things, but the most common is text replacement.

The s,%,$,g part of the command line is the sed command to execute. The s stands for substitute, the , characters are delimiters (other characters can be used; /, : and @ are popular). The % is the pattern to match (here a literal percent sign) and the $ is the second pattern to match (here a literal dollar sign). The g at the end means to globally replace on each line (otherwise it would only update the first match).

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

How to change my Git username in terminal?

From your terminal do:

git config credential.username "prefered username"

OR

git config --global user.name "Firstname Lastname"

jQuery Multiple ID selectors

That should work, you may need a space after the commas.

Also, the function you call afterwards must support an array of objects, and not just a singleton object.

Mvn install or Mvn package

If you're not using a remote repository (like artifactory), use plain old: mvn clean install

Pretty old topic but AFAIK, if you run your own repository (eg: with artifactory) to share jar among your team(s), you might want to use

mvn clean deploy

instead.

This way, your continuous integration server can be sure that all dependencies are correctly pushed into your remote repository. If you missed one, mvn will not be able to find it into your CI local m2 repository.

batch file to check 64bit or 32bit OS

'ProgramFiles(x86)' is an environment variable automatically defined by cmd.exe (both 32-bit and 64-bit versions) on Windows 64-bit machines only, so try this:

@ECHO OFF

echo Check operating system ...
if defined PROGRAMFILES(X86) (
    echo 64-bit sytem detected
) else (
    echo 32-bit sytem detected
)
pause

getting only name of the class Class.getName()

Get simple name instead of path.

String onlyClassName =  this.getLocalClassName(); 

call above method in onCreate

Upgrading Node.js to latest version

All platforms (Windows, Mac & Linux)

Just go to nodejs.org and download the latest installer. It couldn't be any simpler honestly, and without involvement of any third-party stuff. It only takes a minute and does not require you to restart anything or clean out caches, etc.

I've done it via npm a few times before and have run into a few issues. Like for example with the n-package not using the latest stable release.

How to force Selenium WebDriver to click on element which is not currently visible?

I just solve this error while using capybara in ror project by adding:

Capybara.ignore_elements = true

to features/support/env.rb.

Where are Magento's log files located?

These code lines can help you quickly enable log setting in your magento site.

INSERT INTO `core_config_data` (`config_id`, `scope`, `scope_id`, `path`, `value`) VALUES
('', 'default', 0, 'dev/log/active', '1'),
('', 'default', 0, 'dev/log/file', 'system.log'),
('', 'default', 0, 'dev/log/exception_file', 'exception.log');

Then you can see them inside the folder: /var/log under root installation.

More detail in this blog

Java says FileNotFoundException but file exists

You'd obviously figure it out after a while but just posting this so that it might help someone. This could also happen when your file path contains any whitespace appended or prepended to it.

Using array map to filter results with if conditional

You could use flatMap. It can filter and map in one.

$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])

How to put a Scanner input into an array... for example a couple of numbers

**Simple solution**
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int size;
    System.out.println("Enter the number of size of array");
    size = sc.nextInt();
    int[] a = new int[size];
    System.out.println("Enter the array element");
    //For reading the element
    for(int i=0;i<size;i++) {
        a[i] = sc.nextInt();
    }
    //For print the array element
    for(int i : a) {
        System.out.print(i+" ,");
    }
}

How to set environment variable or system property in spring tests?

The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource annotation.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
    ...    
}

See @TestPropertySource in the Spring docs and Javadocs.

Convert JSON to DataTable

Here is another seamless approach to convert JSON to Datatable using Cinchoo ETL - an open source library

Sample below shows how to convert

string json = @"[
{""id"":""10"",""name"":""User"",""add"":false,""edit"":true,""authorize"":true,""view"":true},
{ ""id"":""11"",""name"":""Group"",""add"":true,""edit"":false,""authorize"":false,""view"":true},
{ ""id"":""12"",""name"":""Permission"",""add"":true,""edit"":true,""authorize"":true,""view"":true}
]";

using (var r = ChoJSONReader.LoadText(json))
{
    var dt = r.AsDataTable();
}

Hope it helps.

Git: How to return from 'detached HEAD' state

I had this edge case, where I checked out a previous version of the code in which my file directory structure was different:

git checkout 1.87.1                                    
warning: unable to unlink web/sites/default/default.settings.php: Permission denied
... other warnings ...
Note: checking out '1.87.1'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. 
Example:

  git checkout -b <new-branch-name>

HEAD is now at 50a7153d7... Merge branch 'hotfix/1.87.1'

In a case like this you may need to use --force (when you know that going back to the original branch and discarding changes is a safe thing to do).

git checkout master did not work:

$ git checkout master
error: The following untracked working tree files would be overwritten by checkout:
web/sites/default/default.settings.php
... other files ...

git checkout master --force (or git checkout master -f) worked:

git checkout master -f
Previous HEAD position was 50a7153d7... Merge branch 'hotfix/1.87.1'
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.

Phonegap Cordova installation Windows

Phonegap Cordova Installation on Windows

Requirements

  • Eclipse + ADT Plugin
  • Android SDK Tool
  • Android Platform Tools
  • Latest PhoneGap zip folder. Extract its contents.

Supported Android Devices

Android 2.2 Android 2.3 Android 4.x Phonegap Cordova Installation

Set PATH environment variable for android

  1. From desktop, right click My Computer and click Properties.

  2. Click Advance System Settings link in the left column.

  3. In the system properties window click the environment variables button.

  4. Select the PATH variable from the System variables section. Select the Edit button. You need to add the path to your Android SDK platform-tools and tools directory. For Example: D:\adt-bundle-windows-x86_64-20130219\sdk\platform-tools;D:\adt-bundle-windows-x86_64-20130219\sdk\tools Save your Edit. Close the Environment Variable dialog.

  5. Additionally, you may need to include %JAVA_HOME%\bin to your PATH as well. To check to see if this is required run a command prompt and type java. If the program could not be found add %JAVA_HOME%\bin to the PATH. You may need to specify the full path instead of using %JAVA_HOME% environment variable.
  6. Finally, you may need to include %ANT_HOME%\bin to your PATH as well. To check to see if this is required run a command prompt and type ant. If program cannot be found then add %ANT_HOME%\bin to the PATH. You may need to specify the full path instead of using the %ANT_HOME% environment variable. Set-up New Project

Open Command Prompt, navigate to bin directory within the android sub-folder of the Cordova distribution.

Type in: ./create

Then press Enter.Launch Eclipse. In File Menu Item and select to Import…

Import Select “Existing Android Code into Workspace” and click ‘Next >’.

Browse the project created through command prompt. And click ‘Finish’. Deploy to Emulator From within Eclipse, press this toolbar icon.

Once open, the Android SDK Manager displays various runtime libraries Install the APIs as per requirement from here. From within Eclipse, press this toolbar icon.

Choose and device definition from the list which comes. (There is only one item in the current list.) Press New… in the above window to create new Android Virtual Device(AVD) and use it to run your project.

To open the emulator as a separate application, Select the AVD and press Start. It launches much as it would on device, with additional controls available for hardware buttons:

Deploy to Device:

Make sure USB debugging is enabled on your device and plug it into your system. Right Click the Project and go to Run As > Android Application.

Read more ...

C++ String Declaring

In C++ you can declare a string like this:

#include <string>

using namespace std;

int main()
{
    string str1("argue2000"); //define a string and Initialize str1 with "argue2000"    
    string str2 = "argue2000"; // define a string and assign str2 with "argue2000"
    string str3;  //just declare a string, it has no value
    return 1;
}

How do I add all new files to SVN

If svn add whatever/directory/* doesn't work, you can do it the tough way:

svn st | grep ^\? | cut -c 2- | xargs svn add

How do I read the first line of a file using cat?

There are many different ways:

sed -n 1p file
head -n 1 file
awk 'NR==1' file

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

On your solution explorer window, right click to References, select Add Reference, go to .NET tab, find and add Microsoft.CSharp.

Alternatively add the Microsoft.CSharp NuGet package.

Install-Package Microsoft.CSharp

How do I iterate through children elements of a div using jQuery?

I don't think that you need to use each(), you can use standard for loop

var children = $element.children().not(".pb-sortable-placeholder");
for (var i = 0; i < children.length; i++) {
    var currentChild = children.eq(i);
    // whatever logic you want
    var oldPosition = currentChild.data("position");
}

this way you can have the standard for loop features like break and continue works by default

also, the debugging will be easier

How to convert a selection to lowercase or uppercase in Sublime Text

From the Sublime Text docs for Windows/Linux:

Keypress            Command
Ctrl + K, Ctrl + U  Transform to Uppercase
Ctrl + K, Ctrl + L  Transform to Lowercase

and for Mac:

Keypress    Command
cmd + KU    Transform to Uppercase
cmd + KL    Transform to Lowercase

Also note that Ctrl + Shift + p in Windows (? + Shift + p in a Mac) brings up the Command Palette where you can search for these and other commands. It looks like this:

enter image description here

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

I've run into this with a couple virtual environments.

pip uninstall MySQL-python
pip install -U MySQL-python

Worked both times.

Break when a value changes using the Visual Studio debugger

Right click on the breakpoint works fine for me (though mostly I am using it for conditional breakpoints on specific variable values. Even breaking on expressions involving a thread name works which is very useful if you're trying to spot threading issues).

Difference between SelectedItem, SelectedValue and SelectedValuePath

Their names can be a bit confusing :). Here's a summary:

  • The SelectedItem property returns the entire object that your list is bound to. So say you've bound a list to a collection of Category objects (with each Category object having Name and ID properties). eg. ObservableCollection<Category>. The SelectedItem property will return you the currently selected Category object. For binding purposes however, this is not always what you want, as this only enables you to bind an entire Category object to the property that the list is bound to, not the value of a single property on that Category object (such as its ID property).

  • Therefore we have the SelectedValuePath property and the SelectedValue property as an alternative means of binding (you use them in conjunction with one another). Let's say you have a Product object, that your view is bound to (with properties for things like ProductName, Weight, etc). Let's also say you have a CategoryID property on that Product object, and you want the user to be able to select a category for the product from a list of categories. You need the ID property of the Category object to be assigned to the CategoryID property on the Product object. This is where the SelectedValuePath and the SelectedValue properties come in. You specify that the ID property on the Category object should be assigned to the property on the Product object that the list is bound to using SelectedValuePath='ID', and then bind the SelectedValue property to the property on the DataContext (ie. the Product).

The example below demonstrates this. We have a ComboBox bound to a list of Categories (via ItemsSource). We're binding the CategoryID property on the Product as the selected value (using the SelectedValue property). We're relating this to the Category's ID property via the SelectedValuePath property. And we're saying only display the Name property in the ComboBox, with the DisplayMemberPath property).

<ComboBox ItemsSource="{Binding Categories}" 
          SelectedValue="{Binding CategoryID, Mode=TwoWay}" 
          SelectedValuePath="ID" 
          DisplayMemberPath="Name" />
public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class Product
{
    public int CategoryID { get; set; }
}

It's a little confusing initially, but hopefully this makes it a bit clearer... :)

Chris

Git merge without auto commit

You're misunderstanding the meaning of the merge here.

The --no-commit prevents the MERGE COMMIT from occuring, and that only happens when you merge two divergent branch histories; in your example that's not the case since Git indicates that it was a "fast-forward" merge and then Git only applies the commits already present on the branch sequentially.

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

java.net.ConnectException: Connection refused

I had the same issue, and it turned out to be due to permission of the catalina.out file not being correct. It was not writable by the tomcat user. Once I fixed the permissions, the issue got resolved. I got to know that it is a permissions issue from the logs in the tomcat8-initd.log file:

/usr/sbin/tomcat8: line 40: /usr/share/tomcat8/logs/catalina.out: Permission denied

iterrows pandas get next rows value

Firstly, your "messy way" is ok, there's nothing wrong with using indices into the dataframe, and this will not be too slow. iterrows() itself isn't terribly fast.

A version of your first idea that would work would be:

row_iterator = df.iterrows()
_, last = row_iterator.next()  # take first item from row_iterator
for i, row in row_iterator:
    print(row['value'])
    print(last['value'])
    last = row

The second method could do something similar, to save one index into the dataframe:

last = df.irow(0)
for i in range(1, df.shape[0]):
    print(last)
    print(df.irow(i))
    last = df.irow(i)

When speed is critical you can always try both and time the code.

Negation in Python

Combining the input from everyone else (use not, no parens, use os.mkdir) you'd get...

special_path_for_john = "/usr/share/sounds/blues"
if not os.path.exists(special_path_for_john):
    os.mkdir(special_path_for_john)

Remove Style on Element

var element = document.getElementById('sample_id');
element.style.removeProperty("width");
element.style.removeProperty("height");

CSS3 background image transition

Unfortunately you can't use transition on background-image, see the w3c list of animatable properties.

You may want to do some tricks with background-position.

Difference between socket and websocket?

Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.

I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html

Angular/RxJs When should I unsubscribe from `Subscription`

The SubSink package, an easy and consistent solution for unsubscribing

As nobody else has mentioned it, I want to recommend the Subsink package created by Ward Bell: https://github.com/wardbell/subsink#readme.

I have been using it on a project were we are several developers all using it. It helps a lot to have a consistent way that works in every situation.

How can I declare and define multiple variables in one line using C++?

As of C++17, you can use Structured Bindings:

#include <iostream>
#include <tuple>

int main () 
{
    auto [hello, world] = std::make_tuple("Hello ", "world!");
    std::cout << hello << world << std::endl;
    return 0;
}

Demo

Using find to locate files that match one of multiple patterns

This works on AIX korn shell.

find *.cbl *.dms -prune -type f -mtime -1

This is looking for *.cbl or *.dms which are 1 day old, in current directory only, skipping the sub-directories.

Given an array of numbers, return array of products of all other numbers (no division)

Try this!

import java.util.*;
class arrProduct
{
 public static void main(String args[])
     {
         //getting the size of the array
         Scanner s = new Scanner(System.in);
            int noe = s.nextInt();

        int out[]=new int[noe];
         int arr[] = new int[noe];

         // getting the input array
         for(int k=0;k<noe;k++)
         {
             arr[k]=s.nextInt();
         }

         int val1 = 1,val2=1;
         for(int i=0;i<noe;i++)
         {
             int res=1;

                 for(int j=1;j<noe;j++)
                 {
                if((i+j)>(noe-1))
                {

                    int diff = (i+j)-(noe);

                    if(arr[diff]!=0)
                    {
                    res = res * arr[diff];
                    }
                }

                else
                {
                    if(arr[i+j]!=0)
                    {
                    res= res*arr[i+j];
                    }
                }


             out[i]=res;

         }
         }

         //printing result
         System.out.print("Array of Product: [");
         for(int l=0;l<out.length;l++)
         {
             if(l!=out.length-1)
             {
            System.out.print(out[l]+",");
             }
             else
             {
                 System.out.print(out[l]);
             }
         }
         System.out.print("]");
     }

}

Turn off textarea resizing

This is works for me

_x000D_
_x000D_
<textarea_x000D_
  type='text'_x000D_
  style="resize: none"_x000D_
>_x000D_
Some text_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

Validation for 10 digit mobile number and focus input field on invalid

function is_mobile_valid(string_or_number){
            var mobile=string_or_number;
            if(mobile.length!=10){
                return false;

            }
            intRegex = /[0-9 -()+]+$/;
            is_mobile=true;
            for ( var i=0; i < 10; i++) {
                if(intRegex.test(mobile[i]))
                     { 
                     continue;
                     }
                    else{
                        is_mobile=false;
                        break;
                    }
                 }
            return is_mobile;

}

You can just check by calling the function is_mobile_valid(your_string_of_mobile_number);

how to download file in react js

This is how I did it in React:

import MyPDF from '../path/to/file.pdf';
<a href={myPDF} download="My_File.pdf"> Download Here </a>

It's important to override the default file name with download="name_of_file_you_want.pdf" or else the file will get a hash number attached to it when you download.

What is a "thread" (really)?

Unfortunately, threads do exist. A thread is something tangible. You can kill one, and the others will still be running. You can spawn new threads.... although each thread is not it's own process, they are running separately inside the process. On multi-core machines, 2 threads could run at the same time.

http://en.wikipedia.org/wiki/Simultaneous_multithreading

http://www.intel.com/intelpress/samples/mcp_samplech01.pdf

Quick Way to Implement Dictionary in C

The quickest method would be using binary tree. Its worst case is also only O(logn).

Difference between setTimeout with and without quotes and parentheses

What happens in reality in case you pass string as a first parameter of function

setTimeout('string',number)

is value of first param got evaluated when it is time to run (after numberof miliseconds passed). Basically it is equal to

setTimeout(eval('string'), number)

This is

an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.

So samples which you refer are not good samples, and may be given in different context or just simple typo.

If you invoke like this setTimeout(something, number), first parameter is not string, but pointer to a something called something. And again if something is string - then it will be evaluated. But if it is function, then function will be executed. jsbin sample

What is the proper way to re-throw an exception in C#?

You should always use following syntax to rethrow an exception, else you'll stomp the stack trace:

throw;

If you print the trace resulting from "throw ex", you'll see that it ends on that statement and not at the real source of the exception.

Basically, it should be deemed a criminal offense to use "throw ex".

How to create a temporary table in SSIS control flow task and then use it in data flow task?

I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.

I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.

Deep copy vs Shallow Copy

Shallow copy:

Some members of the copy may reference the same objects as the original:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(copy.pi)
    { }
};

Here, the pi member of the original and copied X object will both point to the same int.


Deep copy:

All members of the original are cloned (recursively, if necessary). There are no shared objects:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(new int(*copy.pi))  // <-- note this line in particular!
    { }
};

Here, the pi member of the original and copied X object will point to different int objects, but both of these have the same value.


The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.

Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.

Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:

The implicitly defined copy constructor for class X performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.

How to create a .gitignore file

Few ways to create .gitignore using cmd:

  • With copy con command:

    1. open cmd and say cd to your git repository
    2. say copy con .gitignore and press Ctrl+Z.

enter image description here

  • With start notepad .gitignore command:

    1. open cmd and say cd to your git repository
    2. say start notepad .gitignore and press Yes button in opened notepad dialog box.

enter image description here

  • With edit .gitignore command (Windows x86 only):

    1. open cmd and say cd to your git repository
    2. say edit .gitignore and close opened edit editor.

MS Access DB Engine (32-bit) with Office 64-bit

A similar approach to @Peter Coppins answer. This, I think, is a bit easier and doesn't require the use of the Orca utility:

  1. Check the "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths" registry key and make sure the value "mso.dll" is NOT present. If it is present, then Office 64-bit seems to be installed and you should not need this workaround.

  2. Download the Microsoft Access Database Engine 2010 Redistributable.

  3. From the command line, run: AccessDatabaseEngine_x64.exe /passive

(Note: this installer silently crashed or failed for me, so I unzipped the components and ran: AceRedist.msi /passive and that installed fine. Maybe a Windows 10 thing.)

  1. Delete or rename the "mso.dll" value in the "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths" key.

Source: How to install 64-bit Microsoft Database Drivers alongside 32-bit Microsoft Office

Jquery checking success of ajax post

I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:

original Code block:

    post: function( url, data, callback, type ) {
    // shift arguments if data argument was omited
    if ( jQuery.isFunction( data ) ) {
        type = type || callback;
        callback = data;
        data = {};
    }

    return jQuery.ajax({
        type: "POST",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });  

Changed Code block:

        post: function (url, data, callback, failcallback, type) {
        if (type === undefined || type === null) {
            if (!jQuery.isFunction(failcallback)) { 
            type=failcallback
        }
        else if (!jQuery.isFunction(callback)) {
            type = callback
        }
        }
        if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
            failcallback = callback;

        }
        // shift arguments if data argument was omited
        if (jQuery.isFunction(data)) {
            type = type || callback;
            callback = data;
            data = {};

        }


        return jQuery.ajax({
            type: "POST",
            url: url,
            data: data,
            success: callback,
            error:failcallback,
            dataType: type
        });
    },

This should help the one trying to catch error on $.Post in jquery.

Updated: Or there is another way to do this is :

   $.post(url,{},function(res){
        //To do write if call is successful
   }).error(function(p1,p2,p3){
             //To do Write if call is failed
          });

Length of a JavaScript object

We can find the length of Object by using:

_x000D_
_x000D_
const myObject = {};
console.log(Object.values(myObject).length);
_x000D_
_x000D_
_x000D_

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

I just had the exact same problem and it turned out to be caused by the fact that 2 projects in the same solution were referencing a different version of the 3rd party library.

Once I corrected all the references everything worked perfectly.

How to get current time in milliseconds in PHP?

Use microtime(true) in PHP 5, or the following modification in PHP 4:

array_sum(explode(' ', microtime()));

A portable way to write that code would be:

function getMicrotime()
{
    if (version_compare(PHP_VERSION, '5.0.0', '<'))
    {
        return array_sum(explode(' ', microtime()));
    }

    return microtime(true);
}

Diff files present in two different directories

Try this:

diff -rq /path/to/folder1 /path/to/folder2      

"No X11 DISPLAY variable" - what does it mean?

you must enable X11 forwarding in you PuTTy

to do so open PuTTy, go to Connection => SSH => Tunnels and check mark the Enable X11 forwarding

Also sudo to server and export the below variable here IP is your local machine's IP

export DISPLAY=10.75.75.75:0.0

enter image description here

How can I view all historical changes to a file in SVN

Thanks, Bendin. I like your solution very much.

I changed it to work in reverse order, showing most recent changes first. Which is important with long standing code, maintained over several years. I usually pipe it into more.

svnhistory elements.py |more

I added -r to the sort. I removed spec. handling for 'first record'. It is it will error out on the last entry, as there is nothing to diff it with. Though I am living with it because I never get down that far.

#!/bin/bash                                                                    

# history_of_file                                                              
#                                                                              
# Bendin on Stack Overflow: http://stackoverflow.com/questions/282802          
#   Outputs the full history of a given file as a sequence of                  
#   logentry/diff pairs.  The first revision of the file is emitted as         
#   full text since there's not previous version to compare it to.             
#                                                                              
# Dlink                                                                        
#   Made to work in reverse order                                              

function history_of_file() {
    url=$1 # current url of file                                               
    svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -nr | {
        while read r
    do
            echo
            svn log -r$r $url@HEAD
            svn diff -c$r $url@HEAD
            echo
    done
    }
}

history_of_file $1

add created_at and updated_at fields to mongoose schemas

Add timestamps to your Schema like this then createdAt and updatedAt will automatic generate for you

var UserSchema = new Schema({
    email: String,
    views: { type: Number, default: 0 },
    status: Boolean
}, { timestamps: {} });

enter image description here
Also you can change createdAt -> created_at by

timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }

jinja2.exceptions.TemplateNotFound error

I think you shouldn't prepend themesDir. You only pass the filename of the template to flask, it will then look in a folder called templates relative to your python file.

How do you clear the console screen in C?

In Windows I have made the mistake of using

system("clear")

but that is actually for Linux

The Windows type is

system("cls")

without #include conio.h

add Shadow on UIView using swift 3

Shadow using UIView Extension Swift 4

I would like to add one more line with selected answer! When we rasterizing the layer, It needs to be set to 2.0 for retina displays. Otherwise label text or images on that view will be blurry. So we need to add rasterizationScale also.

  extension UIView {

    func dropShadow() {
        layer.masksToBounds = false
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.5
        layer.shadowOffset = CGSize(width: -1, height: 1)
        layer.shadowRadius = 1
        layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        layer.shouldRasterize = true
        layer.rasterizationScale = UIScreen.main.scale
    }
}

Should Gemfile.lock be included in .gitignore?

My workmates and I have different Gemfile.lock, because we use different platforms, windows and mac, and our server is linux.

We decide to remove Gemfile.lock in repo and create Gemfile.lock.server in git repo, just like database.yml. Then before deploy it on server, we copy Gemfile.lock.server to Gemfile.lock on server using cap deploy hook

How can I make a SQL temp table with primary key and auto-incrementing field?

you dont insert into identity fields. You need to specify the field names and use the Values clause

insert into #tmp (AssignedTo, field2, field3) values (value, value, value)

If you use do a insert into... select field field field it will insert the first field into that identity field and will bomb

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

On Android >=6.0, We have to request permission runtime.

Step1: add in AndroidManifest.xml file

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

Step2: Request permission.

int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
    //TODO
}

Step3: Handle callback when you request permission.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_READ_PHONE_STATE:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                //TODO
            }
            break;

        default:
            break;
    }
}

Edit: Read official guide here Requesting Permissions at Run Time

Null vs. False vs. 0 in PHP

It's language specific, but in PHP :

Null means "nothing". The var has not been initialized.

False means "not true in a boolean context". Used to explicitly show you are dealing with logical issues.

0 is an int. Nothing to do with the rest above, used for mathematics.

Now, what is tricky, it's that in dynamic languages like PHP, all of them have a value in a boolean context, which (in PHP) is False.

If you test it with ==, it's testing the boolean value, so you will get equality. If you test it with ===, it will test the type, and you will get inequality.

So why are they useful ?

Well, look at the strrpos() function. It returns False if it did not found anything, but 0 if it has found something at the beginning of the string !

<?php
// pitfall :
if (strrpos("Hello World", "Hello")) { 
    // never exectuted
}

// smart move :
if (strrpos("Hello World", "Hello") !== False) {
    // that works !
}
?>

And of course, if you deal with states:

You want to make a difference between DebugMode = False (set to off), DebugMode = True (set to on) and DebugMode = Null (not set at all, will lead to hard debugging ;-)).

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

If you are using API 11 or higher you can try this: FLAG_ACTIVITY_CLEAR_TASK--it seems to be addressing exactly the issue you're having. Obviously the pre-API 11 crowd would have to use some combination of having all activities check an extra, as @doreamon suggests, or some other trickery.

(Also note: to use this you have to pass in FLAG_ACTIVITY_NEW_TASK)

Intent intent = new Intent(this, LoginActivity.class);
intent.putExtra("finish", true); // if you are checking for this in your other Activities
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
                Intent.FLAG_ACTIVITY_CLEAR_TASK |
                Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();

Redirect all to index.php using htaccess

After doing that don't forget to change your href in, <a href="{the chosen redirected name}"> home</a>

Example:

.htaccess file

RewriteEngine On

RewriteRule ^about/$ /about.php

PHP file:

<a href="about/"> about</a>

How to download a file from a website in C#

With the WebClient class:

using System.Net;
//...
WebClient Client = new WebClient ();
Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");

Converting HTML to plain text in PHP for e-mail

You can use lynx with -stdin and -dump options to achieve that:

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/htmp2txt.log", "a") // stderr is a file to write to
);

$process = proc_open('lynx -stdin -dump 2>&1', $descriptorspec, $pipes, '/tmp', NULL);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to htmp2txt.log

    $stdin = $pipes[0];
    fwrite($stdin,  <<<'EOT'
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <title>TEST</title>
</head>
<body>
<h1><span>Lorem Ipsum</span></h1>

<h4>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</h4>
<h5>"There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..."</h5>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque et sapien ut erat porttitor suscipit id nec dui. Nam rhoncus mauris ac dui tristique bibendum. Aliquam molestie placerat gravida. Duis vitae tortor gravida libero semper cursus eu ut tortor. Nunc id orci orci. Suspendisse potenti. Phasellus vehicula leo sed erat rutrum sed blandit purus convallis.
</p>
<p>
Aliquam feugiat, neque a tempus rhoncus, neque dolor vulputate eros, non pellentesque elit lacus ut nunc. Pellentesque vel purus libero, ultrices condimentum lorem. Nam dictum faucibus mollis. Praesent adipiscing nunc sed dui ultricies molestie. Quisque facilisis purus quis felis molestie ut accumsan felis ultricies. Curabitur euismod est id est pretium accumsan. Praesent a mi in dolor feugiat vehicula quis at elit. Mauris lacus mauris, laoreet non molestie nec, adipiscing a nulla. Nullam rutrum, libero id pellentesque tempus, erat nibh ornare dolor, id accumsan est risus at leo. In convallis felis at eros condimentum adipiscing aliquam nisi faucibus. Integer arcu ligula, porttitor in fermentum vitae, lacinia nec dui.
</p>
</body>
</html>
EOT
    );
    fclose($stdin);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}

How to write a switch statement in Ruby

It's critical to emphasize the comma (,) in a when clause. It acts as an || of an if statement, that is, it does an OR comparison and not an AND comparison between the delimited expressions of the when clause. See the following case statement:

x = 3
case x
  when 3, x < 2 then 'apple'
  when 3, x > 2 then 'orange'
end
 => "apple"

x is not less than 2, yet the return value is "apple". Why? Because x was 3 and since ',`` acts as an||, it did not bother to evaluate the expressionx < 2'.

You might think that to perform an AND, you can do something like this below, but it doesn't work:

case x
  when (3 && x < 2) then 'apple'
  when (3 && x > 2) then 'orange'
end
 => nil 

It doesn't work because (3 && x > 2) evaluates to true, and Ruby takes the True value and compares it to x with ===, which is not true, since x is 3.

To do an && comparison, you will have to treat case like an if/else block:

case
  when x == 3 && x < 2 then 'apple'
  when x == 3 && x > 2 then 'orange'
end

In the Ruby Programming Language book, Matz says this latter form is the simple (and infrequently used) form, which is nothing more than an alternative syntax for if/elsif/else. However, whether it is infrequently used or not, I do not see any other way to attach multiple && expressions for a given when clause.

C++ catching all exceptions

Well, if you would like to catch all exception to create a minidump for example...

Somebody did the work on Windows.

See http://www.codeproject.com/Articles/207464/Exception-Handling-in-Visual-Cplusplus In the article, he explains how he found out how to catch all kind of exceptions and he provides code that works.

Here is the list you can catch:

 SEH exception
 terminate
 unexpected
 pure virtual method call
 invalid parameter
 new operator fault 
 SIGABR
 SIGFPE
 SIGILL
 SIGINT
 SIGSEGV
 SIGTERM
 Raised exception
C++ typed exception

And the usage: CCrashHandler ch; ch.SetProcessExceptionHandlers(); // do this for one thread ch.SetThreadExceptionHandlers(); // for each thred


By default, this creates a minidump in the current directory (crashdump.dmp)

How to list physical disks?

GetLogicalDrives() enumerates all mounted disk partitions, not physical drives.

You can enumerate the drive letters with (or without) GetLogicalDrives, then call QueryDosDevice() to find out which physical drive the letter is mapped to.

Alternatively, you can decode the information in the registry at HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices. The binary data encodings there are not obvious, however. If you have a copy of Russinovich and Solomon's book Microsoft Windows Internals, this registry hive is discussed in Chapter 10.

Adding blur effect to background in swift

This worked for me on Swift 5

let blurredView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
blurredView.frame = self.view.bounds
backgroundimage.addSubview(blurredView)

How to uninstall Golang?

only tab
rm -rvf /usr/local/go/
not works well, but
sudo rm -rvf /usr/local/go/
do.

Java finished with non-zero exit value 2 - Android Gradle

in my case problem was build tools version which was 23.0.0 rc3 and i changed to 22.0.1 and my problem fixed.

Base64 PNG data to HTML5 canvas

By the looks of it you need to actually pass drawImage an image object like so

_x000D_
_x000D_
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
  ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

I've tried it in chrome and it works fine.

Finding Android SDK on Mac and adding to PATH

If you don't want to open Android Studio just to modify your path...

They live here with a default installation:

${HOME}/Library/Android/sdk/tools
${HOME}/Library/Android/sdk/platform-tools

Here's what you want to add to your .bashwhatever

export PATH="${HOME}/Library/Android/sdk/tools:${HOME}/Library/Android/sdk/platform-tools:${PATH}"

Preprocessing in scikit learn - single sample - Depreciation warning

Just listen to what the warning is telling you:

Reshape your data either X.reshape(-1, 1) if your data has a single feature/column and X.reshape(1, -1) if it contains a single sample.

For your example type(if you have more than one feature/column):

temp = temp.reshape(1,-1) 

For one feature/column:

temp = temp.reshape(-1,1)

Uri not Absolute exception getting while calling Restful Webservice

Maybe the problem only in your IDE encoding settings. Try to set UTF-8 everywhere:

enter image description here

Mysql: Select all data between two dates

Select *  from  emp where joindate between date1 and date2;

But this query not show proper data.

Eg

1-jan-2013 to 12-jan-2013.

But it's show data

1-jan-2013 to 11-jan-2013.

How to group subarrays by a column value?

I just threw this together, inspired by .NET LINQ

<?php

// callable type hint may be "closure" type hint instead, depending on php version
function array_group_by(array $arr, callable $key_selector) {
  $result = array();
  foreach ($arr as $i) {
    $key = call_user_func($key_selector, $i);
    $result[$key][] = $i;
  }  
  return $result;
}

 $data = array(
        array(1, "Andy", "PHP"),
        array(1, "Andy", "C#"),
        array(2, "Josh", "C#"),
        array(2, "Josh", "ASP"),
        array(1, "Andy", "SQL"),
        array(3, "Steve", "SQL"),
    );

$grouped = array_group_by($data, function($i){  return $i[0]; });

var_dump($grouped);

?>

And voila you get

array(3) {
  [1]=>
  array(3) {
    [0]=>
    array(3) {
      [0]=>
      int(1)
      [1]=>
      string(4) "Andy"
      [2]=>
      string(3) "PHP"
    }
    [1]=>
    array(3) {
      [0]=>
      int(1)
      [1]=>
      string(4) "Andy"
      [2]=>
      string(2) "C#"
    }
    [2]=>
    array(3) {
      [0]=>
      int(1)
      [1]=>
      string(4) "Andy"
      [2]=>
      string(3) "SQL"
    }
  }
  [2]=>
  array(2) {
    [0]=>
    array(3) {
      [0]=>
      int(2)
      [1]=>
      string(4) "Josh"
      [2]=>
      string(2) "C#"
    }
    [1]=>
    array(3) {
      [0]=>
      int(2)
      [1]=>
      string(4) "Josh"
      [2]=>
      string(3) "ASP"
    }
  }
  [3]=>
  array(1) {
    [0]=>
    array(3) {
      [0]=>
      int(3)
      [1]=>
      string(5) "Steve"
      [2]=>
      string(3) "SQL"
    }
  }
}

Java: how to initialize String[]?

You can always write it like this

String[] errorSoon = {"Hello","World"};

For (int x=0;x<errorSoon.length;x++) // in this way u create a for     loop that would like display the elements which are inside the array     errorSoon.oh errorSoon.length is the same as errorSoon<2 

{
   System.out.println(" "+errorSoon[x]); // this will output those two     words, at the top hello and world at the bottom of hello.  
}

RegEx pattern any two letters followed by six numbers

I depends on what is the regexp language you use, but informally, it would be:

[:alpha:][:alpha:][:digit:][:digit:][:digit:][:digit:][:digit:][:digit:]

where [:alpha:] = [a-zA-Z] and [:digit:] = [0-9]

If you use a regexp language that allows finite repetitions, that would look like:

[:alpha:]{2}[:digit:]{6}

The correct syntax depends on the particular language you're using, but that is the idea.

Converting dictionary to JSON

Defining r as a dictionary should do the trick:

>>> r: dict = {'is_claimed': 'True', 'rating': 3.5}
>>> print(r['rating'])
3.5
>>> type(r)
<class 'dict'>

How to get the element clicked (for the whole document)?

Use delegate and event.target. delegate takes advantage of the event bubbling by letting one element listen for, and handle, events on child elements. target is the jQ-normalized property of the event object representing the object from which the event originated.

$(document).delegate('*', 'click', function (event) {
    // event.target is the element
    // $(event.target).text() gets its text
});

Demo: http://jsfiddle.net/xXTbP/

print variable and a string in python

'''

If the python version you installed is 3.6.1, you can print strings and a variable through
a single line of code.
For example the first string is "I have", the second string is "US
Dollars" and the variable, **card.price** is equal to 300, we can write
the code this way:

'''

print("I have", card.price, "US Dollars")

#The print() function outputs strings to the screen.  
#The comma lets you concatenate and print strings and variables together in a single line of code.

How to create RecyclerView with multiple view type?

You can deal multipleViewTypes RecyclerAdapter by making getItemViewType() return the expected viewType value for that position

I prepared an MultipleViewTypeAdapter for constructing MCQ list for examinations which may throw a question that may have 2 or more valid answers (checkbox options) and a single answer questions (radiobutton options).

For this i get the type of Question from API response and i used that for deciding which view i have to show for that question .

public class MultiViewTypeAdapter extends RecyclerView.Adapter {

    Context mContext;
    ArrayList<Question> dataSet;
    ArrayList<String> questions;
    private Object radiobuttontype1; 


    //Viewholder to display Questions with checkboxes
    public static class Checkboxtype2 extends RecyclerView.ViewHolder {
        ImageView imgclockcheck;
        CheckBox checkbox;

        public Checkboxtype2(@NonNull View itemView) {
            super(itemView);
            imgclockcheck = (ImageView) itemView.findViewById(R.id.clockout_cbox_image);
            checkbox = (CheckBox) itemView.findViewById(R.id.clockout_cbox);


        }
    }

        //Viewholder to display Questions with radiobuttons

    public static class Radiobuttontype1 extends RecyclerView.ViewHolder {
        ImageView clockout_imageradiobutton;
        RadioButton clockout_radiobutton;
        TextView sample;

        public radiobuttontype1(View itemView) {
            super(itemView);
            clockout_imageradiobutton = (ImageView) itemView.findViewById(R.id.clockout_imageradiobutton);
            clockout_radiobutton = (RadioButton) itemView.findViewById(R.id.clockout_radiobutton);
            sample = (TextView) itemView.findViewById(R.id.sample);
        }
    }

    public MultiViewTypeAdapter(ArrayList<QueDatum> data, Context context) {
        this.dataSet = data;
        this.mContext = context;

    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {

        if (viewType.equalsIgnoreCase("1")) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
            return new radiobuttontype1(view);

        } else if (viewType.equalsIgnoreCase("2")) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_cbox_list_row, viewGroup, false);
            view.setHorizontalFadingEdgeEnabled(true);
            return new Checkboxtype2(view);

        } else if (viewType.equalsIgnoreCase("3")) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
            return new Radiobuttontype1(view);

        } else if (viewType.equalsIgnoreCase("4")) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
            return new Radiobuttontype1(view);

        } else if (viewType.equalsIgnoreCase("5")) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
            return new Radiobuttontype1(view);
        }


        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int viewType) {
        if (viewType.equalsIgnoreCase("1")) {
            options =  dataSet.get(i).getOptions();
            question = dataSet.get(i).getQuestion();
            image = options.get(i).getValue();
            ((radiobuttontype1) viewHolder).clockout_radiobutton.setChecked(false);
            ((radiobuttontype1) viewHolder).sample.setText(question);
            //loading image bitmap in the ViewHolder's View
            Picasso.with(mContext)
                    .load(image)
                    .into(((radiobuttontype1) viewHolder).clockout_imageradiobutton);

        } else if (viewType.equalsIgnoreCase("2")) {
            options = (ArrayList<Clockout_questions_Option>) dataSet.get(i).getOptions();
            question = dataSet.get(i).getQuestion();
            image = options.get(i).getValue();
            //loading image bitmap in the ViewHolder's View
            Picasso.with(mContext)
                    .load(image)
                    .into(((Checkboxtype2) viewHolder).imgclockcheck);

        } else if (viewType.equalsIgnoreCase("3")) {
                //fit data to viewHolder for ViewType 3
        } else if (viewType.equalsIgnoreCase("4")) {
//fit data to viewHolder for ViewType 4   
        } else if (viewType.equalsIgnoreCase("5")) {
//fit data to viewHolder for ViewType 5     
        }
    }

    @Override
    public int getItemCount() {
        return dataSet.size();
    }

    /**
     * returns viewType for that position by picking the viewType value from the 
     *     dataset
     */
    @Override
    public int getItemViewType(int position) {
        return dataSet.get(position).getViewType();

    }


}

You can avoid multiple conditional based viewHolder data fillings in onBindViewHolder() by assigning same ids for the similar views across viewHolders which differ in their positioning.

Check if a number has a decimal place/is a whole number

Function for check number is Decimal or whole number

function IsDecimalExist(p_decimalNumber) {
    var l_boolIsExist = true;

    if (p_decimalNumber % 1 == 0)
        l_boolIsExist = false;

    return l_boolIsExist;
}

Measure string size in Bytes in php

Do you mean byte size or string length?

Byte size is measured with strlen(), whereas string length is queried using mb_strlen(). You can use substr() to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr() to trim it to X characters in the encoding of the string.

Import Google Play Services library in Android Studio

I got the same problem. I just tried to rebuild, clean and restart but no luck. Then I just remove

compile 'com.google.android.gms:play-services:8.3.0'

from build.gradle and resync. After that I put it again and resync. Next to that, I clean the project and the problem is gone!!

I hope it will help any of you facing the same.

@font-face not working

I'm also facing this type of problem. After trying all solutions I got final solution on this problem. Reasons for this type of problem is per-defined global fonts. Use !important keyword for each line in @font-face is the solution for this problem.

Full description and example for Solution of this problem is here :- http://answerdone.blogspot.com/2017/06/font-face-not-working-solution.html

Fatal error: Call to undefined function curl_init()

do this

sudo apt-get install php-curl

and restart server

sudo service apache2 restart