Programs & Examples On #Url pattern

Giving multiple URL patterns to Servlet Filter

In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml), you can do so by just putting an array of mappings in the @WebFilter annotation:

/**
 * Filter implementation class LoginFilter
 */
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
    ...

And just as an FYI, this same thing works for servlets using the servlet annotation too:

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
    ...

What is the significance of url-pattern in web.xml and how to configure servlet?

url-pattern is used in web.xml to map your servlet to specific URL. Please see below xml code, similar code you may find in your web.xml configuration file.

<servlet>
    <servlet-name>AddPhotoServlet</servlet-name>  //servlet name
    <servlet-class>upload.AddPhotoServlet</servlet-class>  //servlet class
</servlet>
 <servlet-mapping>
    <servlet-name>AddPhotoServlet</servlet-name>   //servlet name
    <url-pattern>/AddPhotoServlet</url-pattern>  //how it should appear
</servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Java Servlet url-pattern Specification:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

Reference : Java Servlet Specification

You may also read this Basics of Java Servlet

Difference between / and /* in servlet mapping url pattern

<url-pattern>/*</url-pattern>

The /* on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /* on a Filter only. It is able to let the request continue to any of the servlets listening on a more specific URL pattern by calling FilterChain#doFilter().

<url-pattern>/</url-pattern>

The / doesn't override any other servlet. It only replaces the servletcontainer's builtin default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings. The servletcontainer's builtin default servlet is also capable of dealing with HTTP cache requests, media (audio/video) streaming and file download resumes. Usually, you don't want to override the default servlet as you would otherwise have to take care of all its tasks, which is not exactly trivial (JSF utility library OmniFaces has an open source example). This is thus also a bad URL pattern for servlets. As to why JSP pages doesn't hit this servlet, it's because the servletcontainer's builtin JSP servlet will be invoked, which is already by default mapped on the more specific URL pattern *.jsp.

<url-pattern></url-pattern>

Then there's also the empty string URL pattern . This will be invoked when the context root is requested. This is different from the <welcome-file> approach that it isn't invoked when any subfolder is requested. This is most likely the URL pattern you're actually looking for in case you want a "home page servlet". I only have to admit that I'd intuitively expect the empty string URL pattern and the slash URL pattern / be defined exactly the other way round, so I can understand that a lot of starters got confused on this. But it is what it is.

Front Controller

In case you actually intend to have a front controller servlet, then you'd best map it on a more specific URL pattern like *.html, *.do, /pages/*, /app/*, etc. You can hide away the front controller URL pattern and cover static resources on a common URL pattern like /resources/*, /static/*, etc with help of a servlet filter. See also How to prevent static resources from being handled by front controller servlet which is mapped on /*. Noted should be that Spring MVC has a builtin static resource servlet, so that's why you could map its front controller on / if you configure a common URL pattern for static resources in Spring. See also How to handle static content in Spring MVC?

Defining static const integer members in class definition

C++ allows static const members to be defined inside a class

Nope, 3.1 §2 says:

A declaration is a definition unless it declares a function without specifying the function's body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification (7.5) and neither an initializer nor a functionbody, it declares a static data member in a class definition (9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), or it is a typedef declaration (7.1.3), a using-declaration (7.3.3), or a using-directive (7.3.4).

Compare two Lists for differences

I hope that I am understing your question correctly, but you can do this very quickly with Linq. I'm assuming that universally you will always have an Id property. Just create an interface to ensure this.

If how you identify an object to be the same changes from class to class, I would recommend passing in a delegate that returns true if the two objects have the same persistent id.

Here is how to do it in Linq:

List<Employee> listA = new List<Employee>();
        List<Employee> listB = new List<Employee>();

        listA.Add(new Employee() { Id = 1, Name = "Bill" });
        listA.Add(new Employee() { Id = 2, Name = "Ted" });

        listB.Add(new Employee() { Id = 1, Name = "Bill Sr." });
        listB.Add(new Employee() { Id = 3, Name = "Jim" });

        var identicalQuery = from employeeA in listA
                             join employeeB in listB on employeeA.Id equals employeeB.Id
                             select new { EmployeeA = employeeA, EmployeeB = employeeB };

        foreach (var queryResult in identicalQuery)
        {
            Console.WriteLine(queryResult.EmployeeA.Name);
            Console.WriteLine(queryResult.EmployeeB.Name);
        }

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

In NHibernate (with NHibernate.Linq) you could do it as follows:

return session.Query<T>()
              .Single(a => a.Filter == filter &&
                           a.Id == session.Query<T>()
                                          .Where(a2 => a2.Filter == filter)
                                          .Max(a2 => a2.Id));

Which will generate SQL like follows:

select *
from TableName foo
where foo.Filter = 'Filter On String'
and foo.Id = (select cast(max(bar.RowVersion) as INT)
              from TableName bar
              where bar.Name = 'Filter On String')

Which seems pretty efficient to me.

How to stop BackgroundWorker correctly

CancelAsync doesn't actually abort your thread or anything like that. It sends a message to the worker thread that work should be cancelled via BackgroundWorker.CancellationPending. Your DoWork delegate that is being run in the background must periodically check this property and handle the cancellation itself.

The tricky part is that your DoWork delegate is probably blocking, meaning that the work you do on your DataSource must complete before you can do anything else (like check for CancellationPending). You may need to move your actual work to yet another async delegate (or maybe better yet, submit the work to the ThreadPool), and have your main worker thread poll until this inner worker thread triggers a wait state, OR it detects CancellationPending.

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync.aspx

http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx

Cannot set some HTTP headers when using System.Net.WebRequest

All the previous answers describe the problem without providing a solution. Here is an extension method which solves the problem by allowing you to set any header via its string name.

Usage

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.SetRawHeader("content-type", "application/json");

Extension Class

public static class HttpWebRequestExtensions
{
    static string[] RestrictedHeaders = new string[] {
            "Accept",
            "Connection",
            "Content-Length",
            "Content-Type",
            "Date",
            "Expect",
            "Host",
            "If-Modified-Since",
            "Keep-Alive",
            "Proxy-Connection",
            "Range",
            "Referer",
            "Transfer-Encoding",
            "User-Agent"
    };

    static Dictionary<string, PropertyInfo> HeaderProperties = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);

    static HttpWebRequestExtensions()
    {
        Type type = typeof(HttpWebRequest);
        foreach (string header in RestrictedHeaders)
        {
            string propertyName = header.Replace("-", "");
            PropertyInfo headerProperty = type.GetProperty(propertyName);
            HeaderProperties[header] = headerProperty;
        }
    }

    public static void SetRawHeader(this HttpWebRequest request, string name, string value)
    {
        if (HeaderProperties.ContainsKey(name))
        {
            PropertyInfo property = HeaderProperties[name];
            if (property.PropertyType == typeof(DateTime))
                property.SetValue(request, DateTime.Parse(value), null);
            else if (property.PropertyType == typeof(bool))
                property.SetValue(request, Boolean.Parse(value), null);
            else if (property.PropertyType == typeof(long))
                property.SetValue(request, Int64.Parse(value), null);
            else
                property.SetValue(request, value, null);
        }
        else
        {
            request.Headers[name] = value;
        }
    }
}

Scenarios

I wrote a wrapper for HttpWebRequest and didn't want to expose all 13 restricted headers as properties in my wrapper. Instead I wanted to use a simple Dictionary<string, string>.

Another example is an HTTP proxy where you need to take headers in a request and forward them to the recipient.

There are a lot of other scenarios where its just not practical or possible to use properties. Forcing the user to set the header via a property is a very inflexible design which is why reflection is needed. The up-side is that the reflection is abstracted away, it's still fast (.001 second in my tests), and as an extension method feels natural.

Notes

Header names are case insensitive per the RFC, http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2

Call a VBA Function into a Sub Procedure

To Add a Function To a new Button on your Form: (and avoid using macro to call function)

After you created your Function (Function MyFunctionName()) and you are in form design view:

  1. Add a new button (I don't think you can reassign an old button - not sure though).

  2. When the button Wizard window opens up click Cancel.

  3. Go to the Button properties Event Tab - On Click - field.

  4. At that fields drop down menu select: Event Procedure.

  5. Now click on button beside drop down menu that has ... in it and you will be taken to a new Private Sub in the forms Visual Basic window.

  6. In that Private Sub type: Call MyFunctionName
    It should look something like this:

    Private Sub Command23_Click()
    
        Call MyFunctionName
    
    End Sub
    
  7. Then just save it.

What is a callback URL in relation to an API?

Another use case could be something like OAuth, it's may not be called by the API directly, instead the callback URL will be called by the browser after completing the authencation with the identity provider.

Normally after end user key in the username password, the identity service provider will trigger a browser redirect to your "callback" url with the temporary authroization code, e.g.

https://example.com/callback?code=AUTHORIZATION_CODE

Then your application could use this authorization code to request a access token with the identity provider which has a much longer lifetime.

Efficient way to Handle ResultSet in Java

  1. Iterate over the ResultSet
  2. Create a new Object for each row, to store the fields you need
  3. Add this new object to ArrayList or Hashmap or whatever you fancy
  4. Close the ResultSet, Statement and the DB connection

Done

EDIT: now that you have posted code, I have made a few changes to it.

public List resultSetToArrayList(ResultSet rs) throws SQLException{
  ResultSetMetaData md = rs.getMetaData();
  int columns = md.getColumnCount();
  ArrayList list = new ArrayList(50);
  while (rs.next()){
     HashMap row = new HashMap(columns);
     for(int i=1; i<=columns; ++i){           
      row.put(md.getColumnName(i),rs.getObject(i));
     }
      list.add(row);
  }

 return list;
}

jQuery: Handle fallback for failed AJAX Request

Yes, it's built in to jQuery. See the docs at jquery documentation.

ajaxError may be what you want.

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

iPhone App Development on Ubuntu

With some tweaking and lots of sweat, it's probably possible to get gcc to compile your Obj-C source on Ubuntu to a binary form that will be compatible with an iPhone ARM processor. But that can't really be considered "iPhone Application development" because you won't have access to all the proprietary APIs of the iPhone (all the Cocoa stuff).

Another real problem is you need to sign your apps so that they can be made available to the app store. I know of no other tool than XCode to achieve that.

Also, you won't be able to test your code, as they is no open source iPhone simulator... maybe you might pull something off with qemu, but again, lots of effort ahead for a small result.

So you might as well buy a used mac or a Mac mini as it has been mentioned previously, you'll save yourself a lot of effort.

Selenium Finding elements by class name in python

By.CLASS_NAME was not yet mentioned:

from selenium.webdriver.common.by import By

driver.find_element(By.CLASS_NAME, "content")

This is the list of attributes which can be used as locators in By:

CLASS_NAME
CSS_SELECTOR
ID
LINK_TEXT
NAME
PARTIAL_LINK_TEXT
TAG_NAME
XPATH

setting y-axis limit in matplotlib

If an axes (generated by code below the code shown in the question) is sharing the range with the first axes, make sure that you set the range after the last plot of that axes.

Node.js server that accepts POST requests

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      console.log('Partial body: ' + body)
    })
    request.on('end', function() {
      console.log('Body: ' + body)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('post received')
    })
  } else {
    console.log('GET')
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Name: 
                        <input type="text" name="name" />
                        <input type="submit" value="Submit" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)


If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation

var express = require('express')
var fs = require('fs')
var app = express()

app.use(express.bodyParser())

app.get('/', function(request, response) {
  console.log('GET /')
  var html = `
    <html>
        <body>
            <form method="post" action="http://localhost:3000">Name: 
                <input type="text" name="name" />
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>`
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end(html)
})

app.post('/', function(request, response) {
  console.log('POST /')
  console.dir(request.body)
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end('thanks')
})

port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)

How to split an integer into an array of digits?

While list(map(int, str(x))) is the Pythonic approach, you can formulate logic to derive digits without any type conversion:

from math import log10

def digitize(x):
    n = int(log10(x))
    for i in range(n, -1, -1):
        factor = 10**i
        k = x // factor
        yield k
        x -= k * factor

res = list(digitize(5243))

[5, 2, 4, 3]

One benefit of a generator is you can feed seamlessly to set, tuple, next, etc, without any additional logic.

Find files in a folder using Java

You can use a FilenameFilter, like so:

File dir = new File(directory);

File[] matches = dir.listFiles(new FilenameFilter()
{
  public boolean accept(File dir, String name)
  {
     return name.startsWith("temp") && name.endsWith(".txt");
  }
});

How to redirect user's browser URL to a different page in Nodejs?

response.writeHead(301,
  {Location: 'http://whateverhostthiswillbe:8675/'+newRoom}
);
response.end();

How to mention C:\Program Files in batchfile

use this as somethink

"C:/Program Files (x86)/Nox/bin/nox_adb" install -r app.apk

where

"path_to_executable" commands_argument

How to prevent "The play() request was interrupted by a call to pause()" error?

I have hit this issue, and have a case where I needed to hit pause() then play() but when using pause().then() I get undefined.

I found that if I started play 150ms after pause it resolved the issue. (Hopefully Google fixes soon)

playerMP3.volume = 0;
playerMP3.pause();

//Avoid the Promise Error
setTimeout(function () {      
   playerMP3.play();
}, 150);

How to prevent errno 32 broken pipe?

This might be because you are using two method for inserting data into database and this cause the site to slow down.

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email).save()  <==== 
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

In above function, the error is where arrow is pointing. The correct implementation is below:

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email)
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

Check if a row exists, otherwise insert

I finally was able to insert a row, on the condition that it didn't already exist, using the following model:

INSERT INTO table ( column1, column2, column3 )
(
    SELECT $column1, $column2, $column3
      WHERE NOT EXISTS (
        SELECT 1
          FROM table 
          WHERE column1 = $column1
          AND column2 = $column2
          AND column3 = $column3 
    )
)

which I found at:

http://www.postgresql.org/message-id/[email protected]

Where can I get a list of Ansible pre-defined variables?

https://github.com/f500/ansible-dumpall
FYI: this github project shows you how to list 90% of variables across all hosts. I find it more globally useful than single host commands. The README includes instructions for building a simple inventory report. It's even more valuable to run this at the end of a playbook to see all the Facts. To also debug Task behaviour use register:

The result is missing a few items: - included YAML file variables - extra-vars - a number of the Ansible internal vars described here: Ansible Behavioural Params

Inline onclick JavaScript variable

Yes, JavaScript variables will exist in the scope they are created.

var bannerID = 55;

<input id="EditBanner" type="button" 
  value="Edit Image" onclick="EditBanner(bannerID);"/>


function EditBanner(id) {
   //Do something with id
}

If you use event handlers and jQuery it is simple also

$("#EditBanner").click(function() {
   EditBanner(bannerID);
});

Read pdf files with php

Not exactly php, but you could exec a program from php to convert the pdf to a temporary html file and then parse the resulting file with php. I've done something similar for a project of mine and this is the program I used:

PdfToHtml

The resulting HTML wraps text elements in < div > tags with absolute position coordinates. It seems like this is exactly what you are trying to do.

c - warning: implicit declaration of function ‘printf’

You need to include a declaration of the printf() function.

#include <stdio.h>

Seeing the underlying SQL in the Spring JdbcTemplate?

I use this line for Spring Boot applications:

logging.level.org.springframework.jdbc.core = TRACE

This approach pretty universal and I usually use it for any other classes inside my application.

Reading specific XML elements from XML file

You could use linq to xml.

    var xmlStr = File.ReadAllText("fileName.xml");


    var str = XElement.Parse(xmlStr);

    var result = str.Elements("word").
Where(x => x.Element("category").Value.Equals("verb")).ToList();

    Console.WriteLine(result);

Including dependencies in a jar with Maven

Thanks I have added below snippet in POM.xml file and Mp problem resolved and create fat jar file that include all dependent jars.

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <descriptorRefs>
                <descriptorRef>dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>
</plugins>

Clear dropdownlist with JQuery

How about storing the new options in a variable, and then using .html(variable) to replace the data in the container?

Javascript Regular Expression Remove Spaces

This works just as well: http://jsfiddle.net/maniator/ge59E/3/

var reg = new RegExp(" ","g"); //<< just look for a space.

Send form data with jquery ajax json

The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.

To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.

$.ajax({
    url: 'test.php',
    type: "POST",
    dataType: 'json',
    data: formToJson($("form")),
    contentType: 'application/json;charset=UTF-8',
    ...
})

Convert float to double without losing precision

I find converting to the binary representation easier to grasp this problem.

float f = 0.27f;
double d2 = (double) f;
double d3 = 0.27d;

System.out.println(Integer.toBinaryString(Float.floatToRawIntBits(f)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d2)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d3)));

You can see the float is expanded to the double by adding 0s to the end, but that the double representation of 0.27 is 'more accurate', hence the problem.

   111110100010100011110101110001
11111111010001010001111010111000100000000000000000000000000000
11111111010001010001111010111000010100011110101110000101001000

Google Maps API: open url by clicking on marker

url isn't an object on the Marker class. But there's nothing stopping you adding that as a property to that class. I'm guessing whatever example you were looking at did that too. Do you want a different URL for each marker? What happens when you do:

for (var i = 0; i < locations.length; i++) 
{
    var flag = new google.maps.MarkerImage('markers/' + (i + 1) + '.png',
      new google.maps.Size(17, 19),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 19));
    var place = locations[i];
    var myLatLng = new google.maps.LatLng(place[1], place[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: flag,
        shape: shape,
        title: place[0],
        zIndex: place[3],
        url: "/your/url/"
    });

    google.maps.event.addListener(marker, 'click', function() {
        window.location.href = this.url;
    });
}

Run react-native application on iOS device directly from command line?

The following worked for me (tested on react native 0.38 and 0.40):

npm install -g ios-deploy
# Run on a connected device, e.g. Max's iPhone:
react-native run-ios --device "Max's iPhone"

If you try to run run-ios, you will see that the script recommends to do npm install -g ios-deploy when it reach install step after building.

While the documentation on the various commands that react-native offers is a little sketchy, it is worth going to react-native/local-cli. There, you can see all the commands available and the code that they run - you can thus work out what switches are available for undocumented commands.

Set database from SINGLE USER mode to MULTI USER

just go to database properties and change SINGLE USER mode to MULTI USER

enter image description here

NOTE: if its not work for you then take Db backup and restore again and do above method again

* Single=SINGLE_USER

Multiple=MULTI_USER

Restricted=RESTRICTED_USER

How to detect when an Android app goes to the background and come back to the foreground

What I did is make sure that all in-app activities are launched with startActivityForResult then checking if onActivityResult was called before onResume. If it wasn't, it means we just returned from somewhere outside our app.

boolean onActivityResultCalledBeforeOnResume;

@Override
public void startActivity(Intent intent) {
    startActivityForResult(intent, 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    onActivityResultCalledBeforeOnResume = true;
}

@Override
protected void onResume() {
    super.onResume();
    if (!onActivityResultCalledBeforeOnResume) {
        // here, app was brought to foreground
    }
    onActivityResultCalledBeforeOnResume = false;
}

no overload for matches delegate 'system.eventhandler'

You need to wrap button click handler to match the pattern

public void klik(object sender, EventArgs e)

The ScriptManager must appear before any controls that need it

Just put ScriptManager inside form tag like this:

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager> 

If it has Master Page then Put this in the Master Page itself.

How do you remove Subversion control for a folder?

It worked well for me:

find directory_to_delete/ -type d -name '*.svn' | xargs rm -rf

Assigning strings to arrays of characters

Note that you can still do:

s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '\0';

What are the differences between struct and class in C++?

The only other difference is the default inheritance of classes and structs, which, unsurprisingly, is private and public respectively.

What is the difference between a token and a lexeme?

Let's see the working of a lexical analyser ( also called Scanner )

Let's take an example expression :

INPUT : cout << 3+2+3;

FORMATTING PERFORMED BY SCANNER :  {cout}|space|{<<}|space|{3}{+}{2}{+}{3}{;} 

not the actual output though .

SCANNER SIMPLY LOOKS REPEATEDLY FOR A LEXEME IN SOURCE-PROGRAM TEXT UNTIL INPUT IS EXHAUSTED

Lexeme is a substring of input that forms a valid string-of-terminals present in grammar . Every lexeme follows a pattern which is explained at the end ( the part that reader may skip at last )

( Important rule is to look for the longest possible prefix forming a valid string-of-terminals until next whitespace is encountered ... explained below )

LEXEMES :

  1. cout
  2. <<

( although "<" is also valid terminal-string but above mentioned rule shall select the pattern for lexeme "<<" in order to generate token returned by scanner )

  1. 3
  2. +
  3. 2
  4. ;

TOKENS : Tokens are returned one at a time ( by Scanner when requested by Parser ) each time Scanner finds a (valid) lexeme. Scanner creates ,if not already present, a symbol-table entry ( having attributes : mainly token-category and few others ) , when it finds a lexeme, in order to generate it's token

'#' denotes a symbol table entry . I have pointed to lexeme number in above list for ease of understanding but it technically should be actual index of record in symbol table.

The following tokens are returned by scanner to parser in specified order for above example.

  1. < identifier , #1 >

  2. < Operator , #2 >

  3. < Literal , #3 >

  4. < Operator , #4 >

  5. < Literal , #5 >

  6. < Operator , #4 >

  7. < Literal , #3 >

  8. < Punctuator , #6 >

As you can see the difference , a token is a pair unlike lexeme which is a substring of input.

And first element of the pair is the token-class/category

Token Classes are listed below:

  • KEYWORDS
  • IDENTIFIERS
  • LITERALS
  • PUNCTUATORS
  • OPERATORS
  • And one more thing , Scanner detects whitespaces , ignores them and does not form any token for a whitespace at all. Not all delimiters are whitespaces, a whitespace is one form of delimiter used by scanners for it's purpose . Tabs , Newlines , Spaces , Escaped Characters in input all are collectively called Whitespace delimiters. Few other delimiters are ';' ',' ':' etc, which are widely recognised as lexemes that form token.

    Total number of tokens returned are 8 here , however only 6 symbol table entries are made for lexemes . Lexemes are also 8 in total ( see definition of lexeme )

    --- You can skip this part

    A ***pattern*** is a rule ( say, a regular expression ) that is used to check if a string-of-terminals is valid or not.

    If a substring of input composed only of grammar terminals is following the rule specified by any of the listed patterns , it is validated as a lexeme and selected pattern will identify the category of lexeme, else a lexical error is reported due to either (i) not following any of the rules or (ii) input consists of a bad terminal-character not present in grammar itself.

    for example :
    
    1. No Pattern Exists : In C++ , "99Id_Var" is grammar-supported string-of-terminals but is not recognised by any of patterns hence lexical error is reported .
    
    2. Bad Input Character : $,@,unicode characters may not be supported as a valid character in few programming languages.`
    

    AngularJS: How to clear query parameters in the URL?

    At the time of writing, and as previously mentioned by @Bosh, html5mode must be true in order to be able to set $location.search() and have it be reflected back into the window’s visual URL.

    See https://github.com/angular/angular.js/issues/1521 for more info.

    But if html5mode is true you can easily clear the URL’s query string with:

    $location.search('');
    

    or

    $location.search({});
    

    This will also alter the window’s visual URL.

    (Tested in AngularJS version 1.3.0-rc.1 with html5Mode(true).)

    HTML to PDF with Node.js

    For those who don't want to install PhantomJS along with an instance of Chrome/Firefox on their server - or because the PhantomJS project is currently suspended, here's an alternative.

    You can externalize the conversions to APIs to do the job. Many exists and varies but what you'll get is a reliable service with up-to-date features (I'm thinking CSS3, Web fonts, SVG, Canvas compatible).

    For instance, with PDFShift (disclaimer, I'm the founder), you can do this simply by using the request package:

    const request = require('request')
    request.post(
        'https://api.pdfshift.io/v2/convert/',
        {
            'auth': {'user': 'your_api_key'},
            'json': {'source': 'https://www.google.com'},
            'encoding': null
        },
        (error, response, body) => {
            if (response === undefined) {
                return reject({'message': 'Invalid response from the server.', 'code': 0, 'response': response})
            }
            if (response.statusCode == 200) {
                // Do what you want with `body`, that contains the binary PDF
                // Like returning it to the client - or saving it as a file locally or on AWS S3
                return True
            }
    
            // Handle any errors that might have occured
        }
    );
    

    Creating Threads in python

    You can use the target argument in the Thread constructor to directly pass in a function that gets called instead of run.

    Renew Provisioning Profile

    For renew team provisioning profile managed by Xcode :

    In the organizer of Xcode :

    • Right click on your device (in the left list)
    • Click on "Add device to provisioning portal"
    • Wait until it's done !

    Upgrade to python 3.8 using conda

    You can update your python version to 3.8 in conda using the command

    conda install -c anaconda python=3.8
    

    as per https://anaconda.org/anaconda/python. Though not all packages support 3.8 yet, running

    conda update --all
    

    may resolve some dependency failures. You can also create a new environment called py38 using this command

    conda create -n py38 python=3.8
    

    Edit - note that the conda install option will potentially take a while to solve the environment, and if you try to abort this midway through you will lose your Python installation (usually this means it will resort to non-conda pre-installed system Python installation).

    Need to find a max of three numbers in java

    Two things: Change the variables x, y, z as int and call the method as Math.max(Math.max(x,y),z) as it accepts two parameters only.

    In Summary, change below:

        String x = keyboard.nextLine();
        String y = keyboard.nextLine();
        String z = keyboard.nextLine();
        int max = Math.max(x,y,z);
    

    to

        int x = keyboard.nextInt();
        int y = keyboard.nextInt();
        int z = keyboard.nextInt();
        int max =  Math.max(Math.max(x,y),z);
    

    Get names of all keys in the collection

    If you are using mongodb 3.4.4 and above then you can use below aggregation using $objectToArray and $group aggregation

    db.collection.aggregate([
      { "$project": {
        "data": { "$objectToArray": "$$ROOT" }
      }},
      { "$project": { "data": "$data.k" }},
      { "$unwind": "$data" },
      { "$group": {
        "_id": null,
        "keys": { "$addToSet": "$data" }
      }}
    ])
    

    Here is the working example

    Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

    I had this problem for days! I tried all the stuff above, but the problem kept coming back. When this message is shown it can have the meaning of "one or more projects in your solution did not compile cleanly" thus the metadata for the file was never written. But in my case, I didn't see any of the other compiler errors!!! I kept working at trying to compile each solution manually, and only after getting VS2012 to actually reveal some compiler errors I hadn't seen previously, this problem vanished.

    I fooled around with build orders, no build orders, referencing debug dlls (which were manually compiled)... NOTHING seemed to work, until I found these errors which did not show up when compiling the entire solution!!!!

    Sometimes, it seems, when compiling, that the compiler will exit on some errors... I've seen this in the past where after fixing issues, subsequent compiles show NEW errors. I don't know why it happens and it's somewhat rare for me to have these issues. However, when you do have them like this, it's a real pain in trying to find out what's going on. Good Luck!

    How to query for Xml values and attributes from table in SQL Server?

    I don't understand why some people are suggesting using cross apply or outer apply to convert the xml into a table of values. For me, that just brought back way too much data.

    Here's my example of how you'd create an xml object, then turn it into a table.

    (I've added spaces in my xml string, just to make it easier to read.)

    DECLARE @str nvarchar(2000)
    
    SET @str = ''
    SET @str = @str + '<users>'
    SET @str = @str + '  <user>'
    SET @str = @str + '     <firstName>Mike</firstName>'
    SET @str = @str + '     <lastName>Gledhill</lastName>'
    SET @str = @str + '     <age>31</age>'
    SET @str = @str + '  </user>'
    SET @str = @str + '  <user>'
    SET @str = @str + '     <firstName>Mark</firstName>'
    SET @str = @str + '     <lastName>Stevens</lastName>'
    SET @str = @str + '     <age>42</age>'
    SET @str = @str + '  </user>'
    SET @str = @str + '  <user>'
    SET @str = @str + '     <firstName>Sarah</firstName>'
    SET @str = @str + '     <lastName>Brown</lastName>'
    SET @str = @str + '     <age>23</age>'
    SET @str = @str + '  </user>'
    SET @str = @str + '</users>'
    
    DECLARE @xml xml
    SELECT @xml = CAST(CAST(@str AS VARBINARY(MAX)) AS XML) 
    
    --  Iterate through each of the "users\user" records in our XML
    SELECT 
        x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
        x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName',
        x.Rec.query('./age').value('.', 'int') AS 'Age'
    FROM @xml.nodes('/users/user') as x(Rec)
    

    And here's the output:

    enter image description here

    Postgresql GROUP_CONCAT equivalent?

    Since 9.0 this is even easier:

    SELECT id, 
           string_agg(some_column, ',')
    FROM the_table
    GROUP BY id
    

    Stacked bar chart

    You will need to melt your dataframe to get it into the so-called long format:

    require(reshape2)
    sample.data.M <- melt(sample.data)
    

    Now your field values are represented by their own rows and identified through the variable column. This can now be leveraged within the ggplot aesthetics:

    require(ggplot2)
    c <- ggplot(sample.data.M, aes(x = Rank, y = value, fill = variable))
    c + geom_bar(stat = "identity")
    

    Instead of stacking you may also be interested in showing multiple plots using facets:

    c <- ggplot(sample.data.M, aes(x = Rank, y = value))
    c + facet_wrap(~ variable) + geom_bar(stat = "identity")
    

    How to debug a stored procedure in Toad?

    Open a PL/SQL object in the Editor.

    Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.

    Compile the object on the database.

    Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor

    Select multiple columns using Entity Framework

    You either want to select an anonymous type:

    var dataset2 = from recordset 
                   in entities.processlists 
                   where recordset.ProcessName == processname 
                   select new 
                   {
                    recordset.ServerName, 
                    recordset.ProcessID, 
                    recordset.Username
                   };
    

    But you cannot cast that to another type, so I guess you want something like this:

    var dataset2 = from recordset 
                   in entities.processlists 
                   where recordset.ProcessName == processname 
    
                   // Select new concrete type
                   select new PInfo
                   {
                    ServerName = recordset.ServerName, 
                    ProcessID = recordset.ProcessID, 
                    Username = recordset.Username
                   };
    

    varbinary to string on SQL Server

    I tried this, it worked for me:

    declare @b2 VARBINARY(MAX) 
    set @b2 = 0x54006800690073002000690073002000610020007400650073007400
    SELECT CONVERT(nVARCHAR(1000), @b2, 0);
    

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

    Due to the mixed comments about BuildConfig.DEBUG, I used the following to disable crashlytics (and analytics) in debug mode :

    update /app/build.gradle

    android {
        compileSdkVersion 25
        buildToolsVersion "25.0.1"
    
        defaultConfig {
            applicationId "your.awesome.app"
            minSdkVersion 16
            targetSdkVersion 25
            versionCode 100
            versionName "1.0.0"
            buildConfigField 'boolean', 'ENABLE_CRASHLYTICS', 'true'
        }
        buildTypes {
            debug {
                debuggable true
                minifyEnabled false
                buildConfigField 'boolean', 'ENABLE_CRASHLYTICS', 'false'
            }
            release {
                debuggable false
                minifyEnabled true
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    

    then, in your code you detect the ENABLE_CRASHLYTICS flag as follows:

        if (BuildConfig.ENABLE_CRASHLYTICS)
        {
            // enable crashlytics and answers (Crashlytics by default includes Answers)
            Fabric.with(this, new Crashlytics());
        }
    

    use the same concept in your app and rename ENABLE_CRASHLYTICS to anything you want. I like this approach because I can see the flag in the configuration and I can control the flag.

    Finding element's position relative to the document

    You can use element.getBoundingClientRect() to retrieve element position relative to the viewport.

    Then use document.documentElement.scrollTop to calculate the viewport offset.

    The sum of the two will give the element position relative to the document:

    element.getBoundingClientRect().top + document.documentElement.scrollTop
    

    Get top n records for each group of grouped results

    Here is one way to do this, using UNION ALL (See SQL Fiddle with Demo). This works with two groups, if you have more than two groups, then you would need to specify the group number and add queries for each group:

    (
      select *
      from mytable 
      where `group` = 1
      order by age desc
      LIMIT 2
    )
    UNION ALL
    (
      select *
      from mytable 
      where `group` = 2
      order by age desc
      LIMIT 2
    )
    

    There are a variety of ways to do this, see this article to determine the best route for your situation:

    http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

    Edit:

    This might work for you too, it generates a row number for each record. Using an example from the link above this will return only those records with a row number of less than or equal to 2:

    select person, `group`, age
    from 
    (
       select person, `group`, age,
          (@num:=if(@group = `group`, @num +1, if(@group := `group`, 1, 1))) row_number 
      from test t
      CROSS JOIN (select @num:=0, @group:=null) c
      order by `Group`, Age desc, person
    ) as x 
    where x.row_number <= 2;
    

    See Demo

    How do I replace part of a string in PHP?

    Just do:

    $text = str_replace(' ', '_', $text)
    

    Getting the source HTML of the current page from chrome extension

    Here is my solution:

    chrome.runtime.onMessage.addListener(function(request, sender) {
            if (request.action == "getSource") {
                this.pageSource = request.source;
                var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
                alert(title)
            }
        });
    
        chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
            chrome.tabs.executeScript(
                tabs[0].id,
                { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
            );
        });
    

    Collections.emptyList() returns a List<Object>?

    You want to use:

    Collections.<String>emptyList();
    

    If you look at the source for what emptyList does you see that it actually just does a

    return (List<T>)EMPTY_LIST;
    

    How to change the color of a button?

    Through Programming:

    btn.setBackgroundColor(getResources().getColor(R.color.colorOffWhite));
    

    and your colors.xml must contain...

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
     <color name="colorOffWhite">#80ffffff</color>
    </resources>
    

    How to get first record in each group using Linq

    var result = input.GroupBy(x=>x.F1,(key,g)=>g.OrderBy(e=>e.F2).First());
    

    Clearing NSUserDefaults

    NSDictionary *defaultsDictionary = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
    for (NSString *key in [defaultsDictionary allKeys]) {
                        [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
    }
    

    Base table or view not found: 1146 Table Laravel 5

    If your error is not related to the issue of

    Laravel can't determine the plural form of the word you used for your table name.

    with this solution

    and still have this error, try my approach. you should find the problem in the default "AppServiceProvider.php" or other ServiceProviders defined for that application specifically or even in Kernel.php in App\Console

    This error happened for me and I solved it temporary and still couldn't figure out the exact origin and description.

    In my case the main problem for causing my table unable to migrate, is that I have running code/query on my "PermissionsServiceProvider.php" in the boot() method.

    In the same way, maybe, you defined something in boot() method of AppServiceProvider.php or in the Kernel.php

    So first check your Serviceproviders and disable code for a while, and run php artisan migrate and then undo changes in your code.

    How to use MapView in android using google map V2?

    I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX

    You can find complete project here: github-link

    MainActivity.kt

    class MainActivity : AppCompatActivity() {
    
    val position = LatLng(-33.920455, 18.466941)
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    
        with(mapView) {
            // Initialise the MapView
            onCreate(null)
            // Set the map ready callback to receive the GoogleMap object
            getMapAsync{
                MapsInitializer.initialize(applicationContext)
                setMapLocation(it)
            }
        }
    }
    
    private fun setMapLocation(map : GoogleMap) {
        with(map) {
            moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
            addMarker(MarkerOptions().position(position))
            mapType = GoogleMap.MAP_TYPE_NORMAL
            setOnMapClickListener {
                Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    override fun onResume() {
        super.onResume()
        mapView.onResume()
    }
    
    override fun onPause() {
        super.onPause()
        mapView.onPause()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        mapView.onDestroy()
    }
    
    override fun onLowMemory() {
        super.onLowMemory()
        mapView.onLowMemory()
     }
    }
    

    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme"
            tools:ignore="GoogleAppIndexingWarning">
        <meta-data
                android:name="com.google.android.geo.API_KEY"
                android:value="API_KEY_HERE" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
    
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
    
    </manifest>
    

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
    <com.google.android.gms.maps.MapView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:id="@+id/mapView"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"/>
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    How do I get HTTP Request body content in Laravel?

    I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.

    Looking at the class in edit #2, I would make it look like this:

    class XmlController extends Controller
    {
        public function index()
        {
            $content = Request::all();
            return Response::json($content);
        }
    }
    

    Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.

    More information on Laravel responses here:

    http://laravel.com/docs/5.0/responses

    How can I count the number of elements of a given value in a matrix?

    This is a very good function file available on Matlab Central File Exchange.

    countmember.m link

    This function file is totally vectorized and hence very quick. Plus, in comparison to the function being referred to in aioobe's answer, this function doesn't use the accumarray function, which is why this is even compatible with older versions of Matlab. Also, it works for cell arrays as well as numeric arrays.

    SOLUTION : You can use this function in conjunction with the built in matlab function, "unique".

    occurance_count = countmember(unique(M),M)

    occurance_count will be a numeric array with the same size as that of unique(M) and the different values of occurance_count array will correspond to the count of corresponding values (same index) in unique(M).

    Fast way to discover the row count of a table in PostgreSQL

    For SQL Server (2005 or above) a quick and reliable method is:

    SELECT SUM (row_count)
    FROM sys.dm_db_partition_stats
    WHERE object_id=OBJECT_ID('MyTableName')   
    AND (index_id=0 or index_id=1);
    

    Details about sys.dm_db_partition_stats are explained in MSDN

    The query adds rows from all parts of a (possibly) partitioned table.

    index_id=0 is an unordered table (Heap) and index_id=1 is an ordered table (clustered index)

    Even faster (but unreliable) methods are detailed here.

    Rename multiple files in a folder, add a prefix (Windows)

    I was tearing my hair out because for some items, the renamed item would get renamed again (repeatedly, unless max file name length was reached). This was happening both for Get-ChildItem and piping the output of dir. I guess that the renamed files got picked up because of a change in the alphabetical ordering. I solved this problem in the following way:

    Get-ChildItem -Path . -OutVariable dirs
    foreach ($i in $dirs) { Rename-Item $i.name ("<MY_PREFIX>"+$i.name) }
    

    This "locks" the results returned by Get-ChildItem in the variable $dirs and you can iterate over it without fear that ordering will change or other funny business will happen.

    Dave.Gugg's tip for using -Exclude should also solve this problem, but this is a different approach; perhaps if the files being renamed already contain the pattern used in the prefix.

    (Disclaimer: I'm very much a PowerShell n00b.)

    Why is it bad practice to call System.gc()?

    People have been doing a good job explaining why NOT to use, so I will tell you a couple situations where you should use it:

    (The following comments apply to Hotspot running on Linux with the CMS collector, where I feel confident saying that System.gc() does in fact always invoke a full garbage collection).

    1. After the initial work of starting up your application, you may be a terrible state of memory usage. Half your tenured generation could be full of garbage, meaning that you are that much closer to your first CMS. In applications where that matters, it is not a bad idea to call System.gc() to "reset" your heap to the starting state of live data.

    2. Along the same lines as #1, if you monitor your heap usage closely, you want to have an accurate reading of what your baseline memory usage is. If the first 2 minutes of your application's uptime is all initialization, your data is going to be messed up unless you force (ahem... "suggest") the full gc up front.

    3. You may have an application that is designed to never promote anything to the tenured generation while it is running. But maybe you need to initialize some data up-front that is not-so-huge as to automatically get moved to the tenured generation. Unless you call System.gc() after everything is set up, your data could sit in the new generation until the time comes for it to get promoted. All of a sudden your super-duper low-latency, low-GC application gets hit with a HUGE (relatively speaking, of course) latency penalty for promoting those objects during normal operations.

    4. It is sometimes useful to have a System.gc call available in a production application for verifying the existence of a memory leak. If you know that the set of live data at time X should exist in a certain ratio to the set of live data at time Y, then it could be useful to call System.gc() a time X and time Y and compare memory usage.

    Reading a cell value in Excel vba and write in another Cell

    The individual alphabets or symbols residing in a single cell can be inserted into different cells in different columns by the following code:

    For i = 1 To Len(Cells(1, 1))
    Cells(2, i) = Mid(Cells(1, 1), i, 1)
    Next
    

    If you do not want the symbols like colon to be inserted put an if condition in the loop.

    Use a cell value in VBA function with a variable

    VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.

    Dim val1 As Integer, val2 As Integer, i As Integer
    
    For i = 1 To 333
    
      Sheets("Feuil2").Activate
      ActiveSheet.Cells(i, 1).Select
    
        val1 = Cells(i, 1).Value
        val2 = Cells(i, 2).Value
    
    Sheets("Classeur2.csv").Select
    Cells(val1, val2).Select
    
    ActiveCell.FormulaR1C1 = "1"
    
    Next i
    

    HashMap with multiple values under the same key

    Apache Commons collection classes can implement multiple values under same key.

    MultiMap multiMapDemo = new MultiValueMap();
    
    multiMapDemo .put("fruit", "Mango");
    multiMapDemo .put("fruit", "Orange");
    multiMapDemo.put("fruit", "Blueberry");
    
    System.out.println(multiMapDemo.get("fruit"));
    

    Maven Dependency

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
    <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-collections4</artifactId>
       <version>4.4</version>
    </dependency>
    

    Convert base64 string to image

    Server side encoding files/Images to base64String ready for client side consumption

    public Optional<String> InputStreamToBase64(Optional<InputStream> inputStream) throws IOException{
        if (inputStream.isPresent()) {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            FileCopyUtils.copy(inputStream.get(), output);
            //TODO retrieve content type from file, & replace png below with it
            return Optional.ofNullable("data:image/png;base64," + DatatypeConverter.printBase64Binary(output.toByteArray()));
        }
    
        return Optional.empty();
    }
    

    Server side base64 Image/File decoder

    public Optional<InputStream> Base64InputStream(Optional<String> base64String)throws IOException {
        if (base64String.isPresent()) {
            return Optional.ofNullable(new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(base64String.get())));
        }
    
        return Optional.empty();
    }
    

    Connect to mysql in a docker container from the host

    If your Docker MySQL host is running correctly you can connect to it from local machine, but you should specify host, port and protocol like this:

    mysql -h localhost -P 3306 --protocol=tcp -u root
    

    Change 3306 to port number you have forwarded from Docker container (in your case it will be 12345).

    Because you are running MySQL inside Docker container, socket is not available and you need to connect through TCP. Setting "--protocol" in the mysql command will change that.

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

    Click on this link to see which version your BROWSER is using: http://jsfiddle.net/Ac6CT/

    You should be able filter by using script tags to each JS version.

    <script type="text/javascript">
      var jsver = 1.0;
    </script>
    <script language="Javascript1.1">
      jsver = 1.1;
    </script>
    <script language="Javascript1.2">
      jsver = 1.2;
    </script>
    <script language="Javascript1.3">
      jsver = 1.3;
    </script>
    <script language="Javascript1.4">
      jsver = 1.4;
    </script>
    <script language="Javascript1.5">
      jsver = 1.5;
    </script>
    <script language="Javascript1.6">
      jsver = 1.6;
    </script>
    <script language="Javascript1.7">
      jsver = 1.7;
    </script>
    <script language="Javascript1.8">
      jsver = 1.8;
    </script>
    <script language="Javascript1.9">
      jsver = 1.9;
    </script>
    
    <script type="text/javascript">
      alert(jsver);
    </script>
    

    My Chrome reports 1.7

    Blatantly stolen from: http://javascript.about.com/library/bljver.htm

    Fiddler not capturing traffic from browsers

    What worked for me is to reset the fiddler https certificate and recreate it.
    
    Fiddler version V4.6XXX 
    
    Fiddler menu-> Tools-> Telerick Fiddler Options... 
    Second tab- HTTPS-> Action -> Reset All Certificate
    

    enter image description here

    Once you do that, again check the check box(Decrypt HTTPS certificate)

    How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

    $('.modal') 
    .on('shown', function(){ 
      console.log('show'); 
      $('body').css({overflow: 'hidden'}); 
    }) 
    .on('hidden', function(){ 
      $('body').css({overflow: ''}); 
    }); 
    

    use this one

    How to fix "Referenced assembly does not have a strong name" error?

    To avoid this error you could either:

    • Load the assembly dynamically, or
    • Sign the third-party assembly.

    You will find instructions on signing third-party assemblies in .NET-fu: Signing an Unsigned Assembly (Without Delay Signing).

    Signing Third-Party Assemblies

    The basic principle to sign a thirp-party is to

    1. Disassemble the assembly using ildasm.exe and save the intermediate language (IL):

      ildasm /all /out=thirdPartyLib.il thirdPartyLib.dll 
      
    2. Rebuild and sign the assembly:

      ilasm /dll /key=myKey.snk thirdPartyLib.il
      

    Fixing Additional References

    The above steps work fine unless your third-party assembly (A.dll) references another library (B.dll) which also has to be signed. You can disassemble, rebuild and sign both A.dll and B.dll using the commands above, but at runtime, loading of B.dll will fail because A.dll was originally built with a reference to the unsigned version of B.dll.

    The fix to this issue is to patch the IL file generated in step 1 above. You will need to add the public key token of B.dll to the reference. You get this token by calling

    sn -Tp B.dll 
    

    which will give you the following output:

    Microsoft (R) .NET Framework Strong Name Utility  Version 4.0.30319.33440
    Copyright (c) Microsoft Corporation.  All rights reserved.
    
    Public key (hash algorithm: sha1):
    002400000480000094000000060200000024000052534131000400000100010093d86f6656eed3
    b62780466e6ba30fd15d69a3918e4bbd75d3e9ca8baa5641955c86251ce1e5a83857c7f49288eb
    4a0093b20aa9c7faae5184770108d9515905ddd82222514921fa81fff2ea565ae0e98cf66d3758
    cb8b22c8efd729821518a76427b7ca1c979caa2d78404da3d44592badc194d05bfdd29b9b8120c
    78effe92
    
    Public key token is a8a7ed7203d87bc9
    

    The last line contains the public key token. You then have to search the IL of A.dll for the reference to B.dll and add the token as follows:

    .assembly extern /*23000003*/ MyAssemblyName
    {
      .publickeytoken = (A8 A7 ED 72 03 D8 7B C9 )                         
      .ver 10:0:0:0
    }
    

    How to slice an array in Bash

    See the Parameter Expansion section in the Bash man page. A[@] returns the contents of the array, :1:2 takes a slice of length 2, starting at index 1.

    A=( foo bar "a  b c" 42 )
    B=("${A[@]:1:2}")
    C=("${A[@]:1}")       # slice to the end of the array
    echo "${B[@]}"        # bar a  b c
    echo "${B[1]}"        # a  b c
    echo "${C[@]}"        # bar a  b c 42
    echo "${C[@]: -2:2}"  # a  b c 42 # The space before the - is necesssary
    

    Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.

    How to deploy a React App on Apache web server

    Ultimately was able to figure it out , i just hope it will help someone like me.
    Following is how the web pack config file should look like check the dist dir and output file specified. I was missing the way to specify the path of dist directory

    const webpack = require('webpack');
    const path = require('path');
    var config = {
        entry: './main.js',
    
        output: {
            path: path.join(__dirname, '/dist'),
            filename: 'index.js',
        },
    
        devServer: {
            inline: true,
            port: 8080
        },
        resolveLoader: {
            modules: [path.join(__dirname, 'node_modules')]
        },
        module: {
            loaders: [
                {
                    test: /\.jsx?$/,
                    exclude: /node_modules/,
                    loader: 'babel-loader',
    
                    query: {
                        presets: ['es2015', 'react']
                    }
                }
            ]
        },
    }
    
    module.exports = config;
    

    Then the package json file

    {
      "name": "reactapp",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "start": "webpack --progress",
        "production": "webpack -p --progress"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "react": "^15.4.2",
        "react-dom": "^15.4.2",
        "webpack": "^2.2.1"
      },
      "devDependencies": {
        "babel-core": "^6.0.20",
        "babel-loader": "^6.0.1",
        "babel-preset-es2015": "^6.0.15",
        "babel-preset-react": "^6.0.15",
        "babel-preset-stage-0": "^6.0.15",
        "express": "^4.13.3",
        "webpack": "^1.9.6",
        "webpack-devserver": "0.0.6"
      }
    }
    

    Notice the script section and production section, production section is what gives you the final deployable index.js file ( name can be anything )

    Rest fot the things will depend upon your code and components

    Execute following sequence of commands

    npm install

    this should get you all the dependency (node modules)

    then

    npm run production

    this should get you the final index.js file which will contain all the code bundled

    Once done place index.html and index.js files under www/html or the web app root directory and that's all.

    CSS media queries for screen sizes

    Unless you have more style sheets than that, you've messed up your break points:

    #1 (max-width: 700px)
    #2 (min-width: 701px) and (max-width: 900px)
    #3 (max-width: 901px)
    

    The 3rd media query is probably meant to be min-width: 901px. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.

    Edit for updated question:

    (max-width: 640px)
    (max-width: 800px)
    (max-width: 1024px)
    (max-width: 1280px)
    

    Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:

    (max-width: 640px)
    (min-width: 641px) and (max-width: 800px)
    (min-width: 801px) and (max-width: 1024px)
    (min-width: 1025px)
    

    Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.

    ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

    It looks like that's an "unhandled exception", meaning the cmdlet itself hasn't been coded to recognize and handle that exception. It blew up without ever getting to run it's internal error handling, so the -ErrorAction setting on the cmdlet never came into play.

    How to open a specific port such as 9090 in Google Compute Engine

    You need to:

    1. Go to cloud.google.com

    2. Go to my Console

    3. Choose your Project

    4. Choose Networking > VPC network

    5. Choose "Firewalls rules"

    6. Choose "Create Firewall Rule"

    7. To apply the rule to select VM instances, select Targets > "Specified target tags", and enter into "Target tags" the name of the tag. This tag will be used to apply the new firewall rule onto whichever instance you'd like. Then, make sure the instances have the network tag applied.

    8. To allow incoming TCP connections to port 9090, in "Protocols and Ports" enter tcp:9090

    9. Click Create

    I hope this helps you.

    Update Please refer to docs to customize your rules.

    Convert HTML to PDF in .NET

    Last Updated: October 2020

    This is the list of options for HTML to PDF conversion in .NET that I have put together (some free some paid)

    If none of the options above help you you can always search the NuGet packages:
    https://www.nuget.org/packages?q=html+pdf

    how to modify an existing check constraint?

    Create a new constraint first and then drop the old one.
    That way you ensure that:

    • constraints are always in place
    • existing rows do not violate new constraints
    • no illegal INSERT/UPDATEs are attempted after you drop a constraint and before a new one is applied.

    How to join on multiple columns in Pyspark?

    You should use & / | operators and be careful about operator precedence (== has lower precedence than bitwise AND and OR):

    df1 = sqlContext.createDataFrame(
        [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
        ("x1", "x2", "x3"))
    
    df2 = sqlContext.createDataFrame(
        [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))
    
    df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
    df.show()
    
    ## +---+---+---+---+---+---+
    ## | x1| x2| x3| x1| x2| x3|
    ## +---+---+---+---+---+---+
    ## |  2|  b|3.0|  2|  b|0.0|
    ## +---+---+---+---+---+---+
    

    Alternative to header("Content-type: text/xml");

    Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

    Take this

    <?php
    require("database.php");
    function parseToXML($htmlStr)
    {
    $xmlStr=str_replace('<','&lt;',$htmlStr);
    $xmlStr=str_replace('>','&gt;',$xmlStr);
    $xmlStr=str_replace('"','&quot;',$xmlStr);
    $xmlStr=str_replace("'",'&#39;',$xmlStr);
    $xmlStr=str_replace("&",'&amp;',$xmlStr);
    return $xmlStr;
    }
    // Opens a connection to a MySQL server
    $connection=mysql_connect (localhost, $username, $password);
    if (!$connection) {
      die('Not connected : ' . mysql_error());
    }
    // Set the active MySQL database
    $db_selected = mysql_select_db($database, $connection);
    if (!$db_selected) {
      die ('Can\'t use db : ' . mysql_error());
    }
    // Select all the rows in the markers table
    $query = "SELECT * FROM markers WHERE 1";
    $result = mysql_query($query);
    if (!$result) {
      die('Invalid query: ' . mysql_error());
    }
    header("Content-type: text/xml");
    // Start XML file, echo parent node
    echo '<markers>';
    // Iterate through the rows, printing XML nodes for each
    while ($row = @mysql_fetch_assoc($result)){
      // ADD TO XML DOCUMENT NODE
      echo '<marker ';
      echo 'name="' . parseToXML($row['name']) . '" ';
      echo 'address="' . parseToXML($row['address']) . '" ';
      echo 'lat="' . $row['lat'] . '" ';
      echo 'lng="' . $row['lng'] . '" ';
      echo 'type="' . $row['type'] . '" ';
      echo '/>';
    }
    // End XML file
    echo '</markers>';
    ?>
    

    and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

    Select all columns except one in MySQL?

    In mysql definitions (manual) there is no such thing. But if you have a really big number of columns col1, ..., col100, the following can be useful:

    DROP TABLE IF EXISTS temp_tb;
    CREATE TEMPORARY TABLE ENGINE=MEMORY temp_tb SELECT * FROM orig_tb;
    ALTER TABLE temp_tb DROP col_x;
       #// ALTER TABLE temp_tb DROP col_a, ... , DROP col_z; #// for a few columns to drop
    SELECT * FROM temp_tb;
    

    Could not load file or assembly Exception from HRESULT: 0x80131040

    Add following dll files to bin folder:

    DotNetOpenAuth.AspNet.dll
    DotNetOpenAuth.Core.dll
    DotNetOpenAuth.OAuth.Consumer.dll
    DotNetOpenAuth.OAuth.dll
    DotNetOpenAuth.OpenId.dll
    DotNetOpenAuth.OpenId.RelyingParty.dll
    

    If you will not need them, delete dependentAssemblies from config named 'DotNetOpenAuth.Core' etc..

    fill an array in C#

    Say you want to fill with number 13.

    int[] myarr = Enumerable.Range(0, 10).Select(n => 13).ToArray();

    or

    List<int> myarr = Enumerable.Range(0,10).Select(n => 13).ToList();

    if you prefer a list.

    How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?

    To get the version of JVM currently running the program

    System.out.println(Runtime.class.getPackage().getImplementationVersion());
    

    How do I install Composer on a shared hosting?

    It depends on the host, but you probably simply can't (you can't on my shared host on Rackspace Cloud Sites - I asked them).

    What you can do is set up an environment on your dev machine that roughly matches your shared host, and do all of your management through the command line locally. Then when everything is set (you've pulled in all the dependencies, updated, managed with git, etc.) you can "push" that to your shared host over (s)FTP.

    Redirecting a request using servlets and the "setHeader" method not working

    Alternatively, you could try the following,

    resp.setStatus(301);
    resp.setHeader("Location", "index.jsp");
    resp.setHeader("Connection", "close");
    

    How can I manually generate a .pyc file from a .py file

    In Python2 you could use:

    python -m compileall <pythonic-project-name>
    

    which compiles all .py files to .pyc files in a project which contains packages as well as modules.


    In Python3 you could use:

    python3 -m compileall <pythonic-project-name>
    

    which compiles all .py files to __pycache__ folders in a project which contains packages as well as modules.

    Or with browning from this post:

    You can enforce the same layout of .pyc files in the folders as in Python2 by using:

    python3 -m compileall -b <pythonic-project-name>

    The option -b triggers the output of .pyc files to their legacy-locations (i.e. the same as in Python2).

    Run C++ in command prompt - Windows

    A better alternative to MinGW is bash for powershell. You can install bash for Windows 10 using the steps given here

    After you've installed bash, all you've got to do is run the bash command on your terminal.

    PS F:\cpp> bash
    user@HP:/mnt/f/cpp$ g++ program.cpp -o program
    user@HP:/mnt/f/cpp$ ./program
    

    Assign output of a program to a variable using a MS batch file

    @OP, you can use for loops to capture the return status of your program, if it outputs something other than numbers

    Custom fonts and XML layouts (Android)

    The only way to use custom fonts is through the source code.

    Just remember that Android runs on devices with very limited resources and fonts might require a good amount of RAM. The built-in Droid fonts are specially made and, if you note, have many characters and decorations missing.

    C# Remove object from list of objects

    First you have to find out the object in the list. Then you can remove from the list.

           var item = myList.Find(x=>x.ItemName == obj.ItemName);
           myList.Remove(item);
    

    Easiest way to use SVG in Android?

    Try the SVG2VectorDrawable Plugin. Go to Preferences->Plugins->Browse Plugins and install SVG2VectorDrawable. Great for converting sag files to vector drawable. Once you have installed you will find an icon for this in the toolbar section just to the right of the help (?) icon.

    What's the best way to center your HTML email content in the browser window (or email client preview pane)?

    Align the table to center.

    <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <td align="center">
                Your Content
            </td>
        </tr>
    </table>
    

    Where you have "your content" if it is a table, set it to the desired width and you will have centred content.

    Setting up and using Meld as your git difftool and mergetool

    For Windows. Run these commands in Git Bash:

    git config --global diff.tool meld
    git config --global difftool.meld.path "C:\Program Files (x86)\Meld\Meld.exe"
    git config --global difftool.prompt false
    
    git config --global merge.tool meld
    git config --global mergetool.meld.path "C:\Program Files (x86)\Meld\Meld.exe"
    git config --global mergetool.prompt false
    

    (Update the file path for Meld.exe if yours is different.)

    For Linux. Run these commands in Git Bash:

    git config --global diff.tool meld
    git config --global difftool.meld.path "/usr/bin/meld"
    git config --global difftool.prompt false
    
    git config --global merge.tool meld
    git config --global mergetool.meld.path "/usr/bin/meld"
    git config --global mergetool.prompt false
    

    You can verify Meld's path using this command:

    which meld
    

    Convert char array to string use C

    You're saying you have this:

    char array[20]; char string[100];
    array[0]='1'; 
    array[1]='7'; 
    array[2]='8'; 
    array[3]='.'; 
    array[4]='9';
    

    And you'd like to have this:

    string[0]= "178.9"; // where it was stored 178.9 ....in position [0]
    

    You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).

    Now if you want to copy the first x characters out of array to string you can do that with memcpy():

    memcpy(string, array, x);
    string[x] = '\0'; 
    

    How to fix broken paste clipboard in VNC on Windows

    You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.

    Combine two or more columns in a dataframe into a new column with a new name

    Some examples with NAs and their removal using apply

    n = c(2, NA, NA) 
    s = c("aa", "bb", NA) 
    b = c(TRUE, FALSE, NA) 
    c = c(2, 3, 5) 
    d = c("aa", NA, "cc") 
    e = c(TRUE, NA, TRUE) 
    df = data.frame(n, s, b, c, d, e)
    
    paste_noNA <- function(x,sep=", ") {
    gsub(", " ,sep, toString(x[!is.na(x) & x!="" & x!="NA"] ) ) }
    
    sep=" "
    df$x <- apply( df[ , c(1:6) ] , 1 , paste_noNA , sep=sep)
    df
    

    HTTP 1.0 vs 1.1

    Proxy support and the Host field:

    HTTP 1.1 has a required Host header by spec.

    HTTP 1.0 does not officially require a Host header, but it doesn't hurt to add one, and many applications (proxies) expect to see the Host header regardless of the protocol version.

    Example:

    GET / HTTP/1.1
    Host: www.blahblahblahblah.com
    

    This header is useful because it allows you to route a message through proxy servers, and also because your web server can distinguish between different sites on the same server.

    So this means if you have blahblahlbah.com and helohelohelo.com both pointing to the same IP. Your web server can use the Host field to distinguish which site the client machine wants.

    Persistent connections:

    HTTP 1.1 also allows you to have persistent connections which means that you can have more than one request/response on the same HTTP connection.

    In HTTP 1.0 you had to open a new connection for each request/response pair. And after each response the connection would be closed. This lead to some big efficiency problems because of TCP Slow Start.

    OPTIONS method:

    HTTP/1.1 introduces the OPTIONS method. An HTTP client can use this method to determine the abilities of the HTTP server. It's mostly used for Cross Origin Resource Sharing in web applications.

    Caching:

    HTTP 1.0 had support for caching via the header: If-Modified-Since.

    HTTP 1.1 expands on the caching support a lot by using something called 'entity tag'. If 2 resources are the same, then they will have the same entity tags.

    HTTP 1.1 also adds the If-Unmodified-Since, If-Match, If-None-Match conditional headers.

    There are also further additions relating to caching like the Cache-Control header.

    100 Continue status:

    There is a new return code in HTTP/1.1 100 Continue. This is to prevent a client from sending a large request when that client is not even sure if the server can process the request, or is authorized to process the request. In this case the client sends only the headers, and the server will tell the client 100 Continue, go ahead with the body.

    Much more:

    • Digest authentication and proxy authentication
    • Extra new status codes
    • Chunked transfer encoding
    • Connection header
    • Enhanced compression support
    • Much much more.

    Get WooCommerce product categories from WordPress

    In my opinion this is the simplest solution

    $orderby = 'name';
                    $order = 'asc';
                    $hide_empty = false ;
                    $cat_args = array(
                        'orderby'    => $orderby,
                        'order'      => $order,
                        'hide_empty' => $hide_empty,
                    );
    
                    $product_categories = get_terms( 'product_cat', $cat_args );
    
                    if( !empty($product_categories) ){
                        echo '
    
                    <ul>';
                        foreach ($product_categories as $key => $category) {
                            echo '
    
                    <li>';
                            echo '<a href="'.get_term_link($category).'" >';
                            echo $category->name;
                            echo '</a>';
                            echo '</li>';
                        }
                        echo '</ul>
    
    
                    ';
                    }
    

    ASP.NET GridView RowIndex As CommandArgument

    void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        Button b = (Button)e.CommandSource;
        b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
    }
    

    center MessageBox in parent form

    Surely using your own panel or form would be by far the simplest approach if a little more heavy on the background (designer) code. It gives all the control in terms of centring and manipulation without writing all that custom code.

    'Operation is not valid due to the current state of the object' error during postback

    Somebody posted quite a few form fields to your page. The new default max introduced by the recent security update is 1000.

    Try adding the following setting in your web.config's <appsettings> block. in this block you are maximizing the MaxHttpCollection values this will override the defaults set by .net Framework. you can change the value accordingly as per your form needs

    <appSettings>
        <add key="aspnet:MaxHttpCollectionKeys" value="2001" />
     </appSettings>
    

    For more information please read this post. For more insight into the security patch by microsoft you can read this Knowledge base article

    Difference between webdriver.Dispose(), .Close() and .Quit()

    Selenium WebDriver

    1. WebDriver.Close() This method is used to close the current open window. It closes the current open window on which driver has focus on.

    2. WebDriver.Quit() This method is used to destroy the instance of WebDriver. It closes all Browser Windows associated with that driver and safely ends the session. WebDriver.Quit() calls Dispose.

    3. WebDriver.Dispose() This method closes all Browser windows and safely ends the session

    What's the "Content-Length" field in HTTP header?

    From this page

    The most common use of POST, by far, is to submit HTML form data to CGI scripts. In this case, the Content-Type: header is usually application/x-www-form-urlencoded, and the Content-Length: header gives the length of the URL-encoded form data (here's a note on URL-encoding). The CGI script receives the message body through STDIN, and decodes it. Here's a typical form submission, using POST:

    POST /path/script.cgi HTTP/1.0
    From: [email protected]
    User-Agent: HTTPTool/1.0
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 32
    

    What happened to Lodash _.pluck?

    There isn't a need for _.map or _.pluck since ES6 has taken off.

    Here's an alternative using ES6 JavaScript:

    clips.map(clip => clip.id)

    I can't understand why this JAXB IllegalAnnotationException is thrown

    I once received this message after thinking that putting @XmlTransient on a field I didn't need to serialize, in a class that was annotated with @XmlAccessorType(XmlAccessType.NONE).

    In that case, removing XmlTransient resolved the issue. I am not a JAXB expert, but I suspect that because AccessType.NONE indicates that no auto-serialization should be done (i.e. fields must be specifically annotated to serialize them) that makes XmlTransient illegal since its sole purpose is to exclude a field from auto-serialization.

    Excel is not updating cells, options > formula > workbook calculation set to automatic

    I had this happen in a worksheet today. Neither F9 nor turning on Iterative Calculation made the cells in question update, but double-clicking the cell and pressing Enter did. I searched the Excel Help and found this in the help article titled Change formula recalculation, iteration, or precision:

    CtrlAltF9:
    Recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.

    CtrlShiftAltF9:
    Check dependent formulas, and then recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.

    So I tried CtrlShiftAltF9, and sure enough, all of my non-recalculating formulas finally recalculated!

    How can I refresh c# dataGridView after update ?

    Rebind your DatagridView to the source.

    DataGridView dg1 = new DataGridView();
    dg1.DataSource = src1;
    
    // Update Data in src1
    
    dg1.DataSource = null;
    dg1.DataSource = src1;
    

    The equivalent of wrap_content and match_parent in flutter?

    To make a child fill its parent, simply wrap it into a FittedBox

        FittedBox(
         child: Image.asset('foo.png'),
         fit: BoxFit.fill,
       )
    

    Try/catch does not seem to have an effect

    I was able to duplicate your result when trying to run a remote WMI query. The exception thrown is not caught by the Try/Catch, nor will a Trap catch it, since it is not a "terminating error". In PowerShell, there are terminating errors and non-terminating errors . It appears that Try/Catch/Finally and Trap only works with terminating errors.

    It is logged to the $error automatic variable and you can test for these type of non-terminating errors by looking at the $? automatic variable, which will let you know if the last operation succeeded ($true) or failed ($false).

    From the appearance of the error generated, it appears that the error is returned and not wrapped in a catchable exception. Below is a trace of the error generated.

    PS C:\scripts\PowerShell> Trace-Command -Name errorrecord  -Expression {Get-WmiObject win32_bios -ComputerName HostThatIsNotThere}  -PSHost
    DEBUG: InternalCommand Information: 0 :  Constructor Enter Ctor
    Microsoft.PowerShell.Commands.GetWmiObjectCommand: 25857563
    DEBUG: InternalCommand Information: 0 :  Constructor Leave Ctor
    Microsoft.PowerShell.Commands.GetWmiObjectCommand: 25857563
    DEBUG: ErrorRecord Information: 0 :  Constructor Enter Ctor
    System.Management.Automation.ErrorRecord: 19621801 exception =
    System.Runtime.InteropServices.COMException (0x800706BA): The RPC
    server is unavailable. (Exception from HRESULT: 0x800706BA)
       at
    System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
       at System.Management.ManagementScope.InitializeGuts(Object o)
       at System.Management.ManagementScope.Initialize()
       at System.Management.ManagementObjectSearcher.Initialize()
       at System.Management.ManagementObjectSearcher.Get()
       at Microsoft.PowerShell.Commands.GetWmiObjectCommand.BeginProcessing()
    errorId = GetWMICOMException errorCategory = InvalidOperation
    targetObject =
    DEBUG: ErrorRecord Information: 0 :  Constructor Leave Ctor
    System.Management.Automation.ErrorRecord: 19621801
    

    A work around for your code could be:

    try
    {
        $colItems = get-wmiobject -class "Win32_PhysicalMemory" -namespace "root\CIMV2" -computername $strComputerName -Credential $credentials
        if ($?)
        {
          foreach ($objItem in $colItems) 
          {
              write-host "Bank Label: " $objItem.BankLabel
              write-host "Capacity: " ($objItem.Capacity / 1024 / 1024)
              write-host "Caption: " $objItem.Caption
              write-host "Creation Class Name: " $objItem.CreationClassName      
              write-host
          }
        }
        else
        {
           throw $error[0].Exception
        }
    

    Get characters after last / in url

    Here's a beautiful dynamic function I wrote to remove last part of url or path.

    /**
     * remove the last directories
     *
     * @param $path the path
     * @param $level number of directories to remove
     *
     * @return string
     */
    private function removeLastDir($path, $level)
    {
        if(is_int($level) && $level > 0){
            $path = preg_replace('#\/[^/]*$#', '', $path);
            return $this->removeLastDir($path, (int) $level - 1);
        }
        return $path;
    }
    

    How to send parameters with jquery $.get()

    This is what worked for me:

    $.get({
        method: 'GET',
        url: 'api.php',
        headers: {
            'Content-Type': 'application/json',
        },
        // query parameters go under "data" as an Object
        data: {
            client: 'mikescafe'
        }
    });
    

    will make a REST/AJAX call - > GET http://localhost:3000/api.php?client=mikescafe

    Good Luck.

    How to change the font size on a matplotlib plot

    Here is a totally different approach that works surprisingly well to change the font sizes:

    Change the figure size!

    I usually use code like this:

    import matplotlib.pyplot as plt
    import numpy as np
    fig = plt.figure(figsize=(4,3))
    ax = fig.add_subplot(111)
    x = np.linspace(0,6.28,21)
    ax.plot(x, np.sin(x), '-^', label="1 Hz")
    ax.set_title("Oscillator Output")
    ax.set_xlabel("Time (s)")
    ax.set_ylabel("Output (V)")
    ax.grid(True)
    ax.legend(loc=1)
    fig.savefig('Basic.png', dpi=300)
    

    The smaller you make the figure size, the larger the font is relative to the plot. This also upscales the markers. Note I also set the dpi or dot per inch. I learned this from a posting the AMTA (American Modeling Teacher of America) forum. Example from above code: enter image description here

    What does "xmlns" in XML mean?

    It defines an XML Namespace.

    In your example, the Namespace Prefix is "android" and the Namespace URI is "http://schemas.android.com/apk/res/android"

    In the document, you see elements like: <android:foo />

    Think of the namespace prefix as a variable with a short name alias for the full namespace URI. It is the equivalent of writing <http://schemas.android.com/apk/res/android:foo /> with regards to what it "means" when an XML parser reads the document.

    NOTE: You cannot actually use the full namespace URI in place of the namespace prefix in an XML instance document.

    Check out this tutorial on namespaces: http://www.sitepoint.com/xml-namespaces-explained/

    Not showing placeholder for input type="date" field

    You can

    1. set it as type text
    2. convert to date on focus
    3. make click on it
    4. ...let user check date
    5. on change store the value
    6. set input to type text
    7. set text type input value to the stored value

    like this...

    _x000D_
    _x000D_
    $("#dateplaceholder").change(function(evt) {_x000D_
      var date = new Date($("#dateplaceholder").val());_x000D_
      $("#dateplaceholder").attr("type", "text");_x000D_
      $("#dateplaceholder").val(date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear());_x000D_
    });_x000D_
    $("#dateplaceholder").focus(function(evt) {_x000D_
      $("#dateplaceholder").attr("type", "date");_x000D_
      setTimeout('$("#dateplaceholder").click();', 500);_x000D_
    });_x000D_
    $("#dateplaceholder").attr("type", "text");
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>_x000D_
    <input type="date" id="dateplaceholder" placeholder="Set the date" />
    _x000D_
    _x000D_
    _x000D_

    adb command not found in linux environment

    Make sure you installed sudo apt-get install android-tools-adb Now check sudo adb It will show help of adb

    Now please kill/start adb use following commands -

    sudo adb kill-server sudo adb start-server

    Lastly, sudo adb devices

    Hopefully this will work !!!

    Where does one get the "sys/socket.h" header/source file?

    Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).

    This library files should be under cygwin\usr\include

    Regards.

    Visual Studio 2017 - Git failed with a fatal error

    I once had such an error from Git while I was trying to synchronise a repository (I tried to send my commits while having pending changes from my coworker):

    Git failed with a fatal error. pull --verbose --progress --no-edit --no-stat --recurse-submodules=no origin

    It turned out that after pressing the Commit all button to create a local commit, Visual Studio had left one file uncommitted and this elaborated error message actually meant: "Commit all your changes".

    That missing file was Entity Framework 6 model, and it is often shown as uncommitted file although you haven't changed a thing in it.

    You can do commit all or undo all changes that are not committed.

    Two Decimal places using c#

    here is another approach

    decimal decimalRounded = Decimal.Parse(Debitvalue.ToString("0.00"));
    

    How to build & install GLFW 3 and use it in a Linux project

    Great guide, thank you. Given most instructions here, it almost built for me but I did have one remaining error.

    /usr/bin/ld: //usr/local/lib/libglfw3.a(glx_context.c.o): undefined reference to symbol 'dlclose@@GLIBC_2.2.5'
    //lib/x86_64-linux-gnu/libdl.so.2: error adding symbols: DSO missing from command line
    collect2: error: ld returned 1 exit status
    

    After searching for this error, I had to add -ldl to the command line.

    g++ main.cpp -lglfw3 -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -lGL -lpthread -ldl
    

    Then the "hello GLFW" sample app compiled and linked.

    I am pretty new to linux so I am not completely certain what exactly this extra library does... other than fix my linking error. I do see that cmd line switch in the post above, however.

    Why is <deny users="?" /> included in the following example?

    Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.

    Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.

    Export table from database to csv file

    I wrote a small tool that does just that. Code is available on github.

    To dump the results of one (or more) SQL queries to one (or more) CSV files:

    java -jar sql_dumper.jar /path/sql/files/ /path/out/ user pass jdbcString
    

    Cheers.

    How to generate random number in Bash?

    What about:

    perl -e 'print int rand 10, "\n"; '
    

    When is assembly faster than C?

    In my job, there are three reasons for me to know and use assembly. In order of importance:

    1. Debugging - I often get library code that has bugs or incomplete documentation. I figure out what it's doing by stepping in at the assembly level. I have to do this about once a week. I also use it as a tool to debug problems in which my eyes don't spot the idiomatic error in C/C++/C#. Looking at the assembly gets past that.

    2. Optimizing - the compiler does fairly well in optimizing, but I play in a different ballpark than most. I write image processing code that usually starts with code that looks like this:

      for (int y=0; y < imageHeight; y++) {
          for (int x=0; x < imageWidth; x++) {
             // do something
          }
      }
      

      the "do something part" typically happens on the order of several million times (ie, between 3 and 30). By scraping cycles in that "do something" phase, the performance gains are hugely magnified. I don't usually start there - I usually start by writing the code to work first, then do my best to refactor the C to be naturally better (better algorithm, less load in the loop etc). I usually need to read assembly to see what's going on and rarely need to write it. I do this maybe every two or three months.

    3. doing something the language won't let me. These include - getting the processor architecture and specific processor features, accessing flags not in the CPU (man, I really wish C gave you access to the carry flag), etc. I do this maybe once a year or two years.

    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.)

    Complex nesting of partials and templates

    Well, since you can currently only have one ngView directive... I use nested directive controls. This allows you to set up templating and inherit (or isolate) scopes among them. Outside of that I use ng-switch or even just ng-show to choose which controls I'm displaying based on what's coming in from $routeParams.

    EDIT Here's some example pseudo-code to give you an idea of what I'm talking about. With a nested sub navigation.

    Here's the main app page

    <!-- primary nav -->
    <a href="#/page/1">Page 1</a>
    <a href="#/page/2">Page 2</a>
    <a href="#/page/3">Page 3</a>
    
    <!-- display the view -->
    <div ng-view>
    </div>
    

    Directive for the sub navigation

    app.directive('mySubNav', function(){
        return {
            restrict: 'E',
            scope: {
               current: '=current'
            },
            templateUrl: 'mySubNav.html',
            controller: function($scope) {
            }
        };
    });
    

    template for the sub navigation

    <a href="#/page/1/sub/1">Sub Item 1</a>
    <a href="#/page/1/sub/2">Sub Item 2</a>
    <a href="#/page/1/sub/3">Sub Item 3</a>
    

    template for a main page (from primary nav)

    <my-sub-nav current="sub"></my-sub-nav>
    
    <ng-switch on="sub">
      <div ng-switch-when="1">
          <my-sub-area1></my-sub-area>
      </div>
      <div ng-switch-when="2">
          <my-sub-area2></my-sub-area>
      </div>
      <div ng-switch-when="3">
          <my-sub-area3></my-sub-area>
      </div>
    </ng-switch>
    

    Controller for a main page. (from the primary nav)

    app.controller('page1Ctrl', function($scope, $routeParams) {
         $scope.sub = $routeParams.sub;
    });
    

    Directive for a Sub Area

    app.directive('mySubArea1', function(){
        return {
            restrict: 'E',
            templateUrl: 'mySubArea1.html',
            controller: function($scope) {
                //controller for your sub area.
            }
        };
    });
    

    How do I check OS with a preprocessor directive?

    Use #define OSsymbol and #ifdef OSsymbol where OSsymbol is a #define'able symbol identifying your target OS.

    Typically you would include a central header file defining the selected OS symbol and use OS-specific include and library directories to compile and build.

    You did not specify your development environment, but I'm pretty sure your compiler provides global defines for common platforms and OSes.

    See also http://en.wikibooks.org/wiki/C_Programming/Preprocessor

    What is correct media query for IPad Pro?

    This worked for me

    /* Portrait */
    @media only screen 
      and (min-device-width: 834px) 
      and (max-device-width: 834px) 
      and (orientation: portrait) 
      and (-webkit-min-device-pixel-ratio: 2) {
    
    }
    
    /* Landscape */
    @media only screen 
      and (min-width: 1112px) 
      and (max-width: 1112px) 
      and (orientation: landscape) 
      and (-webkit-min-device-pixel-ratio: 2)
     {
    
    }
    

    Handle JSON Decode Error when nothing returned

    If you don't mind importing the json module, then the best way to handle it is through json.JSONDecodeError (or json.decoder.JSONDecodeError as they are the same) as using default errors like ValueError could catch also other exceptions not necessarily connected to the json decode one.

    from json.decoder import JSONDecodeError
    
    
    try:
        qByUser = byUsrUrlObj.read()
        qUserData = json.loads(qByUser).decode('utf-8')
        questionSubjs = qUserData["all"]["questions"]
    except JSONDecodeError as e:
        # do whatever you want
    

    //EDIT (Oct 2020):

    As @Jacob Lee noted in the comment, there could be the basic common TypeError raised when the JSON object is not a str, bytes, or bytearray. Your question is about JSONDecodeError, but still it is worth mentioning here as a note; to handle also this situation, but differentiate between different issues, the following could be used:

    from json.decoder import JSONDecodeError
    
    
    try:
        qByUser = byUsrUrlObj.read()
        qUserData = json.loads(qByUser).decode('utf-8')
        questionSubjs = qUserData["all"]["questions"]
    except JSONDecodeError as e:
        # do whatever you want
    except TypeError as e:
        # do whatever you want in this case
    

    How to use awk sort by column 3

    awk -F "," '{print $0}' user.csv | sort -nk3 -t ','
    

    This should work

    How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

    I was able to get this to work thanks to this post utilizing VisualWGet. It worked great for me. The important part seems to be to check the -recursive flag (see image).

    Also found that the -no-parent flag is important, othewise it will try to download everything.

    enter image description here enter image description here

    Get all object attributes in Python?

    What you probably want is dir().

    The catch is that classes are able to override the special __dir__ method, which causes dir() to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding __getattr__, may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a __dict__ or be able to provide a comprehensive list of attributes via __dir__: many of these objects may have so many dynamic attrs it doesn't won't actually know what it has until you try to access it.

    In the short run, if dir() isn't sufficient, you could write a function which traverses __dict__ for an object, then __dict__ for all the classes in obj.__class__.__mro__; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions - if it looks like a duck, cross your fingers, and hope it has .feathers.

    OpenSSL: unable to verify the first certificate for Experian URL

    Adding additional information to emboss's answer.

    To put it simply, there is an incorrect cert in your certificate chain.

    For example, your certificate authority will have most likely given you 3 files.

    • your_domain_name.crt
    • DigiCertCA.crt # (Or whatever the name of your certificate authority is)
    • TrustedRoot.crt

    You most likely combined all of these files into one bundle.

    -----BEGIN CERTIFICATE----- 
    (Your Primary SSL certificate: your_domain_name.crt) 
    -----END CERTIFICATE----- 
    -----BEGIN CERTIFICATE----- 
    (Your Intermediate certificate: DigiCertCA.crt) 
    -----END CERTIFICATE----- 
    -----BEGIN CERTIFICATE----- 
    (Your Root certificate: TrustedRoot.crt) 
    -----END CERTIFICATE-----
    

    If you create the bundle, but use an old, or an incorrect version of your Intermediate Cert (DigiCertCA.crt in my example), you will get the exact symptoms you are describing.

    Redownload all certs from your certificate authority and make a fresh bundle.

    How do I express "if value is not empty" in the VBA language?

    Try this:

    If Len(vValue & vbNullString) > 0 Then
      ' we have a non-Null and non-empty String value
      doSomething()
    Else
      ' We have a Null or empty string value
      doSomethingElse()
    End If
    

    How do I set the timeout for a JAX-WS webservice client?

    Here is my working solution :

    // --------------------------
    // SOAP Message creation
    // --------------------------
    SOAPMessage sm = MessageFactory.newInstance().createMessage();
    sm.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
    sm.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
    
    SOAPPart sp = sm.getSOAPPart();
    SOAPEnvelope se = sp.getEnvelope();
    se.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
    se.setAttribute("xmlns:SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/");
    se.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
    se.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    
    SOAPBody sb = sm.getSOAPBody();
    // 
    // Add all input fields here ...
    // 
    
    SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
    // -----------------------------------
    // URL creation with TimeOut connexion
    // -----------------------------------
    URL endpoint = new URL(null,
                          "http://myDomain/myWebService.php",
                        new URLStreamHandler() { // Anonymous (inline) class
                        @Override
                        protected URLConnection openConnection(URL url) throws IOException {
                        URL clone_url = new URL(url.toString());
                        HttpURLConnection clone_urlconnection = (HttpURLConnection) clone_url.openConnection();
                        // TimeOut settings
                        clone_urlconnection.setConnectTimeout(10000);
                        clone_urlconnection.setReadTimeout(10000);
                        return(clone_urlconnection);
                        }
                    });
    
    
    try {
        // -----------------
        // Send SOAP message
        // -----------------
        SOAPMessage retour = connection.call(sm, endpoint);
    }
    catch(Exception e) {
        if ((e instanceof com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl) && (e.getCause()!=null) && (e.getCause().getCause()!=null) && (e.getCause().getCause().getCause()!=null)) {
            System.err.println("[" + e + "] Error sending SOAP message. Initial error cause = " + e.getCause().getCause().getCause());
        }
        else {
            System.err.println("[" + e + "] Error sending SOAP message.");
    
        }
    }
    

    Issue in installing php7.2-mcrypt

    Mcrypt PECL extenstion

     sudo apt-get -y install gcc make autoconf libc-dev pkg-config
     sudo apt-get -y install libmcrypt-dev
     sudo pecl install mcrypt-1.0.1
    

    When you are shown the prompt

     libmcrypt prefix? [autodetect] :
    

    Press [Enter] to autodetect.

    After success installing mcrypt trought pecl, you should add mcrypt.so extension to php.ini.

    The output will look like this:

    ...
    Build process completed successfully
    Installing '/usr/lib/php/20170718/mcrypt.so'    ---->   this is our path to mcrypt extension lib
    install ok: channel://pecl.php.net/mcrypt-1.0.1
    configuration option "php_ini" is not set to php.ini location
    You should add "extension=mcrypt.so" to php.ini
    

    Grab installing path and add to cli and apache2 php.ini configuration.

    sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/cli/conf.d/mcrypt.ini"
    sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/apache2/conf.d/mcrypt.ini"
    

    Verify that the extension was installed

    Run command:

    php -i | grep "mcrypt"
    

    The output will look like this:

    /etc/php/7.2/cli/conf.d/mcrypt.ini
    Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
    mcrypt
    mcrypt support => enabled
    mcrypt_filter support => enabled
    mcrypt.algorithms_dir => no value => no value
    mcrypt.modes_dir => no value => no value
    

    Xcode process launch failed: Security

    Hey so the accepted answer works, except if you need to debug the initial launch of the app. However I think that answer is more of a work around, and not an actual solution. From my understanding this message occurs when you have some weirdness in your provisioning profile / cert setup so make extra sure everything is in tip-top shape in that dept. before ramming your head against the wall repeatedly.

    What worked for me was as follows from the apple docs:

    Provisioning Profiles Known Issue If you have upgraded to the GM seed from other betas you may see your apps crashing due to provisioning profile issues.

    Workaround:

    1. Connect the device via USB to your Mac

    2. Launch Xcode Choose Window ->Devices

    3. Right click on the device in left column, choose "Show Provisioning Profiles"

    4. Click on the provisioning profile in question

    5. Press the "-" button Continue to removing all affected profiles.

    6. Re-install the app

    Make sure you right click on the image of the device not the name of the device or you won't see the provisioning profiles option. I restored my new phone from an old backup and there was a lot of cruft hanging around, i also had 2 different dev. certs active (not sure why) but i deleted one, made a new profile got rid of all the profiles on device and it worked.

    Hope this helps someone else.

    Execute external program

    This is not right. Here's how you should use Runtime.exec(). You might also try its more modern cousin, ProcessBuilder:

    Java Runtime.getRuntime().exec() alternatives

    Can we instantiate an abstract class?

    The above instantiates an anonymous inner class which is a subclass of the my abstract class. It's not strictly equivalent to instantiating the abstract class itself. OTOH, every subclass instance is an instance of all its super classes and interfaces, so most abstract classes are indeed instantiated by instantiating one of their concrete subclasses.

    If the interviewer just said "wrong!" without explaining, and gave this example, as a unique counterexample, I think he doesn't know what he's talking about, though.

    Deserialize JSON string to c# object

    Use this code:

    var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);
    

    Icons missing in jQuery UI

    I met a similar error after adding jQuery-ui-tooltip component using bower. It downloads js + css files only, so I had to manually add images.

    A good source to find all the images (for all standard themes) is this CDN.

    Python Sets vs Lists

    I would recommend a Set implementation where the use case is limit to referencing or search for existence and Tuple implementation where the use case requires you to perform iteration. A list is a low-level implementation and requires significant memory overhead.

    Sleep function in C++

    The simplest way I found for C++ 11 was this:

    Your includes:

    #include <chrono>
    #include <thread>
    

    Your code (this is an example for sleep 1000 millisecond):

    std::chrono::duration<int, std::milli> timespan(1000);
    std::this_thread::sleep_for(timespan);
    

    The duration could be configured to any of the following:

    std::chrono::nanoseconds   duration</*signed integer type of at least 64 bits*/, std::nano>
    std::chrono::microseconds  duration</*signed integer type of at least 55 bits*/, std::micro>
    std::chrono::milliseconds  duration</*signed integer type of at least 45 bits*/, std::milli>
    std::chrono::seconds       duration</*signed integer type of at least 35 bits*/, std::ratio<1>>  
    std::chrono::minutes       duration</*signed integer type of at least 29 bits*/, std::ratio<60>>
    std::chrono::hours         duration</*signed integer type of at least 23 bits*/, std::ratio<3600>>
    

    Why does one use dependency injection?

    As the other answers stated, dependency injection is a way to create your dependencies outside of the class that uses it. You inject them from the outside, and take control about their creation away from the inside of your class. This is also why dependency injection is a realization of the Inversion of control (IoC) principle.

    IoC is the principle, where DI is the pattern. The reason that you might "need more than one logger" is never actually met, as far as my experience goes, but the actualy reason is, that you really need it, whenever you test something. An example:

    My Feature:

    When I look at an offer, I want to mark that I looked at it automatically, so that I don't forget to do so.

    You might test this like this:

    [Test]
    public void ShouldUpdateTimeStamp
    {
        // Arrange
        var formdata = { . . . }
    
        // System under Test
        var weasel = new OfferWeasel();
    
        // Act
        var offer = weasel.Create(formdata)
    
        // Assert
        offer.LastUpdated.Should().Be(new DateTime(2013,01,13,13,01,0,0));
    }
    

    So somewhere in the OfferWeasel, it builds you an offer Object like this:

    public class OfferWeasel
    {
        public Offer Create(Formdata formdata)
        {
            var offer = new Offer();
            offer.LastUpdated = DateTime.Now;
            return offer;
        }
    }
    

    The problem here is, that this test will most likely always fail, since the date that is being set will differ from the date being asserted, even if you just put DateTime.Now in the test code it might be off by a couple of milliseconds and will therefore always fail. A better solution now would be to create an interface for this, that allows you to control what time will be set:

    public interface IGotTheTime
    {
        DateTime Now {get;}
    }
    
    public class CannedTime : IGotTheTime
    {
        public DateTime Now {get; set;}
    }
    
    public class ActualTime : IGotTheTime
    {
        public DateTime Now {get { return DateTime.Now; }}
    }
    
    public class OfferWeasel
    {
        private readonly IGotTheTime _time;
    
        public OfferWeasel(IGotTheTime time)
        {
            _time = time;
        }
    
        public Offer Create(Formdata formdata)
        {
            var offer = new Offer();
            offer.LastUpdated = _time.Now;
            return offer;
        }
    }
    

    The Interface is the abstraction. One is the REAL thing, and the other one allows you to fake some time where it is needed. The test can then be changed like this:

    [Test]
    public void ShouldUpdateTimeStamp
    {
        // Arrange
        var date = new DateTime(2013, 01, 13, 13, 01, 0, 0);
        var formdata = { . . . }
    
        var time = new CannedTime { Now = date };
    
        // System under test
        var weasel= new OfferWeasel(time);
    
        // Act
        var offer = weasel.Create(formdata)
    
        // Assert
        offer.LastUpdated.Should().Be(date);
    }
    

    Like this, you applied the "inversion of control" principle, by injecting a dependency (getting the current time). The main reason to do this is for easier isolated unit testing, there are other ways of doing it. For example, an interface and a class here is unnecessary since in C# functions can be passed around as variables, so instead of an interface you could use a Func<DateTime> to achieve the same. Or, if you take a dynamic approach, you just pass any object that has the equivalent method (duck typing), and you don't need an interface at all.

    You will hardly ever need more than one logger. Nonetheless, dependency injection is essential for statically typed code such as Java or C#.

    And... It should also be noted that an object can only properly fulfill its purpose at runtime, if all its dependencies are available, so there is not much use in setting up property injection. In my opinion, all dependencies should be satisfied when the constructor is being called, so constructor-injection is the thing to go with.

    I hope that helped.

    Execute command without keeping it in history

    Start your command with a space and it won't be included in the history.

    Be aware that this does require the environment variable $HISTCONTROL to be set.

    • Check that the following command returns ignorespace or ignoreboth

      #> echo $HISTCONTROL
      
    • To add the environment variable if missing, the following line can be added to the bash profile. E.g. %HOME/.bashrc

      export HISTCONTROL=ignorespace
      

    After sourcing the profile again space prefixed commands will not be written to $HISTFILE

    Python: pandas merge multiple dataframes

    If you are filtering by common date this will return it:

    dfs = [df1, df2, df3]
    checker = dfs[-1]
    check = set(checker.loc[:, 0])
    
    for df in dfs[:-1]:
        check = check.intersection(set(df.loc[:, 0]))
    
    print(checker[checker.loc[:, 0].isin(check)])
    

    Error handling in getJSON calls

    This is quite an old thread, but it does come up in Google search, so I thought I would add a jQuery 3 answer using promises. This snippet also shows:

    • You no longer need to switch to $.ajax to pass in your bearer token
    • Uses .then() to make sure you can process synchronously any outcome (I was coming across this problem .always() callback firing too soon - although I'm not sure that was 100% true)
    • I'm using .always() to simply show the outcome whether positive or negative
    • In the .always() function I'm updating two targets with the HTTP Status code and message body

    The code snippet is:

        $.getJSON({
             url: "https://myurl.com/api",
             headers: { "Authorization": "Bearer " + user.access_token}
        }).then().always(   function (data, textStatus) {
            $("#txtAPIStatus").html(data.status);
            $("#txtAPIValue").html(data.responseText);
        });
    

    Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

    I think this need to be run from the Management Shell rather than the console, it sounds like the module isn't being imported into the Powershell console. You can add the module by running:

    Add-PSSnapin Microsoft.Sharepoint.Powershell
    

    in the Powershell console.

    Postgres: check if array field contains value?

    Instead of IN we can use ANY with arrays casted to enum array, for example:

    create type example_enum as enum (
      'ENUM1', 'ENUM2'
    );
    
    create table example_table (
      id integer,
      enum_field example_enum
    );
    
    select 
      * 
    from 
      example_table t
    where
      t.enum_field = any(array['ENUM1', 'ENUM2']::example_enum[]);
    

    Or we can still use 'IN' clause, but first, we should 'unnest' it:

    select 
      * 
    from 
      example_table t
    where
      t.enum_field in (select unnest(array['ENUM1', 'ENUM2']::example_enum[]));
    

    Example: https://www.db-fiddle.com/f/LaUNi42HVuL2WufxQyEiC/0

    What is a mutex?

    Mutex: Mutex stands for Mutual Exclusion. It means only one process/thread can enter into critical section at a given time. In concurrent programming multiple threads/process updating the shared resource (any variable, shared memory etc.) may lead to some unexpected result. ( As the result depends upon the which thread/process gets the first access).

    In order to avoid such an unexpected result we need some synchronization mechanism, which ensures that only one thread/process gets access to such a resource at a time.

    pthread library provides support for Mutex.

    typedef union
    {
      struct __pthread_mutex_s
      {
        ***int __lock;***
        unsigned int __count;
        int __owner;
    #ifdef __x86_64__
        unsigned int __nusers;
    #endif
    int __kind;
    #ifdef __x86_64__
        short __spins;
        short __elision;
        __pthread_list_t __list;
    # define __PTHREAD_MUTEX_HAVE_PREV      1
    # define __PTHREAD_SPINS             0, 0
    #else
        unsigned int __nusers;
        __extension__ union
        {
          struct
          {
            short __espins;
            short __elision;
    # define __spins __elision_data.__espins
    # define __elision __elision_data.__elision
    # define __PTHREAD_SPINS         { 0, 0 }
          } __elision_data;
          __pthread_slist_t __list;
        };
    #endif
    

    This is the structure for mutex data type i.e pthread_mutex_t. When mutex is locked, __lock set to 1. When it is unlocked __lock set to 0.

    This ensure that no two processes/threads can access the critical section at same time.

    Getting datarow values into a string?

    You need to specify which column of the datarow you want to pull data from.

    Try the following:

            StringBuilder output = new StringBuilder();
            foreach (DataRow rows in results.Tables[0].Rows)
            {
                foreach (DataColumn col in results.Tables[0].Columns)
                {
                    output.AppendFormat("{0} ", rows[col]);
                }
    
                output.AppendLine();
            }
    

    java: Class.isInstance vs Class.isAssignableFrom

    clazz.isAssignableFrom(Foo.class) will be true whenever the class represented by the clazz object is a superclass or superinterface of Foo.

    clazz.isInstance(obj) will be true whenever the object obj is an instance of the class clazz.

    That is:

    clazz.isAssignableFrom(obj.getClass()) == clazz.isInstance(obj)
    

    is always true so long as clazz and obj are nonnull.

    Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

    You can use NSValue for this. An NSValue object is a simple container for a single C or Objective-C data item. It can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object ids.

    Example:

      CGPoint cgPoint = CGPointMake(10,30);
        NSLog(@"%@",[NSValue valueWithCGPoint:cgPoint]);
    

    OUTPUT : NSPoint: {10, 30}

    Hope it helps you.

    How to check if type of a variable is string?

    Also I want notice that if you want to check whether the type of a variable is a specific kind, you can compare the type of the variable to the type of a known object.

    For string you can use this

    type(s) == type('')
    

    How to redirect output to a file and stdout

    Another way that works for me is,

    <command> |& tee  <outputFile>
    

    as shown in gnu bash manual

    Example:

    ls |& tee files.txt
    

    If ‘|&’ is used, command1’s standard error, in addition to its standard output, is connected to command2’s standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error to the standard output is performed after any redirections specified by the command.

    For more information, refer redirection

    How do I get whole and fractional parts from double in JSP/Java?

    The original question asked for the exponent and mantissa, rather than the fractional and whole part.

    To get the exponent and mantissa from a double you can convert it into the IEEE 754 representation and extract the bits like this:

    long bits = Double.doubleToLongBits(3.25);
    
    boolean isNegative = (bits & 0x8000000000000000L) != 0; 
    long exponent      = (bits & 0x7ff0000000000000L) >> 52;
    long mantissa      =  bits & 0x000fffffffffffffL;
    

    Where is the Microsoft.IdentityModel dll

    In Windows 8 and up there's a way to enable the feature from the command line without having to download/install anything explicitly by running the following:

    dism /online /Enable-Feature:Windows-Identity-Foundation
    

    And then find the file by running the following at the root of your Windows disk:

    dir /s /b Microsoft.IdentityModel.dll
    

    macro for Hide rows in excel 2010

    Well, you're on the right path, Benno!

    There are some tips regarding VBA programming that might help you out.

    1. Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.

    2. As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.

    3. Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.

    Now, let's have a draft code...

    Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.

    Hope it helps!

    Private Sub Worksheet_Change(ByVal Target As Range)
    
        Dim oSheet As Excel.Worksheet
    
        'We only want to do something if the changed cell is B6, right?
        If Target.Address = "$B$6" Then
    
            'Checks if it's a number...
            If IsNumeric(Target.Value) Then
    
                'Let's avoid values out of your bonds, correct?
                If Target.Value > 0 And Target.Value < 51 Then
    
                    'Let's assign the worksheet we'll show / hide rows to one variable and then
                    '   use only the reference to the variable itself instead of the sheet name.
                    '   It's safer.
    
                    'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
                    '   the sheet index within the workbook
                    Set oSheet = ActiveWorkbook.Sheets("Sheet 2")
    
                    'We'll unhide before hide, to ensure we hide the correct ones
                    oSheet.Range("A7:A56").EntireRow.Hidden = False
    
                    oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True
    
                End If
    
            End If
    
        End If
    
    End Sub
    

    How to find the port for MS SQL Server 2008?

    In addition to what is listed above, I had to enable both TCP and UDP ports for SQLExpress to connect remotely. Because I have three different instances on my development machine, I enable 1430-1435 for both TCP and UDP.

    Searching for UUIDs in text with regex

    /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89AB][0-9a-f]{3}-[0-9a-f]{12}$/i
    

    Gajus' regexp rejects UUID V1-3 and 5, even though they are valid.

    Difference between IISRESET and IIS Stop-Start command

    Take IISReset as a suite of commands that helps you manage IIS start / stop etc.

    Which means you need to specify option (/switch) what you want to do to carry any operation.

    Default behavior OR default switch is /restart with iisreset so you do not need to run command twice with /start and /stop.

    Hope this clarifies your question. For reference the output of iisreset /? is:

    IISRESET.EXE (c) Microsoft Corp. 1998-2005
    
    Usage:
    iisreset [computername]
    
        /RESTART            Stop and then restart all Internet services.
        /START              Start all Internet services.
        /STOP               Stop all Internet services.
        /REBOOT             Reboot the computer.
        /REBOOTONERROR      Reboot the computer if an error occurs when starting,
                            stopping, or restarting Internet services.
        /NOFORCE            Do not forcefully terminate Internet services if
                            attempting to stop them gracefully fails.
        /TIMEOUT:val        Specify the timeout value ( in seconds ) to wait for
                            a successful stop of Internet services. On expiration
                            of this timeout the computer can be rebooted if
                            the /REBOOTONERROR parameter is specified.
                            The default value is 20s for restart, 60s for stop,
                            and 0s for reboot.
        /STATUS             Display the status of all Internet services.
        /ENABLE             Enable restarting of Internet Services
                            on the local system.
        /DISABLE            Disable restarting of Internet Services
                            on the local system.
    

    Save matplotlib file to a directory

    If the directory you wish to save to is a sub-directory of your working directory, simply specify the relative path before your file name:

        fig.savefig('Sub Directory/graph.png')
    

    If you wish to use an absolute path, import the os module:

        import os
        my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
        ...
        fig.savefig(my_path + '/Sub Directory/graph.png')
    

    If you don't want to worry about the leading slash in front of the sub-directory name, you can join paths intelligently as follows:

        import os
        my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
        my_file = 'graph.png'
        ...
        fig.savefig(os.path.join(my_path, my_file))        
    

    change directory in batch file using variable

    The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

    Remove the spaces from both sides of the = sign, and put the value in double quotes:

    set Pathname="C:\Program Files"
    

    Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

    Use

    cd /d %Pathname%
    

    or

    pushd %Pathname%
    

    instead.

    Oracle - How to generate script from sql developer

    use the dbms_metadata package, as described here

    What is the best way to give a C# auto-property an initial value?

    Edited on 1/2/15

    C# 6 :

    With C# 6 you can initialize auto-properties directly (finally!), there are now other answers in the thread that describe that.

    C# 5 and below:

    Though the intended use of the attribute is not to actually set the values of the properties, you can use reflection to always set them anyway...

    public class DefaultValuesTest
    {    
        public DefaultValuesTest()
        {               
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this))
            {
                DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];
    
                if (myAttribute != null)
                {
                    property.SetValue(this, myAttribute.Value);
                }
            }
        }
    
        public void DoTest()
        {
            var db = DefaultValueBool;
            var ds = DefaultValueString;
            var di = DefaultValueInt;
        }
    
    
        [System.ComponentModel.DefaultValue(true)]
        public bool DefaultValueBool { get; set; }
    
        [System.ComponentModel.DefaultValue("Good")]
        public string DefaultValueString { get; set; }
    
        [System.ComponentModel.DefaultValue(27)]
        public int DefaultValueInt { get; set; }
    }
    

    How can I use "." as the delimiter with String.split() in java

    The argument to split is a regular expression. "." matches anything so your delimiter to split on is anything.

    Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

    Just in case someone is using Bootstrap, I was able to add more than one class:

    <a href="" class="baseclass" th:classappend="${isAdmin} ?: 'text-danger font-italic' "></a>
    

    Deserialize JSON array(or list) in C#

    This code works for me:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.Script.Serialization;
    
    namespace Json
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(DeserializeNames());
                Console.ReadLine();
            }
    
            public static string DeserializeNames()
            {
                var jsonData = "{\"name\":[{\"last\":\"Smith\"},{\"last\":\"Doe\"}]}";
    
                JavaScriptSerializer ser = new JavaScriptSerializer();
    
                nameList myNames = ser.Deserialize<nameList>(jsonData);
    
                return ser.Serialize(myNames);
            }
    
            //Class descriptions
    
            public class name
            {
                public string last { get; set; }
            }
    
            public class nameList
            {
                public List<name> name { get; set; }
            }
        }
    }
    

    Set Memory Limit in htaccess

    In your .htaccess you can add:

    PHP 5.x

    <IfModule mod_php5.c>
        php_value memory_limit 64M
    </IfModule>
    

    PHP 7.x

    <IfModule mod_php7.c>
        php_value memory_limit 64M
    </IfModule>
    

    If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

    If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

    Read more on http://support.tigertech.net/php-value

    Test if string begins with a string?

    Judging by the declaration and description of the startsWith Java function, the "most straight forward way" to implement it in VBA would either be with Left:

    Public Function startsWith(str As String, prefix As String) As Boolean
        startsWith = Left(str, Len(prefix)) = prefix
    End Function
    

    Or, if you want to have the offset parameter available, with Mid:

    Public Function startsWith(str As String, prefix As String, Optional toffset As Integer = 0) As Boolean
        startsWith = Mid(str, toffset + 1, Len(prefix)) = prefix
    End Function
    

    What is meaning of negative dbm in signal strength?

    The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.

    dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is

    P(dBm) = 10 · log10( P(W) / 1mW ) 
    

    where

    P(dBm) = Power expressed in dBm   
    P(W) = the absolute power measured in Watts   
    mW = milliWatts   
    log10 = log to base 10
    

    From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.

    There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.

    Your actual question was "does the - sign count?"

    The answer is yes, it does.

    -85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.

    Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.

    How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.

    Using sed and grep/egrep to search and replace

    I couldn't get any of the commands on this page to work for me: the sed solution added a newline to the end of all the files it processed, and the perl solution was unable to accept enough arguments from find. I found this solution which works perfectly:

    find . -type f -name '*.[hm]' -print0 
        | xargs -0 perl -pi -e 's/search_regex/replacement_string/g'
    

    This will recurse down the current directory tree and replace search_regex with replacement_string in any files ending in .h or .m.

    I have also used rpl for this purpose in the past.

    How do you tell if a string contains another string in POSIX sh?

    Here's yet another solution. This uses POSIX substring parameter expansion, so it works in Bash, Dash, KornShell (ksh), Z shell (zsh), etc.

    test "${string#*$word}" != "$string" && echo "$word found in $string"
    

    A functionalized version with some examples:

    # contains(string, substring)
    #
    # Returns 0 if the specified string contains the specified substring,
    # otherwise returns 1.
    contains() {
        string="$1"
        substring="$2"
        if test "${string#*$substring}" != "$string"
        then
            return 0    # $substring is in $string
        else
            return 1    # $substring is not in $string
        fi
    }
    
    contains "abcd" "e" || echo "abcd does not contain e"
    contains "abcd" "ab" && echo "abcd contains ab"
    contains "abcd" "bc" && echo "abcd contains bc"
    contains "abcd" "cd" && echo "abcd contains cd"
    contains "abcd" "abcd" && echo "abcd contains abcd"
    contains "" "" && echo "empty string contains empty string"
    contains "a" "" && echo "a contains empty string"
    contains "" "a" || echo "empty string does not contain a"
    contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
    contains "abcd efgh" " " && echo "abcd efgh contains a space"
    

    IIS URL Rewrite and Web.config

    1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.

    2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):

    This rule will do SINGLE EXACT rewrite (internal redirect) /page to /page.html. URL in browser will remain unchanged.

    <system.webServer>
        <rewrite>
            <rules>
                <rule name="SpecificRewrite" stopProcessing="true">
                    <match url="^page$" />
                    <action type="Rewrite" url="/page.html" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
    

    This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.

    <system.webServer>
        <rewrite>
            <rules>
                <rule name="SpecificRedirect" stopProcessing="true">
                    <match url="^page$" />
                    <action type="Redirect" url="/page.html" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
    

    Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page it will check if /page.html exists, and if it does then rewrite occurs):

    <system.webServer>
        <rewrite>
            <rules>
                <rule name="DynamicRewrite" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
                    </conditions>
                    <action type="Rewrite" url="/{R:1}.html" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
    

    What is this date format? 2011-08-12T20:17:46.384Z

    tl;dr

    Standard ISO 8601 format is used by your input string.

    Instant.parse ( "2011-08-12T20:17:46.384Z" ) 
    

    ISO 8601

    This format is defined by the sensible practical standard, ISO 8601.

    The T separates the date portion from the time-of-day portion. The Z on the end means UTC (that is, an offset-from-UTC of zero hours-minutes-seconds). The Z is pronounced “Zulu”.

    java.time

    The old date-time classes bundled with the earliest versions of Java have proven to be poorly designed, confusing, and troublesome. Avoid them.

    Instead, use the java.time framework built into Java 8 and later. The java.time classes supplant both the old date-time classes and the highly successful Joda-Time library.

    The java.time classes use ISO 8601 by default when parsing/generating textual representations of date-time values.

    The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds. That class can directly parse your input string without bothering to define a formatting pattern.

    Instant instant = Instant.parse ( "2011-08-12T20:17:46.384Z" ) ;
    

    Table of date-time types in Java, both modern and legacy


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

    Where to obtain the java.time classes?

    Table of which java.time library to use with which version of Java or Android

    How to pass an object from one activity to another on Android

    I found a simple & elegant method:

    • NO Parcelable
    • NO Serializable
    • NO Static Field
    • No Event Bus

    Method 1

    Code for the first activity:

        final Object objSent = new Object();
        final Bundle bundle = new Bundle();
        bundle.putBinder("object_value", new ObjectWrapperForBinder(objSent));
        startActivity(new Intent(this, SecondActivity.class).putExtras(bundle));        
        Log.d(TAG, "original object=" + objSent);
    

    Code for the second activity:

        final Object objReceived = ((ObjectWrapperForBinder)getIntent().getExtras().getBinder("object_value")).getData();
        Log.d(TAG, "received object=" + objReceived);
    

    you will find objSent & objReceived have the same hashCode, so they are identical.

    But why can we pass a java object in this way?

    Actually, android binder will create global JNI reference for java object and release this global JNI reference when there are no reference for this java object. binder will save this global JNI reference in the Binder object.

    *CAUTION: this method ONLY work unless the two activities run in the same process, otherwise throw ClassCastException at (ObjectWrapperForBinder)getIntent().getExtras().getBinder("object_value") *

    class ObjectWrapperForBinder defination

    public class ObjectWrapperForBinder extends Binder {
    
        private final Object mData;
    
        public ObjectWrapperForBinder(Object data) {
            mData = data;
        }
    
        public Object getData() {
            return mData;
        }
    }
    

    Method 2

    • for the sender,
      1. use custom native method to add your java object to JNI global reference table(via JNIEnv::NewGlobalRef)
      2. put the return integer (actually, JNIEnv::NewGlobalRef return jobject, which is a pointer, we can cast it to int safely) to your Intent(via Intent::putExtra)
    • for the receiver
      1. get integer from Intent(via Intent::getInt)
      2. use custom native method to restore your java object from JNI global reference table (via JNIEnv::NewLocalRef)
      3. remove item from JNI global reference table(via JNIEnv::DeleteGlobalRef),

    But Method 2 has a little but serious issue, if the receiver fail to restore the java object (for example, some exception happen before restore the java object, or the receiver Activity does not exist at all), then the java object will become an orphan or memory leak, Method 1 don't have this issue, because android binder will handle this exception

    Method 3

    To invoke the java object remotely, we will create a data contract/interface to describe the java object, we will use the aidl file

    IDataContract.aidl

    package com.example.objectwrapper;
    interface IDataContract {
        int func1(String arg1);
        int func2(String arg1);
    }
    

    Code for the first activity

        final IDataContract objSent = new IDataContract.Stub() {
    
            @Override
            public int func2(String arg1) throws RemoteException {
                // TODO Auto-generated method stub
                Log.d(TAG, "func2:: arg1=" + arg1);
                return 102;
            }
    
            @Override
            public int func1(String arg1) throws RemoteException {
                // TODO Auto-generated method stub
                Log.d(TAG, "func1:: arg1=" + arg1);
                return 101;
            }
        };
        final Bundle bundle = new Bundle();
        bundle.putBinder("object_value", objSent.asBinder());
        startActivity(new Intent(this, SecondActivity.class).putExtras(bundle));
        Log.d(TAG, "original object=" + objSent);
    

    Code for the second activity:

    change the android:process attribute in AndroidManifest.xml to a non-empty process name to make sure the second activity run in another process

        final IDataContract objReceived = IDataContract.Stub.asInterface(getIntent().getExtras().getBinder("object_value"));
        try {
            Log.d(TAG, "received object=" + objReceived + ", func1()=" + objReceived.func1("test1") + ", func2()=" + objReceived.func2("test2"));
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    

    In this way, we can pass an interface between two activities even though they run in different process, and call the interface method remotely

    Method 4

    method 3 seem not simple enough because we must implement an aidl interface. If you just want to do simple task and the method return value is unnecessary, we can use android.os.Messenger

    Code for the first activity( sender):

    public class MainActivity extends Activity {
        private static final String TAG = "MainActivity";
    
        public static final int MSG_OP1 = 1;
        public static final int MSG_OP2 = 2;
    
        public static final String EXTRA_MESSENGER = "messenger";
    
        private final Handler mHandler = new Handler() {
    
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                Log.e(TAG, "handleMessage:: msg=" + msg);
                switch (msg.what) {
                case MSG_OP1:
    
                    break;
                case MSG_OP2:
                    break;
    
                default:
    
                    break;
                }
                super.handleMessage(msg);
            }
    
        };
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            startActivity(new Intent(this, SecondActivity.class).putExtra(EXTRA_MESSENGER, new Messenger(mHandler)));
        }
    }
    

    Code for the second activity ( receiver ):

    public class SecondActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
    
            final Messenger messenger = getIntent().getParcelableExtra(MainActivity.EXTRA_MESSENGER);
            try {
                messenger.send(Message.obtain(null, MainActivity.MSG_OP1, 101, 1001, "10001"));
                messenger.send(Message.obtain(null, MainActivity.MSG_OP2, 102, 1002, "10002"));
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    }
    

    All the Messenger.send will execute in a Handler asynchronously and sequentially.

    Actually, android.os.Messenger is also an aidl interface, if you have the android source code, you can find a file named IMessenger.aidl

    package android.os;
    
    import android.os.Message;
    
    /** @hide */
    oneway interface IMessenger {
        void send(in Message msg);
    }
    

    Ways to circumvent the same-origin policy

    AnyOrigin didn't function well with some https sites, so I just wrote an open source alternative called whateverorigin.org that seems to work well with https.

    Code on github.

    How to implement a read only property

    C# 6.0 adds readonly auto properties

    public object MyProperty { get; }
    

    So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.


    Versioning:
    I think it doesn't make much difference if you are only interested in source compatibility.
    Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.

    Convention:
    You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.

    Serialization
    Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer does only serialize public properties and not public fields.

    Using an Autoproperty
    Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.

    Readonly field is selfdocumenting
    There is one advantage of the field though:
    It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.

    But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.

    IIS Express gives Access Denied error when debugging ASP.NET MVC

    None of the above had worked for me. This had been working for me prior to today. I then realized I had been working with creating a hosted connection on my laptop and had Shared an internet connection with my Wireless Network Connection.

    To fix my issue:

    Go to Control Panel > Network and Internet > Network Connections

    Right click on any secondary Wireless Network Connection you may have (mine was named Wireless Network Connection 2) and click 'Properties'.

    Go to the 'Sharing' tab at the top.

    Uncheck the box that states 'Allow other network users to connect through this computer's Internet connection'.

    Hit OK > then Apply.

    Hope this helps!

    Convert textbox text to integer

    If your SQL database allows Null values for that field try using int? value like that :

    if (this.txtboxname.Text == "" || this.txtboxname.text == null)
         value = null;
    else
         value = Convert.ToInt32(this.txtboxname.Text);
    

    Take care that Convert.ToInt32 of a null value returns 0 !

    Convert.ToInt32(null) returns 0
    

    Execute Stored Procedure from a Function

    I have figured out a solution to this problem. We can build a Function or View with "rendered" sql in a stored procedure that can then be executed as normal.

    1.Create another sproc

    CREATE PROCEDURE [dbo].[usp_FunctionBuilder]
    DECLARE @outerSql VARCHAR(MAX)
    DECLARE @innerSql VARCHAR(MAX)
    

    2.Build the dynamic sql that you want to execute in your function (Example: you could use a loop and union, you could read in another sproc, use if statements and parameters for conditional sql, etc.)

    SET @innerSql = 'your sql'
    

    3.Wrap the @innerSql in a create function statement and define any external parameters that you have used in the @innerSql so they can be passed into the generated function.

    SET @outerSql = 'CREATE FUNCTION [dbo].[fn_GeneratedFunction] ( @Param varchar(10))
    RETURNS TABLE
    AS
    RETURN
    ' + @innerSql;
    
    
    EXEC(@outerSql)
    

    This is just pseudocode but the solution solves many problems such as linked server limitations, parameters, dynamic sql in function, dynamic server/database/table name, loops, etc.

    You will need to tweak it to your needs, (Example: changing the return in the function)

    Performing Inserts and Updates with Dapper

    You can try this:

     string sql = "UPDATE Customer SET City = @City WHERE CustomerId = @CustomerId";             
     conn.Execute(sql, customerEntity);
    

    Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

    The ngRoute module is no longer part of the core angular.js file. If you are continuing to use $routeProvider then you will now need to include angular-route.js in your HTML:

    <script src="angular.js">
    <script src="angular-route.js">
    

    API Reference

    You also have to add ngRoute as a dependency for your application:

    var app = angular.module('MyApp', ['ngRoute', ...]);
    

    If instead you are planning on using angular-ui-router or the like then just remove the $routeProvider dependency from your module .config() and substitute it with the relevant provider of choice (e.g. $stateProvider). You would then use the ui.router dependency:

    var app = angular.module('MyApp', ['ui.router', ...]);
    

    CSS3 selector :first-of-type with class name?

    I found a solution for your reference. from some group divs select from group of two same class divs the first one

    p[class*="myclass"]:not(:last-of-type) {color:red}
    p[class*="myclass"]:last-of-type {color:green}
    

    BTW, I don't know why :last-of-type works, but :first-of-type does not work.

    My experiments on jsfiddle... https://jsfiddle.net/aspanoz/m1sg4496/

    How to get the browser viewport dimensions?

    A solution that would conform to W3C standards would be to create a transparent div (for example dynamically with JavaScript), set its width and height to 100vw/100vh (Viewport units) and then get its offsetWidth and offsetHeight. After that, the element can be removed again. This will not work in older browsers because the viewport units are relatively new, but if you don't care about them but about (soon-to-be) standards instead, you could definitely go this way:

    var objNode = document.createElement("div");
    objNode.style.width  = "100vw";
    objNode.style.height = "100vh";
    document.body.appendChild(objNode);
    var intViewportWidth  = objNode.offsetWidth;
    var intViewportHeight = objNode.offsetHeight;
    document.body.removeChild(objNode);
    

    Of course, you could also set objNode.style.position = "fixed" and then use 100% as width/height - this should have the same effect and improve compatibility to some extent. Also, setting position to fixed might be a good idea in general, because otherwise the div will be invisible but consume some space, which will lead to scrollbars appearing etc.

    Get index of selected option with jQuery

    try this

     alert(document.getElementById("dropDownMenuKategorie").selectedIndex);