Programs & Examples On #Iasyncresult

Questions аbout IAsyncResult .net interface that represents the status of an asynchronous operation.

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

Just as a follow up for anyone still running into this – I had added the ServicePointManager.SecurityProfile options as noted in the solution:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

And yet I continued to get the same “The request was aborted: Could not create SSL/TLS secure channel” error. I was attempting to connect to some older voice servers with HTTPS SOAP API interfaces (i.e. voice mail, IP phone systems etc… installed years ago). These only support SSL3 connections as they were last updated years ago.

One would think including SSl3 in the list of SecurityProtocols would do the trick here, but it didn’t. The only way I could force the connection was to include ONLY the Ssl3 protocol and no others:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

Then the connection goes through – seems like a bug to me but this didn’t start throwing errors until recently on tools I provide for these servers that have been out there for years – I believe Microsoft has started rolling out system changes that have updated this behavior to force TLS connections unless there is no other alternative.

Anyway – if you’re still running into this against some old sites/servers, it’s worth giving it a try.

How to wait for a JavaScript Promise to resolve before resuming function?

Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.

Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).

_x000D_
_x000D_
function append_output(suffix, value) {
  $("#output_"+suffix).append(value)
}

function kickOff() {
  let start = new Promise((resolve, reject) => {
    append_output("now", "start")
    resolve("start")
  })
  let middle = new Promise((resolve, reject) => {
    setTimeout(() => {
      append_output("now", " middle")
      resolve(" middle")
    }, 1000)
  })
  let end = new Promise((resolve, reject) => {
    append_output("now", " end")
    resolve(" end")
  })

  Promise.all([start, middle, end]).then(results => {
    results.forEach(
      result => append_output("later", result))
  })
}

kickOff()
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>
_x000D_
_x000D_
_x000D_

No connection could be made because the target machine actively refused it 127.0.0.1

If you have this while Fiddler is running -> in Fiddler, go to 'Rules' and disable 'Automatically Authenticate' and it should work again.

How to resolve this System.IO.FileNotFoundException

I came across a similar situation after publishing a ClickOnce application, and one of my colleagues on a different domain reported that it fails to launch.

To find out what was going on, I added a try catch statement inside the MainWindow method as @BradleyDotNET mentioned in one comment on the original post, and then published again.

public MainWindow()
{
    try
    {
        InitializeComponent();
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.ToString());
    }
}

Then my colleague reported to me the exception detail, and it was a missing reference of a third party framework dll file.

Added the reference and problem solved.

System.Data.SqlClient.SqlException: Login failed for user

You can also get this error if your SQL Server has not been configured to use Mixed mode authentication - it doesn't actually tell you that this is not enabled!

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

If the other answers don't work you can check if something else is using the port with netstat:

netstat -ano | findstr <your port number>

If nothing is already using it, the port might be excluded, try this command to see if the range is blocked by something else:

netsh interface ipv4 show excludedportrange protocol=tcp

How to upload file to server with HTTP POST multipart/form-data?

hi guys after one day searching on web finally i solve problem with below source code hope to help you

    public UploadResult UploadFile(string  fileAddress)
    {
        HttpClient client = new HttpClient();

        MultipartFormDataContent form = new MultipartFormDataContent();
        HttpContent content = new StringContent("fileToUpload");
        form.Add(content, "fileToUpload");       
        var stream = new FileStream(fileAddress, FileMode.Open);            
        content = new StreamContent(stream);
        var fileName = 
        content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "name",
            FileName = Path.GetFileName(fileAddress),                 
        };
        form.Add(content);
        HttpResponseMessage response = null;          

        var url = new Uri("http://192.168.10.236:2000/api/Upload2");
        response = (client.PostAsync(url, form)).Result;          

    }

Non-static method requires a target

I face this error on testing WebAPI in Postman tool.

After building the code, If we remove any line (For Example: In my case when I remove one Commented line this error was occur...) in debugging mode then the "Non-static method requires a target" error will occur.

Again, I tried to send the same request. This time code working properly. And I get the response properly in Postman.

I hope it will use to someone...

Task<> does not contain a definition for 'GetAwaiter'

If you are writing a Visual Studio Extension (VSIX) then ensure that you have a using statement for Microsoft.VisualStudio.Threading, as such:

using Microsoft.VisualStudio.Threading;

No connection could be made because the target machine actively refused it 127.0.0.1:3446

I also faced problem in .Net Remoting Service in C#.

I got it solved in 3 steps:

  1. Change Port of Protocol in all the files whereever it is being used.
  2. Run your Host Server Program and make it active.
  3. Now run your client program.

The I/O operation has been aborted because of either a thread exit or an application request

995 is an error reported by the IO Completion Port. The error comes since you try to continue read from the socket when it has most likely been closed.

Receiving 0 bytes from EndRecieve means that the socket has been closed, as does most exceptions that EndRecieve will throw.

You need to start dealing with those situations.

Never ever ignore exceptions, they are thrown for a reason.

Update

There is nothing that says that the server does anything wrong. A connection can be lost for a lot of reasons such as idle connection being closed by a switch/router/firewall, shaky network, bad cables etc.

What I'm saying is that you MUST handle disconnections. The proper way of doing so is to dispose the socket and try to connect a new one at certain intervals.

As for the receive callback a more proper way of handling it is something like this (semi pseudo code):

public void OnDataReceived(IAsyncResult asyn)
{
    BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", ref swReceivedLogWriter, strLogPath, 0);

    try
    {
        SocketPacket client = (SocketPacket)asyn.AsyncState;

        int bytesReceived = client.thisSocket.EndReceive(asyn); //Here error is coming
        if (bytesReceived == 0)
        {
          HandleDisconnect(client);
          return;
        }
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }

    try
    {
        string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);                    

        //do your handling here
    }
    catch (Exception err)
    {
        // Your logic threw an exception. handle it accordinhly
    }

    try
    {
       client.thisSocket.BeginRecieve(.. all parameters ..);
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }
}

the reason to why I'm using three catch blocks is simply because the logic for the middle one is different from the other two. Exceptions from BeginReceive/EndReceive usually indicates socket disconnection while exceptions from your logic should not stop the socket receiving.

An item with the same key has already been added

Here is what I did to find out the key that was being added twice. I downloaded the source code from http://referencesource.microsoft.com/DotNetReferenceSource.zip and setup VS to debug framework source. Opened up Dictionary.cs in VS ran the project, once page loads, added a debug at the line ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); and was able to see the 'key' value. I realized that in the JSON one letter of a variable was in upper case but in my model it was lowercase. I fixed the model and now the same code works.

No connection could be made because the target machine actively refused it?

This happened to me too.. Sometimes when I open my project this error shown up which was frustrating. The problem was that sometimes the port-number of web service was changing unexpectedly.

This problem usually happens when you have more than one copies of the project

My project was calling the Web service with a specific port number which I assigned in the Web.Config file of my main project file. As the port number changed unexpectedly, the browser was unable to find the Web service and throwing that error.

I solved this by following the below steps: (Visual Studio 2010)

Go to Properties of the Web service project --> click on Web tab --> In Servers section --> Check Specific port and then assign the standard port number by which your main project is calling the web service.

I hope this will solve the problem.

Cheers :)

Server cannot set status after HTTP headers have been sent IIS7.5

We were getting the same error - so this may be useful to some.

For us the cause was super simple. An interface change confused an end user and they were pressing the back button in the browser at a 'bad' time after a form submission (sure we should probably have used a PRG pattern, but we didn't).

We fixed the issue and the user is no longer pressing the back button. Problem solved.

Display progress bar while doing some work in C#?

I have to throw the simplest answer out there. You could always just implement the progress bar and have no relationship to anything of actual progress. Just start filling the bar say 1% a second, or 10% a second whatever seems similar to your action and if it fills over to start again.

This will atleast give the user the appearance of processing and make them understand to wait instead of just clicking a button and seeing nothing happen then clicking it more.

Instantly detect client disconnection from server socket

You can also check the .IsConnected property of the socket if you were to poll.

WCF, Service attribute value in the ServiceHost directive could not be found

Double check that you're referencing the correct type from the ServiceHost directive in the .svc file. Here's how...

  1. In the VS project containing your web service, open the .svc file in the XML editor (right-click the file, Open With..., choose XML (Text) Editor, OK).
  2. Note the "Service" attribute value.
  3. Make sure it matches the fully qualified type name of your service. This includes the namespace + type name. For example, if the namespace is "MyCompany.Department.Services" and the class is called "MyService", then the Service attribute value should be "MyCompany.Department.Services.MyService".

MySQL Insert query doesn't work with WHERE clause

I am aware that this is a old post but I hope that this will still help somebody, with what I hope is a simple example:

background:

I had a many to many case: the same user is listed multiple times with multiple values and I wanted to Create a new record, hence UPDATE wouldn't make sense in my case and I needed to address a particular user just like I would do using a WHERE clause.

INSERT into MyTable(aUser,aCar)
value(User123,Mini)

By using this construct you actually target a specific user (user123,who has other records) so you don't really need a where clause, I reckon.

the output could be:

aUser   aCar
user123 mini
user123 HisOtherCarThatWasThereBefore

How do I use tools:overrideLibrary in a build.gradle file?

I just changed minSdkVersion="7" in C:\MyApp\platforms\android\CordovaLib\AndroidManifest.xml and it worked.

Steps:

  1. Path: C:\MyApp\platforms\android\CordovaLib\AndroidManifest.xml
  2. Value: <uses-sdk android:minSdkVersion="7"/>
  3. Ran command in new cmd prompt:

    C:\MyApp>phonegap build android --debug [phonegap] executing 'cordova build android --debug'... [phonegap] completed 'cordova build android --debug'

Have a fixed position div that needs to scroll if content overflows

Here are both fixes.

First, regarding the fixed sidebar, you need to give it a height for it to overflow:

HTML Code:

<div id="sidebar">Menu</div>
<div id="content">Text</div>

CSS Code:

body {font:76%/150% Arial, Helvetica, sans-serif; color:#666; width:100%; height:100%;}
#sidebar {position:fixed; top:0; left:0; width:20%; height:100%; background:#EEE; overflow:auto;}
#content {width:80%; padding-left:20%;}

@media screen and (max-height:200px){
    #sidebar {color:blue; font-size:50%;}
}

Live example: http://jsfiddle.net/RWxGX/3/

It's impossible NOT to get a scroll bar if your content overflows the height of the div. That's why I've added a media query for screen height. Maybe you can adjust your styles for short screen sizes so the scroll doesn't need to appear.

Cheers, Ignacio

Permission to write to the SD card

The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.

However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).

The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).

For example:

[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
  protected override void OnCreate(Bundle bindle)
  {
    base.OnCreate(bindle);
  }
}

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

Print a variable in hexadecimal in Python

You mean you have a string of bytes in my_hex which you want to print out as hex numbers, right? E.g., let's take your example:

>>> my_string = "deadbeef"
>>> my_hex = my_string.decode('hex')  # python 2 only
>>> print my_hex
Þ ­ ¾ ï

This construction only works on Python 2; but you could write the same string as a literal, in either Python 2 or Python 3, like this:

my_hex = "\xde\xad\xbe\xef"

So, to the answer. Here's one way to print the bytes as hex integers:

>>> print " ".join(hex(ord(n)) for n in my_hex)
0xde 0xad 0xbe 0xef

The comprehension breaks the string into bytes, ord() converts each byte to the corresponding integer, and hex() formats each integer in the from 0x##. Then we add spaces in between.

Bonus: If you use this method with unicode strings (or Python 3 strings), the comprehension will give you unicode characters (not bytes), and you'll get the appropriate hex values even if they're larger than two digits.

Addendum: Byte strings

In Python 3 it is more likely you'll want to do this with a byte string; in that case, the comprehension already returns ints, so you have to leave out the ord() part and simply call hex() on them:

>>> my_hex = b'\xde\xad\xbe\xef'
>>> print(" ".join(hex(n) for n in my_hex))
0xde 0xad 0xbe 0xef

How to run VBScript from command line without Cscript/Wscript

I am wondering why you cannot put this in a batch file. Example:

cd D:\VBS\
WSCript Converter.vbs

Put the above code in a text file and save the text file with .bat extension. Now you have to simply run this .bat file.

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

I solved it by myself.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.0.7.Final</version>
</dependency>

Java - using System.getProperty("user.dir") to get the home directory

Program to get the current working directory=user.dir

public class CurrentDirectoryExample {

    public static void main(String args[]) {

        String current = System.getProperty("user.dir");
        System.out.println("Current working directory in Java : " + current);
    }
}

WPF Add a Border to a TextBlock

A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label

See this link for more on the differences between a TextBlock and other Controls

What is the current choice for doing RPC in Python?

Apache Thrift is a cross-language RPC option developed at Facebook. Works over sockets, function signatures are defined in text files in a language-independent way.

Creating SVG graphics using Javascript?

All modern browsers except IE support SVG

Here is a tutorial that provides step by step guide on how to work with SVG using javascript:

SVG Scripting with JavaScript Part 1: Simple Circle

Like Boldewyn has said already if you want

To do it cross-browser, I strongly recommend RaphaelJS: rapaheljs.com

Although right now I feel the size of the library is too large. It has many great features some of which you might not need.

Remove non-numeric characters (except periods and commas) from a string

Simplest way to truly remove all non-numeric characters:

echo preg_replace('/\D/', '', $string);

\D represents "any character that is not a decimal digit"

http://php.net/manual/en/regexp.reference.escape.php

regex with space and letters only?

use this expression

var RegExpression = /^[a-zA-Z\s]*$/;  

for more refer this http://tools.netshiftmedia.com

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

It seems you don't import jquery. Those $ functions come with this non standard (but very useful) library.

Read the tutorial there : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery It starts with how to import the library.

Hidden features of Windows batch files

Output a blank line:

echo.

Enable vertical scrolling on textarea

Here's your CSS

element{
  width: 200px;
  height: 300px;
  overflow-y: auto;
}

Download pdf file using jquery ajax

You can do this with html5 very easily:

var link = document.createElement('a');
link.href = "/WWW/test.pdf";
link.download = "file_" + new Date() + ".pdf";
link.click();
link.remove()

How to access property of anonymous type in C#?

The accepted answer correctly describes how the list should be declared and is highly recommended for most scenarios.

But I came across a different scenario, which also covers the question asked. What if you have to use an existing object list, like ViewData["htmlAttributes"] in MVC? How can you access its properties (they are usually created via new { @style="width: 100px", ... })?

For this slightly different scenario I want to share with you what I found out. In the solutions below, I am assuming the following declaration for nodes:

List<object> nodes = new List<object>();

nodes.Add(
new
{
    Checked = false,
    depth = 1,
    id = "div_1" 
});

1. Solution with dynamic

In C# 4.0 and higher versions, you can simply cast to dynamic and write:

if (nodes.Any(n => ((dynamic)n).Checked == false))
    Console.WriteLine("found a  not checked  element!");

Note: This is using late binding, which means it will recognize only at runtime if the object doesn't have a Checked property and throws a RuntimeBinderException in this case - so if you try to use a non-existing Checked2 property you would get the following message at runtime: "'<>f__AnonymousType0<bool,int,string>' does not contain a definition for 'Checked2'".

2. Solution with reflection

The solution with reflection works both with old and new C# compiler versions. For old C# versions please regard the hint at the end of this answer.

Background

As a starting point, I found a good answer here. The idea is to convert the anonymous data type into a dictionary by using reflection. The dictionary makes it easy to access the properties, since their names are stored as keys (you can access them like myDict["myProperty"]).

Inspired by the code in the link above, I created an extension class providing GetProp, UnanonymizeProperties and UnanonymizeListItems as extension methods, which simplify access to anonymous properties. With this class you can simply do the query as follows:

if (nodes.UnanonymizeListItems().Any(n => (bool)n["Checked"] == false))
{
    Console.WriteLine("found a  not checked  element!");
}

or you can use the expression nodes.UnanonymizeListItems(x => (bool)x["Checked"] == false).Any() as if condition, which filters implicitly and then checks if there are any elements returned.

To get the first object containing "Checked" property and return its property "depth", you can use:

var depth = nodes.UnanonymizeListItems()
             ?.FirstOrDefault(n => n.Contains("Checked")).GetProp("depth");

or shorter: nodes.UnanonymizeListItems()?.FirstOrDefault(n => n.Contains("Checked"))?["depth"];

Note: If you have a list of objects which don't necessarily contain all properties (for example, some do not contain the "Checked" property), and you still want to build up a query based on "Checked" values, you can do this:

if (nodes.UnanonymizeListItems(x => { var y = ((bool?)x.GetProp("Checked", true)); 
                                      return y.HasValue && y.Value == false;}).Any())
{
    Console.WriteLine("found a  not checked   element!");
}

This prevents, that a KeyNotFoundException occurs if the "Checked" property does not exist.


The class below contains the following extension methods:

  • UnanonymizeProperties: Is used to de-anonymize the properties contained in an object. This method uses reflection. It converts the object into a dictionary containing the properties and its values.
  • UnanonymizeListItems: Is used to convert a list of objects into a list of dictionaries containing the properties. It may optionally contain a lambda expression to filter beforehand.
  • GetProp: Is used to return a single value matching the given property name. Allows to treat not-existing properties as null values (true) rather than as KeyNotFoundException (false)

For the examples above, all that is required is that you add the extension class below:

public static class AnonymousTypeExtensions
{
    // makes properties of object accessible 
    public static IDictionary UnanonymizeProperties(this object obj)
    {
        Type type = obj?.GetType();
        var properties = type?.GetProperties()
               ?.Select(n => n.Name)
               ?.ToDictionary(k => k, k => type.GetProperty(k).GetValue(obj, null));
        return properties;
    }
    
    // converts object list into list of properties that meet the filterCriteria
    public static List<IDictionary> UnanonymizeListItems(this List<object> objectList, 
                    Func<IDictionary<string, object>, bool> filterCriteria=default)
    {
        var accessibleList = new List<IDictionary>();
        foreach (object obj in objectList)
        {
            var props = obj.UnanonymizeProperties();
            if (filterCriteria == default
               || filterCriteria((IDictionary<string, object>)props) == true)
            { accessibleList.Add(props); }
        }
        return accessibleList;
    }

    // returns specific property, i.e. obj.GetProp(propertyName)
    // requires prior usage of AccessListItems and selection of one element, because
    // object needs to be a IDictionary<string, object>
    public static object GetProp(this object obj, string propertyName, 
                                 bool treatNotFoundAsNull = false)
    {
        try 
        {
            return ((System.Collections.Generic.IDictionary<string, object>)obj)
                   ?[propertyName];
        }
        catch (KeyNotFoundException)
        {
            if (treatNotFoundAsNull) return default(object); else throw;
        }
    }
}

Hint: The code above is using the null-conditional operators, available since C# version 6.0 - if you're working with older C# compilers (e.g. C# 3.0), simply replace ?. by . and ?[ by [ everywhere (and do the null-handling traditionally by using if statements or catch NullReferenceExceptions), e.g.

var depth = nodes.UnanonymizeListItems()
            .FirstOrDefault(n => n.Contains("Checked"))["depth"];

As you can see, the null-handling without the null-conditional operators would be cumbersome here, because everywhere you removed them you have to add a null check - or use catch statements where it is not so easy to find the root cause of the exception resulting in much more - and hard to read - code.

If you're not forced to use an older C# compiler, keep it as is, because using null-conditionals makes null handling much easier.

Note: Like the other solution with dynamic, this solution is also using late binding, but in this case you're not getting an exception - it will simply not find the element if you're referring to a non-existing property, as long as you keep the null-conditional operators.

What might be useful for some applications is that the property is referred to via a string in solution 2, hence it can be parameterized.

How to add a href link in PHP?

Just do it in HTML

<a href="https://www.google.com">Google</a>

PHP Warning: Invalid argument supplied for foreach()

Try this.

if(is_array($value) || is_object($value)){
    foreach($value as $item){
     //somecode
    }
}

Chmod recursively

To make everything writable by the owner, read/execute by the group, and world executable:

chmod -R 0755

To make everything wide open:

chmod -R 0777

Adding external resources (CSS/JavaScript/images etc) in JSP

The reason that you get the 404 File Not Found error, is that your path to CSS given as a value to the href attribute is missing context path.

An HTTP request URL contains the following parts:

http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

  • Context path: A concatenation of a forward slash (/) with the context root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]

  • Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).

  • Path info: The part of the request path that is not part of the context path or the servlet path.

Read more here.


Solutions

There are several solutions to your problem, here are some of them:

1) Using <c:url> tag from JSTL

In my Java web applications I usually used <c:url> tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).

If you say, that your CSS is located inside WebContent folder, then this should work:

<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />

The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):

7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.

NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.


2) Using JSP Expression Language and implicit objects

An alternative solution is using Expression Language (EL) to add application context:

<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />

Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.


3) Using <c:set> tag from JSTL

DISCLAIMER
The idea of this solution was taken from here.

To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set> tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.

<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />

IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.


4) Using ServletContextListener

The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.

We need a class that implements ServletContextListener interface. Here is an example of such class:

package com.example.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        sc.setAttribute("ctx", sc.getContextPath());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {}

}

Now in a JSP we can access this global variable using EL:

<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />

NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    ...  
    <listener>
        <listener-class>com.example.listener.AppContextListener</listener-class>
    </listener>
    ...
</webapp>


5) Using scriptlets

As suggested by user @gavenkoa you can also use scriptlets like this:

<%= request.getContextPath() %>

For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.


Conclusion

I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.


Other thoughts

You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.

How to style the <option> with only CSS?

There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...

Python: Remove division decimal

You could probably do like below

# p and q are the numbers to be divided
if p//q==p/q:
    print(p//q)
else:
    print(p/q)

Apply function to each element of a list

Sometimes you need to apply a function to the members of a list in place. The following code worked for me:

>>> def func(a, i):
...     a[i] = a[i].lower()
>>> a = ['TEST', 'TEXT']
>>> list(map(lambda i:func(a, i), range(0, len(a))))
[None, None]
>>> print(a)
['test', 'text']

Please note, the output of map() is passed to the list constructor to ensure the list is converted in Python 3. The returned list filled with None values should be ignored, since our purpose was to convert list a in place

Storing Python dictionaries

If save to a JSON file, the best and easiest way of doing this is:

import json
with open("file.json", "wb") as f:
    f.write(json.dumps(dict).encode("utf-8"))

How do I make a redirect in PHP?

You can attempt to use the PHP header function to do the redirect. You will want to set the output buffer so your browser doesn't throw a redirect warning to the screen.

ob_start();
header("Location: " . $website);
ob_end_flush();

Angular - ui-router get previous state

In the following example i created a decorator (runs only once per app at configuration phase) and adds an extra property to $state service, so this approach does not add global variables to $rootscope and does not require to add any extra dependency to other services than $state.

In my example i needed to redirect a user to the index page when he was already signed in and when he was not to redirect him to the previous "protected" page after sign in.

The only unknown services (for you) that i use are authenticationFactory and appSettings:

  • authenticationFactory just administrates the user login. In this case i use only a method to identify if the user is logged in or not.
  • appSettings are constants just for not use strings everywhere. appSettings.states.login and appSettings.states.register contain the name of the state for the login and register url.

Then in any controller/service etc you need to inject $state service and you can access current and previous url like this:

  • Current: $state.current.name
  • Previous: $state.previous.route.name

From the Chrome console:

var injector = angular.element(document.body).injector();
var $state = injector.get("$state");
$state.current.name;
$state.previous.route.name;

Implementation:

(I'm using angular-ui-router v0.2.17 and angularjs v1.4.9)

(function(angular) {
    "use strict";

    function $stateDecorator($delegate, $injector, $rootScope, appSettings) {
        function decorated$State() {
            var $state = $delegate;
            $state.previous = undefined;
            $rootScope.$on("$stateChangeSuccess", function (ev, to, toParams, from, fromParams) {
                $state.previous = { route: from, routeParams: fromParams }
            });

            $rootScope.$on("$stateChangeStart", function (event, toState/*, toParams, fromState, fromParams*/) {
                var authenticationFactory = $injector.get("authenticationFactory");
                if ((toState.name === appSettings.states.login || toState.name === appSettings.states.register) && authenticationFactory.isUserLoggedIn()) {
                    event.preventDefault();
                    $state.go(appSettings.states.index);
                }
            });

            return $state;
        }

        return decorated$State();
    }

    $stateDecorator.$inject = ["$delegate", "$injector", "$rootScope", "appSettings"];

    angular
        .module("app.core")
        .decorator("$state", $stateDecorator);
})(angular);

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

I solved this by using the /sm flag to specify to look in the machine store instead of the default, which is My (Local User) store. Also, it can help to turn on debug for signtool by using /debug.

Get final URL after curl is redirected

Can you try with it?

#!/bin/bash 
LOCATION=`curl -I 'http://your-domain.com/url/redirect?r=something&a=values-VALUES_FILES&e=zip' | perl -n -e '/^Location: (.*)$/ && print "$1\n"'` 
echo "$LOCATION"

Note: when you execute the command curl -I http://your-domain.com have to use single quotes in the command like curl -I 'http://your-domain.com'

Javascript format date / time

For the date part:(month is 0-indexed while days are 1-indexed)

var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' +  date.getFullYear());

for the time you'll want to create a function to test different situations and convert.

How to reduce the image size without losing quality in PHP

I'd go for jpeg. Read this post regarding image size reduction and after deciding on the technique, use ImageMagick

Hope this helps

How to scroll to top of the page in AngularJS?

You can use $anchorScroll.

Just inject $anchorScroll as a dependency, and call $anchorScroll() whenever you want to scroll to top.

Do something if screen width is less than 960 px

// Adds and removes body class depending on screen width.
function screenClass() {
    if($(window).innerWidth() > 960) {
        $('body').addClass('big-screen').removeClass('small-screen');
    } else {
        $('body').addClass('small-screen').removeClass('big-screen');
    }
}

// Fire.
screenClass();

// And recheck when window gets resized.
$(window).bind('resize',function(){
    screenClass();
});

Connection failed: SQLState: '01000' SQL Server Error: 10061

  1. Windows firewall blocks the sql server. Even if you open the 1433 port from exceptions, in the client machine it sets the connection point to dynamic port. Add also the sql server to the exceptions.

"C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn\Sqlservr.exe"

More info

  1. This page helped me to solve the problem. Especially

or if you feel brave, locate the alias in the registry and delete it there.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo\

Add newly created specific folder to .gitignore in Git

I'm incredibly lazy. I just did a search hoping to find a shortcut to this problem but didn't get an answer so I knocked this up.

~/bin/IGNORE_ALL

#!/bin/bash
# Usage: IGNORE_ALL <commit message>                                                                                                                             
git status --porcelain | grep '^??' | cut -f2 -d' ' >> .gitignore              
git commit -m "$*" .gitignore 

EG: IGNORE_ALL added stat ignores

This will just append all the ignore files to your .gitignore and commit. note you might want to add annotations to the file afterwards.

Using Google maps API v3 how do I get LatLng with a given address?

There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

To shorten it up a little:

geocoder = new google.maps.Geocoder();

function codeAddress() {

    //In this case it gets the address from an element on the page, but obviously you  could just pass it to the method instead
    var address = document.getElementById( 'address' ).value;

    geocoder.geocode( { 'address' : address }, function( results, status ) {
        if( status == google.maps.GeocoderStatus.OK ) {

            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter( results[0].geometry.location );
            var marker = new google.maps.Marker( {
                map     : map,
                position: results[0].geometry.location
            } );
        } else {
            alert( 'Geocode was not successful for the following reason: ' + status );
        }
    } );
}

how to use substr() function in jquery?

Extract characters from a string:

var str = "Hello world!";
var res = str.substring(1,4);

The result of res will be:

ell

http://www.w3schools.com/jsref/jsref_substring.asp

$('.dep_buttons').mouseover(function(){
    $(this).text().substring(0,25);
    if($(this).text().length > 30) {
        $(this).stop().animate({height:"150px"},150);
    }
    $(".dep_buttons").mouseout(function(){
        $(this).stop().animate({height:"40px"},150);
    });
});

Spring cron expression for every day 1:01:am

For my scheduler, I am using it to fire at 6 am every day and my cron notation is:

0 0 6 * * *

If you want 1:01:am then set it to

0 1 1 * * *

Complete code for the scheduler

@Scheduled(cron="0 1 1 * * *")
public void doScheduledWork() {
    //complete scheduled work
}

** VERY IMPORTANT

To be sure about the firing time correctness of your scheduler, you have to set zone value like this (I am in Istanbul):

@Scheduled(cron="0 1 1 * * *", zone="Europe/Istanbul")
public void doScheduledWork() {
    //complete scheduled work
}

You can find the complete time zone values from here.

Note: My Spring framework version is: 4.0.7.RELEASE

VBScript How can I Format Date?

'for unique file names I use

Dim ts, logfile, thisScript

thisScript = LEFT(Wscript.ScriptName,LEN(Wscript.ScriptName)-4) ' assuming .vbs extension

ts = timeStamp
logfile = thisScript & "_" & ts

' ======
Function timeStamp() 
    timeStamp = Year(Now) & "-" & _
    Right("0" & Month(Now),2)  & "-" & _
    Right("0" & Day(Now),2)  & "_" & _  
    Right("0" & Hour(Now),2) & _
    Right("0" & Minute(Now),2) '    '& _    Right("0" & Second(Now),2) 
End Function
' ======

How can I make my flexbox layout take 100% vertical space?

set the wrapper to height 100%

.vwrapper {
  display: flex;
  flex-direction: column;

  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: stretch;
  align-content: stretch;

  height: 100%;
}

and set the 3rd row to flex-grow

#row3 {
   background-color: green;
   flex: 1 1 auto;
   display: flex;
}

demo

How can I add a variable to console.log?

You can use another console method:

let name = prompt("what is your name?");
console.log(`story ${name} story`);

Creating C formatted strings (not printing them)

Don't use sprintf.
It will overflow your String-Buffer and crash your Program.
Always use snprintf

Query to get the names of all tables in SQL Server 2008 Database

sys.tables

Contains all tables. so exec this query to get all tables with details.

SELECT * FROM sys.tables

enter image description here

or simply select Name from sys.tables to get the name of all tables.

SELECT Name From sys.tables

How to install Hibernate Tools in Eclipse?

For Eclipse plugins, you just unzip them and drop the folder in the Eclipse\Plugins directory. Simple as that.

java.io.IOException: Server returned HTTP response code: 500

I had this problem i.e. works fine when pasted into browser but 505s when done through java. It was simply the spaces that needed to be escaped/encoded.

Generics/templates in python?

Python uses duck typing, so it doesn't need special syntax to handle multiple types.

If you're from a C++ background, you'll remember that, as long as the operations used in the template function/class are defined on some type T (at the syntax level), you can use that type T in the template.

So, basically, it works the same way:

  1. define a contract for the type of items you want to insert in the binary tree.
  2. document this contract (i.e. in the class documentation)
  3. implement the binary tree using only operations specified in the contract
  4. enjoy

You'll note however, that unless you write explicit type checking (which is usually discouraged), you won't be able to enforce that a binary tree contains only elements of the chosen type.

How do you add a Dictionary of items into another Dictionary

You can try this

var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

var temp = NSMutableDictionary(dictionary: dict1);
temp.addEntriesFromDictionary(dict2)

How to read appSettings section in the web.config file?

Here's the easy way to get access to the web.config settings anywhere in your C# project.

 Properties.Settings.Default

Use case:

litBodyText.Text = Properties.Settings.Default.BodyText;
litFootText.Text = Properties.Settings.Default.FooterText;
litHeadText.Text = Properties.Settings.Default.HeaderText;

Web.config file:

  <applicationSettings>
    <myWebSite.Properties.Settings> 
      <setting name="BodyText" serializeAs="String">
        <value>
          &lt;h1&gt;Hello World&lt;/h1&gt;
          &lt;p&gt;
      Ipsum Lorem
          &lt;/p&gt;
        </value>
      </setting>
      <setting name="HeaderText" serializeAs="String">
      My header text
        <value />
      </setting>
      <setting name="FooterText" serializeAs="String">
      My footer text
        <value />
      </setting>
    </myWebSite.Properties.Settings>
  </applicationSettings>

No need for special routines - everything is right there already. I'm surprised that no one has this answer for the best way to read settings from your web.config file.

Does a TCP socket connection have a "keep alive"?

TCP keepalive and HTTP keepalive are very different concepts. In TCP, the keepalive is the administrative packet sent to detect stale connection. In HTTP, keepalive means the persistent connection state.

This is from TCP specification,

Keep-alive packets MUST only be sent when no data or acknowledgement packets have been received for the connection within an interval. This interval MUST be configurable and MUST default to no less than two hours.

As you can see, the default TCP keepalive interval is too long for most applications. You might have to add keepalive in your application protocol.

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

I can't be satisfied by the answers calling for a English-only solution based on manual formats. I've been looking for a proper solution for a while now and I finally found it.

You should be using RuleBasedNumberFormat. It works perfectly and it's respectful of the Locale.

Are list-comprehensions and functional functions faster than "for loops"?

I have managed to modify some of @alpiii's code and discovered that List comprehension is a little faster than for loop. It might be caused by int(), it is not fair between list comprehension and for loop.

from functools import reduce
import datetime

def time_it(func, numbers, *args):
    start_t = datetime.datetime.now()
    for i in range(numbers):
        func(args[0])
    print (datetime.datetime.now()-start_t)

def square_sum1(numbers):
    return reduce(lambda sum, next: sum+next*next, numbers, 0)

def square_sum2(numbers):
    a = []
    for i in numbers:
        a.append(i*2)
    a = sum(a)
    return a

def square_sum3(numbers):
    sqrt = lambda x: x*x
    return sum(map(sqrt, numbers))

def square_sum4(numbers):
    return(sum([i*i for i in numbers]))

time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
0:00:00.101122 #Reduce

0:00:00.089216 #For loop

0:00:00.101532 #Map

0:00:00.068916 #List comprehension

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

For me, the problem was passing in a larger than normally expected HTTP header. I resolved it by setting maxHttpHeaderSize="1048576" attribute on the Connector node in server.xml.

How can I count the number of matches for a regex?

Use the below code to find the count of number of matches that the regex finds in your input

        Pattern p = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);// "regex" here indicates your predefined regex.
        Matcher m = p.matcher(pattern); // "pattern" indicates your string to match the pattern against with
        boolean b = m.matches();
        if(b)
        count++;
        while (m.find())
        count++;

This is a generalized code not specific one though, tailor it to suit your need

Please feel free to correct me if there is any mistake.

Simplest way to form a union of two lists

If it is two IEnumerable lists you can't use AddRange, but you can use Concat.

IEnumerable<int> first = new List<int>{1,1,2,3,5};
IEnumerable<int> second = new List<int>{8,13,21,34,55};

var allItems = first.Concat(second);
// 1,1,2,3,5,8,13,21,34,55

How to make PyCharm always show line numbers

Using Search bar

  1. Press 2 times Shift
  2. Paste /editor /appearance/ and then
  3. Click on Show line numbers toggle button

For Windows and Linux

File | Settings | Editor | General | Appearance 

For macOS

IntelliJ IDEA | Preferences | Editor | General | Appearance 

Using shortcut

Ctrl+Alt+S

Then

Editor > General > Appearance

Click on Show line numbers toggle button.


Pycharm Official Doc (Appearance)

Select Rows with id having even number

Sql Server we can use %

select * from orders where ID % 2 = 0;

This can be used in both Mysql and oracle. It is more affection to use mod function that %.

select * from orders where mod(ID,2) = 0

Why is textarea filled with mysterious white spaces?

Also, when you say that the cursor is in the "middle" of the textarea, it makes me think you could also either have extra padding or text-align: center defined somewhere in your CSS.

SyntaxError: Unexpected token o in JSON at position 1

Don't ever use JSON.parse without wrapping it in try-catch block:

// payload 
let userData = null;

try {
    // Parse a JSON
    userData = JSON.parse(payload); 
} catch (e) {
    // You can read e for more info
    // Let's assume the error is that we already have parsed the payload
    // So just return that
    userData = payload;
}

// Now userData is the parsed result

Concatenating elements in an array to a string

Example using Java 8.

  String[] arr = {"1", "2", "3"};
  String join = String.join("", arr);

I hope that helps

How to bind Events on Ajax loaded Content?

For ASP.NET try this:

<script type="text/javascript">
    Sys.Application.add_load(function() { ... });
</script>

This appears to work on page load and on update panel load

Please find the full discussion here.

What is the best Java email address validation method?

Although there are many alternatives to Apache commons, their implementations are rudimentary at best (like Apache commons' implementation itself) and even dead wrong in other cases.

I'd also stay away from so called simple 'non-restrictive' regex; there's no such thing. For example @ is allowed multiple times depending on context, how do you know the required one is there? Simple regex won't understand it, even though the email should be valid. Anything more complex becomes error-prone or even contain hidden performance killers. How are you going to maintain something like this?

The only comprehensive RFC compliant regex based validator I'm aware of is email-rfc2822-validator with its 'refined' regex appropriately named Dragons.java. It supports only the older RFC-2822 spec though, although appropriate enough for modern needs (RFC-5322 updates it in areas already out of scope for daily use cases).

But really what you want is a lexer that properly parses a string and breaks it up into the component structure according to the RFC grammar. EmailValidator4J seems promising in that regard, but is still young and limited.

Another option you have is using a webservice such as Mailgun's battle-tested validation webservice or Mailboxlayer API (just took the first Google results). It is not strictly RFC compliant, but works well enough for modern needs.

Update Jenkins from a war file

#on ubuntu, in /usr/share/jenkins:

sudo service jenkins stop
sudo mv jenkins.war jenkins.war.old
sudo wget https://updates.jenkins-ci.org/latest/jenkins.war
sudo service jenkins start

C++ initial value of reference to non-const must be an lvalue

When you call test with &nKByte, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.

Either do not use a reference for the argument, or better yet don't use a pointer.

How to install MySQLi on MacOS

Here is the link for installation details: http://php.net/manual/en/mysqli.installation.php

If you are using Windows or Linux:
- The MySQLi extension is automatically installed in most cases, when PHP & MySQL package is installed.

Raise warning in Python without interrupting program

By default, unlike an exception, a warning doesn't interrupt.

After import warnings, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning by default.

>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.

To simply use a preexisting class instead, e.g. DeprecationWarning:

>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.

Creating a custom warning class is similar to creating a custom exception class:

>>> class MyCustomWarning(UserWarning):
...     pass
... 
... warnings.warn('This is my custom warning.', MyCustomWarning)

<string>:1: MyCustomWarning: This is my custom warning.

For testing, consider assertWarns or assertWarnsRegex.


As an alternative, especially for standalone applications, consider the logging module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.

How to URL encode in Python 3?

You misread the documentation. You need to do two things:

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL

Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

from urllib.parse import urlencode, quote_plus

payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'

JavaScript: Check if mouse button down?

You need to handle the MouseDown and MouseUp and set some flag or something to track it "later down the road"... :(

What is the best way to generate a unique and short file name in Java

Combining other answers, why not use the ms timestamp with a random value appended; repeat until no conflict, which in practice will be almost never.

For example: File-ccyymmdd-hhmmss-mmm-rrrrrr.txt

Get current index from foreach loop

You have two options here, 1. Use for instead for foreach for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:

int i = 0; // for index
foreach (var row in list)
{
    bool IsChecked;// assign value to this variable
    if (IsChecked)
    {    
       // use i value here                
    }
    i++; // will increment i in each iteration
}

How do I change column default value in PostgreSQL?

'SET' is forgotten

ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';

Javascript find json value

var obj = [
  {"name": "Afghanistan", "code": "AF"}, 
  {"name": "Åland Islands", "code": "AX"}, 
  {"name": "Albania", "code": "AL"}, 
  {"name": "Algeria", "code": "DZ"}
];

// the code you're looking for
var needle = 'AL';

// iterate over each element in the array
for (var i = 0; i < obj.length; i++){
  // look for the entry with a matching `code` value
  if (obj[i].code == needle){
     // we found it
    // obj[i].name is the matched result
  }
}

What do we mean by Byte array?

From wikipedia:

In computer science, an array data structure or simply array is a data structure consisting of a collection of elements (values or variables), each identified by one or more integer indices, stored so that the address of each element can be computed from its index tuple by a simple mathematical formula.

So when you say byte array, you're referring to an array of some defined length (e.g. number of elements) that contains a collection of byte (8 bits) sized elements.

In C# a byte array could look like:

byte[] bytes = { 3, 10, 8, 25 };

The sample above defines an array of 4 elements, where each element can be up to a Byte in length.

what is right way to do API call in react js?

As best place and practice for external API calls is React Lifecycle method componentDidMount(), where after the execution of the API call you should update the local state to be triggered new render() method call, then the changes in the updated local state will be applied on the component view.

As other option for initial external data source call in React is pointed the constructor() method of the class. The constructor is the first method executed on initialization of the component object instance. You could see this approach in the documentation examples for Higher-Order Components.

The method componentWillMount() and UNSAFE_componentWillMount() should not be used for external API calls, because they are intended to be deprecated. Here you could see common reasons, why this method will be deprecated.

Anyway you must never use render() method or method directly called from render() as a point for external API call. If you do this your application will be blocked.

Configuring ObjectMapper in Spring

To configure a message converter in plain spring-web, in this case to enable the Java 8 JSR-310 JavaTimeModule, you first need to implement WebMvcConfigurer in your @Configuration class and then override the configureMessageConverters method:

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modules(new JavaTimeModule(), new Jdk8Module()).build()
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
}

Like this you can register any custom defined ObjectMapper in a Java-based Spring configuration.

Ternary operator (?:) in Bash

(( a = b==5 ? c : d )) # string + numeric

dropping infinite values from dataframes in pandas?

With option context, this is possible without permanently setting use_inf_as_na. For example:

with pd.option_context('mode.use_inf_as_na', True):
    df = df.dropna(subset=['col1', 'col2'], how='all')

Of course it can be set to treat inf as NaN permanently with

pd.set_option('use_inf_as_na', True)

For older versions, replace use_inf_as_na with use_inf_as_null.

How Stuff and 'For Xml Path' work in SQL Server?

In for xml path, if we define any value like [ for xml path('ENVLOPE') ] then these tags will be added with each row:

<ENVLOPE>
</ENVLOPE>

How to disable or enable viewpager swiping in android

I found another solution that worked for me follow this link

https://stackoverflow.com/a/42687397/4559365

It basically overrides the method canScrollHorizontally to disable swiping by finger. Howsoever setCurrentItem still works.

How to change the session timeout in PHP?

Put $_SESSION['login_time'] = time(); into the previous authentication page. And the snipped below in every other page where you want to check the session time-out.

if(time() - $_SESSION['login_time'] >= 1800){
    session_destroy(); // destroy session.
    header("Location: logout.php");
    die(); // See https://thedailywtf.com/articles/WellIntentioned-Destruction
    //redirect if the page is inactive for 30 minutes
}
else {        
   $_SESSION['login_time'] = time();
   // update 'login_time' to the last time a page containing this code was accessed.
}

Edit : This only works if you already used the tweaks in other posts, or disabled Garbage Collection, and want to manually check the session duration. Don't forget to add die() after a redirect, because some scripts/robots might ignore it. Also, directly destroying the session with session_destroy() instead of relying on a redirect for that might be a better option, again, in case of a malicious client or a robot.

Build error, This project references NuGet

It's a bit old post but I recently ran into this issue. All I did was deleted all the nuget packages from packages folder and restored it. I was able to build the solution successfully. Hopefully helpful to someone.

CSS body background image fixed to full screen even when zooming in/out

Add this in your css file:

.custom_class
 {
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
 }

and then, in your .html (or .php) file call this class like that:

<div class="custom_class">
   ...
</div>

How to turn on WCF tracing?

In your web.config (on the server) add

<system.diagnostics>
 <sources>
  <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
   <listeners>
    <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\logs\Traces.svclog"/>
   </listeners>
  </source>
 </sources>
</system.diagnostics>

JavaScript Chart Library

Check out Google Visualization API, which is kind of a generalization of the simpler Chart API

dotnet ef not found in .NET Core 3

For me, The problem was solved after I close Visual Studio and Open it again

How to force addition instead of concatenation in javascript

Should also be able to do this:

total += eval(myInt1) + eval(myInt2) + eval(myInt3);

This helped me in a different, but similar, situation.

Listing all the folders subfolders and files in a directory using php

define ('PATH', $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']));
$dir = new DirectoryIterator(PATH);
echo '<ul>';
foreach ($dir as $fileinfo)
{   
    if (!$fileinfo->isDot()) {
       echo '<li><a href="'.$fileinfo->getFilename().'" target="_blank">'.$fileinfo->getFilename().'</a></li>'; 

       echo '</li>';
    }
}
echo '</ul>';

c++ array assignment of multiple values

const static int newvals[] = {34,2,4,5,6};

std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);

sed: print only matching group

I agree with @kent that this is well suited for grep -o. If you need to extract a group within a pattern, you can do it with a 2nd grep.

# To extract \1 from /xx([0-9]+)yy/
$ echo "aa678bb xx123yy xx4yy aa42 aa9bb" | grep -Eo 'xx[0-9]+yy' | grep -Eo '[0-9]+'
123
4

# To extract \1 from /a([0-9]+)b/
$ echo "aa678bb xx123yy xx4yy aa42 aa9bb" | grep -Eo 'a[0-9]+b' | grep -Eo '[0-9]+'
678
9

I generally cringe when I see 2 calls to grep/sed/awk piped together, but it's not always wrong. While we should exercise our skills of doing things efficiently, "A foolish consistency is the hobgoblin of little minds", and "Real artists ship".

Can't build create-react-app project with custom PUBLIC_URL

Actually the way of setting environment variables is different between different Operating System.

Windows (cmd.exe)

set PUBLIC_URL=http://xxxx.com&&npm start

(Note: the lack of whitespace is intentional.)

Linux, macOS (Bash)

 PUBLIC_URL=http://xxxx.com npm start

Recommended: cross-env

{
  "scripts": {
    "serve": "cross-env PUBLIC_URL=http://xxxx.com npm start"
  }
}

ref: create-react-app/README.md#adding-temporary-environment-variables-in-your-shell at master · facebookincubator/create-react-app

Convert double to BigDecimal and set BigDecimal Precision

The String.format syntax helps us convert doubles and BigDecimals to strings of whatever precision.

This java code:

double dennis = 0.00000008880000d;
System.out.println(dennis);
System.out.println(String.format("%.7f", dennis));
System.out.println(String.format("%.9f", new BigDecimal(dennis)));
System.out.println(String.format("%.19f", new BigDecimal(dennis)));

Prints:

8.88E-8
0.0000001
0.000000089
0.0000000888000000000

Making HTML page zoom by default

In js you can change zoom by

document.body.style.zoom="90%"

But it doesn't work in FF http://caniuse.com/#search=zoom

For ff you can try

-moz-transform: scale(0.9);

And check next topic How can I zoom an HTML element in Firefox and Opera?

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Although an oldie, what forget is that they should wrap their code block and then catch the error and then test...

function checkup( t ){
  try{
    for(p in t){
      if( p.hasOwnProperty( t ) ){
        return true;
      }
    }
    return false;
  }catch(e){
    console.log("ERROR : "+e);
    return e;
  }
}

So you really don't have to check for a potential problem before hand, you simply catch it and then deal with it how you want.

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

I've faced same problem and came across to this thread but my problem was with upstream. Below git command worked for me.

Syntax

git checkout {remoteName}/{branch} -- {../path/file.js}

Example

git checkout upstream/develop -- public/js/index.js

Whitespaces in java

If you want to consider a regular expression based way of doing it

if(text.split("\\s").length > 1){
    //text contains whitespace
}

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.

$products = DB::table('products AS pr')
        ->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
        ->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
        ->orderBy('pr.id', 'desc')
        ->get();

Hope this helps.

How to check the differences between local and github before the pull

git pull is really equivalent to running git fetch and then git merge. The git fetch updates your so-called "remote-tracking branches" - typically these are ones that look like origin/master, github/experiment, etc. that you see with git branch -r. These are like a cache of the state of branches in the remote repository that are updated when you do git fetch (or a successful git push).

So, suppose you've got a remote called origin that refers to your GitHub repository, you would do:

git fetch origin

... and then do:

git diff master origin/master

... in order to see the difference between your master, and the one on GitHub. If you're happy with those differences, you can merge them in with git merge origin/master, assuming master is your current branch.

Personally, I think that doing git fetch and git merge separately is generally a good idea.

Postgresql Select rows where column = array

In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:

SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])

I spent almost 6 hours before I stumble on the post.

How to Empty Caches and Clean All Targets Xcode 4 and later

Command-Option-Shift-K to clean out the build folder. Even better, quit Xcode and clean out ~/Library/Developer/Xcode/DerivedData manually. Remove all its contents because there's a bug where Xcode will run an old version of your project that's in there somewhere. (Xcode 4.2 will show you the Derived Data folder: choose Window > Organizer and switch to the Projects tab. Click the right-arrow to the right of the Derived Data folder name.)

In the simulator, choose iOS Simulator > Reset Content and Settings.

Finally, for completeness, you can delete the contents of /var/folders; some caching happens there too.

WARNING: Deleting /var/folders can cause issues, and you may need to repair or reinstall your operating system after doing so.

EDIT: I have just learned that if you are afraid to grapple with /var/folders/ you can use the following command in the Terminal to delete in a more targeted way:

rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache"

EDIT: For certain Swift-related problems I have found it useful to delete ~/Library/Caches/com.apple.dt.Xcode. You lose a lot when you do this, like your spare copies of the downloaded documentation doc sets, but it can be worth it.

What's the use of ob_start() in php?

this is to further clarify JD Isaaks answer ...

The problem you run into often is that you are using php to output html from many different php sources, and those sources are often, for whatever reason, outputting via different ways.

Sometimes you have literal html content that you want to directly output to the browser; other times the output is being dynamically created (server-side).

The dynamic content is always(?) going to be a string. Now you have to combine this stringified dynamic html with any literal, direct-to-display html ... into one meaningful html node structure.

This usually forces the developer to wrap all that direct-to-display content into a string (as JD Isaak was discussing) so that it can be properly delivered/inserted in conjunction with the dynamic html ... even though you don't really want it wrapped.

But by using ob_## methods you can avoid that string-wrapping mess. The literal content is, instead, output to the buffer. Then in one easy step the entire contents of the buffer (all your literal html), is concatenated into your dynamic-html string.

(My example shows literal html being output to the buffer, which is then added to a html-string ... look also at JD Isaaks example to see string-wrapping-of-html).

<?php // parent.php

//---------------------------------
$lvs_html  = "" ;

$lvs_html .= "<div>html</div>" ;
$lvs_html .= gf_component_assembler__without_ob( ) ;
$lvs_html .= "<div>more html</div>" ;

$lvs_html .= "----<br/>" ;

$lvs_html .= "<div>html</div>" ;
$lvs_html .= gf_component_assembler__with_ob( ) ;
$lvs_html .= "<div>more html</div>" ;

echo $lvs_html ;    
//    02 - component contents
//    html
//    01 - component header
//    03 - component footer
//    more html
//    ----
//    html
//    01 - component header
//    02 - component contents
//    03 - component footer
//    more html 

//---------------------------------
function gf_component_assembler__without_ob( ) 
  { 
    $lvs_html  = "<div>01 - component header</div>" ; // <table ><tr>" ;
    include( "component_contents.php" ) ;
    $lvs_html .= "<div>03 - component footer</div>" ; // </tr></table>" ;

    return $lvs_html ;
  } ;

//---------------------------------
function gf_component_assembler__with_ob( ) 
  { 
    $lvs_html  = "<div>01 - component header</div>" ; // <table ><tr>" ;

        ob_start();
        include( "component_contents.php" ) ;
    $lvs_html .= ob_get_clean();

    $lvs_html .= "<div>03 - component footer</div>" ; // </tr></table>" ;

    return $lvs_html ;
  } ;

//---------------------------------
?>

<!-- component_contents.php -->
  <div>
    02 - component contents
  </div>

NGINX - No input file specified. - php Fast/CGI

Same problem.

Reason old open_basedir settings copied with a rogue user.ini file in a backup

Solution delete it

Specifying and saving a figure with exact size in pixels

Based on the accepted response by tiago, here is a small generic function that exports a numpy array to an image having the same resolution as the array:

import matplotlib.pyplot as plt
import numpy as np

def export_figure_matplotlib(arr, f_name, dpi=200, resize_fact=1, plt_show=False):
    """
    Export array as figure in original resolution
    :param arr: array of image to save in original resolution
    :param f_name: name of file where to save figure
    :param resize_fact: resize facter wrt shape of arr, in (0, np.infty)
    :param dpi: dpi of your screen
    :param plt_show: show plot or not
    """
    fig = plt.figure(frameon=False)
    fig.set_size_inches(arr.shape[1]/dpi, arr.shape[0]/dpi)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    ax.imshow(arr)
    plt.savefig(f_name, dpi=(dpi * resize_fact))
    if plt_show:
        plt.show()
    else:
        plt.close()

As said in the previous reply by tiago, the screen DPI needs to be found first, which can be done here for instance: http://dpi.lv

I've added an additional argument resize_fact in the function which which you can export the image to 50% (0.5) of the original resolution, for instance.

CSS - Expand float child DIV height to parent's height

CSS table display is ideal for this:

_x000D_
_x000D_
.parent {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
}_x000D_
.parent > div {_x000D_
  display: table-cell;_x000D_
}_x000D_
.child-left {_x000D_
  background: powderblue;_x000D_
}_x000D_
.child-right {_x000D_
  background: papayawhip;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child-left">Short</div>_x000D_
  <div class="child-right">Tall<br>Tall</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Original answer (assumed any column could be taller):

You're trying to make the parent's height dependent on the children's height and children's height dependent on parent's height. Won't compute. CSS Faux columns is the best solution. There's more than one way of doing that. I'd rather not use JavaScript.

Increase distance between text and title on the y-axis

From ggplot2 2.0.0 you can use the margin = argument of element_text() to change the distance between the axis title and the numbers. Set the values of the margin on top, right, bottom, and left side of the element.

ggplot(mpg, aes(cty, hwy)) + geom_point()+
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))

margin can also be used for other element_text elements (see ?theme), such as axis.text.x, axis.text.y and title.

addition

in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top"), you'll need a different theme setting - e.g. axis.title.x.top. See https://github.com/tidyverse/ggplot2/issues/4343.

Convert a list to a string in C#

The direct answer to your question is String.Join as others have mentioned.

However, if you need some manipulations, you can use Aggregate:

List<string> employees = new List<string>();
employees.Add("e1");
employees.Add("e2");
employees.Add("e3");

string employeesString = "'" + employees.Aggregate((x, y) => x + "','" + y) + "'";
Console.WriteLine(employeesString);
Console.ReadLine();

What is the difference between an Instance and an Object?

When a variable is declared of a custom type (class), only a reference is created, which is called an object. At this stage, no memory is allocated to this object. It acts just as a pointer (to the location where the object will be stored in future). This process is called 'Declaration'.

Employee e; // e is an object

On the other hand, when a variable of custom type is declared using the new operator, which allocates memory in heap to this object and returns the reference to the allocated memory. This object which is now termed as instance. This process is called 'Instantiation'.

Employee e = new Employee(); // e is an instance

On the other hand, in some languages such as Java, an object is equivalent to an instance, as evident from the line written in Oracle's documentation on Java:

Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

Truncate number to two decimal places without rounding

This worked well for me. I hope it will fix your issues too.

function toFixedNumber(number) {
    const spitedValues = String(number.toLocaleString()).split('.');
    let decimalValue = spitedValues.length > 1 ? spitedValues[1] : '';
    decimalValue = decimalValue.concat('00').substr(0,2);

    return '$'+spitedValues[0] + '.' + decimalValue;
}

// 5.56789      ---->  $5.56
// 0.342        ---->  $0.34
// -10.3484534  ---->  $-10.34 
// 600          ---->  $600.00

_x000D_
_x000D_
function convertNumber(){_x000D_
  var result = toFixedNumber(document.getElementById("valueText").value);_x000D_
  document.getElementById("resultText").value = result;_x000D_
}_x000D_
_x000D_
_x000D_
function toFixedNumber(number) {_x000D_
        const spitedValues = String(number.toLocaleString()).split('.');_x000D_
        let decimalValue = spitedValues.length > 1 ? spitedValues[1] : '';_x000D_
        decimalValue = decimalValue.concat('00').substr(0,2);_x000D_
_x000D_
        return '$'+spitedValues[0] + '.' + decimalValue;_x000D_
}
_x000D_
<div>_x000D_
  <input type="text" id="valueText" placeholder="Input value here..">_x000D_
  <br>_x000D_
  <button onclick="convertNumber()" >Convert</button>_x000D_
  <br><hr>_x000D_
  <input type="text" id="resultText" placeholder="result" readonly="true">_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is a C++ delegate?

A delegate is a class that wraps a pointer or reference to an object instance, a member method of that object's class to be called on that object instance, and provides a method to trigger that call.

Here's an example:

template <class T>
class CCallback
{
public:
    typedef void (T::*fn)( int anArg );

    CCallback(T& trg, fn op)
        : m_rTarget(trg)
        , m_Operation(op)
    {
    }

    void Execute( int in )
    {
        (m_rTarget.*m_Operation)( in );
    }

private:

    CCallback();
    CCallback( const CCallback& );

    T& m_rTarget;
    fn m_Operation;

};

class A
{
public:
    virtual void Fn( int i )
    {
    }
};


int main( int /*argc*/, char * /*argv*/ )
{
    A a;
    CCallback<A> cbk( a, &A::Fn );
    cbk.Execute( 3 );
}

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

Ruby: How to get the first character of a string

Any of these methods will work:

name = 'Smith'
puts name.[0..0] # => S
puts name.[0] # => S
puts name.[0,1] # => S
puts name.[0].chr # => S

QComboBox - set selected item based on the item's data

You lookup the value of the data with findData() and then use setCurrentIndex()

QComboBox* combo = new QComboBox;
combo->addItem("100",100.0);    // 2nd parameter can be any Qt type
combo->addItem .....

float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found
   combo->setCurrentIndex(index);
}

JavaFX: How to get stage from controller during initialization?

The simplest way to get stage object in controller is:

  1. Add an extra method in own created controller class like (it will be a setter method to set the stage in controller class),

    private Stage myStage;
    public void setStage(Stage stage) {
         myStage = stage;
    }
    
  2. Get controller in start method and set stage

    FXMLLoader loader = new FXMLLoader(getClass().getResource("MyFXML.fxml"));
    OwnController controller = loader.getController();
    controller.setStage(this.stage);
    
  3. Now you can access the stage in controller

Find index of a value in an array

If you want to find the word you can use

var word = words.Where(item => item.IsKey).First();

This gives you the first item for which IsKey is true (if there might be non you might want to use .FirstOrDefault()

To get both the item and the index you can use

KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();

Filtering a data frame by values in a column

The subset command is not necessary. Just use data frame indexing

studentdata[studentdata$Drink == 'water',]

Read the warning from ?subset

This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like ‘[’, and in particular the non-standard evaluation of argument ‘subset’ can have unanticipated consequences.

How do I implement basic "Long Polling"?

Here is a simple long-polling example in PHP by Erik Dubbelboer using the Content-type: multipart/x-mixed-replace header:

<?

header('Content-type: multipart/x-mixed-replace; boundary=endofsection');

// Keep in mind that the empty line is important to separate the headers
// from the content.
echo 'Content-type: text/plain

After 5 seconds this will go away and a cat will appear...
--endofsection
';
flush(); // Don't forget to flush the content to the browser.


sleep(5);


echo 'Content-type: image/jpg

';

$stream = fopen('cat.jpg', 'rb');
fpassthru($stream);
fclose($stream);

echo '
--endofsection
';

And here is a demo:

http://dubbelboer.com/multipart.php

Loop and get key/value pair for JSON array using jQuery

You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
    //display the key and value pair
    alert(k + ' is ' + v);
});

Live demo.

nginx error "conflicting server name" ignored

There should be only one localhost defined, check sites-enabled or nginx.conf.

Check if textbox has empty value

Use the following to check if text box is empty or have more than 1 white spaces

var name = jQuery.trim($("#ContactUsName").val());

if ((name.length == 0))
{
    Your code 
}
else
{
    Your code
}

Javascript - remove an array item by value

As a variant

delete array[array.indexOf(item)];

If you know nothing about delete operator, DON'T use this.

Gerrit error when Change-Id in commit messages are missing

You need to follow below 2 steps instructions:

[Issue] remote: Hint: To automatically insert Change-Id, install the hook:

1) gitdir=$(git rev-parse --git-dir);

2) scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg ${gitdir}/hooks/

normally $gitdir = ".git". You need to update the username and the Gerrit link.

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

To change the Prevent saving changes that require the table re-creation option, follow these steps:

Open SQL Server Management Studio (SSMS). On the Tools menu, click Options.

In the navigation pane of the Options window, click Designers.

Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

Note: If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.

enter image description here

Check whether an input string contains a number in javascript

You can also try lodash:

const isNumeric = number => 
  _.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))

How do I debug Node.js applications?

Visual Studio Code will be my choice for debugging. No overhead of installing any tools or npm install stuff. Just set the starting point of your app in package.json and VSCode will automatically create a configuration file inside your solution. It's build on Electron, on which editors like Atom are built.

VS Code gives similar debugging experience as you might have had in other IDEs like VS, Eclipse, etc.

enter image description here enter image description here

Differences Between vbLf, vbCrLf & vbCr Constants

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.

You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:

  1. move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
  2. move the paper up by the width of one line. This is a line feed.

In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.

The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).

So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

plot data from CSV file with matplotlib

According to the docs numpy.loadtxt is

a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.

so there are only a few options to handle more complicated files. As mentioned numpy.genfromtxt has more options. So as an example you could use

import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
                     skip_footer=10, names=['x', 'y', 'z'])

to read the data and assign names to the columns (or read a header line from the file with names=True) and than plot it with

ax1.plot(data['x'], data['y'], color='r', label='the data')

I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython or by using an IDE like spider if you prefer to read them rendered as HTML.

Class Not Found: Empty Test Suite in IntelliJ

solved by manually run testClasses task before running unit test.

You must add a reference to assembly 'netstandard, Version=2.0.0.0

I was facing this problem when trying to add a .NETStandard dependency to a .NET4.6.1 library, and compiling it in Linux with Mono 4.6.2 (the version that comes with Ubuntu 16.04).

I finally solved it today; the solution requires to do both of these things:

  1. Change <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion> to <TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion> in the .csproj file.
  2. Upgrade your mono to a newer version. I believe 5.x should work, but to be sure, you can just install Ubuntu 20.04 (which at the time of writing is only in preview), which includes Mono 6.8.0.105.

When should we call System.exit in Java

If you have another program running in the JVM and you use System.exit, that second program will be closed, too. Imagine for example that you run a java job on a cluster node and that the java program that manages the cluster node runs in the same JVM. If the job would use System.exit it would not only quit the job but also "shut down the complete node". You would not be able to send another job to that cluster node since the management program has been closed accidentally.

Therefore, do not use System.exit if you want to be able to control your program from another java program within the same JVM.

Use System.exit if you want to close the complete JVM on purpose and if you want to take advantage of the possibilities that have been described in the other answers (e.g. shut down hooks: Java shutdown hook, non-zero return value for command line calls: How to get the exit status of a Java program in Windows batch file).

Also have a look at Runtime Exceptions: System.exit(num) or throw a RuntimeException from main?

Python - Extracting and Saving Video Frames

To extend on this question (& answer by @user2700065) for a slightly different cases, if anyone does not want to extract every frame but wants to extract frame every one second. So a 1-minute video will give 60 frames(images).

import sys
import argparse

import cv2
print(cv2.__version__)

def extractImages(pathIn, pathOut):
    count = 0
    vidcap = cv2.VideoCapture(pathIn)
    success,image = vidcap.read()
    success = True
    while success:
        vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))    # added this line 
        success,image = vidcap.read()
        print ('Read a new frame: ', success)
        cv2.imwrite( pathOut + "\\frame%d.jpg" % count, image)     # save frame as JPEG file
        count = count + 1

if __name__=="__main__":
    a = argparse.ArgumentParser()
    a.add_argument("--pathIn", help="path to video")
    a.add_argument("--pathOut", help="path to images")
    args = a.parse_args()
    print(args)
    extractImages(args.pathIn, args.pathOut)

How to fill Dataset with multiple tables?

Method Load of DataTable executes NextResult on the DataReader, so you shouldn't call NextResult explicitly when using Load, otherwise odd tables in the sequence would be omitted.

Here is a generic solution to load multiple tables using a DataReader.

// your command initialization code here
// ...
DataSet ds = new DataSet();
DataTable t;
using (DbDataReader reader = command.ExecuteReader())
{
  while (!reader.IsClosed)
  {
    t = new DataTable();
    t.Load(rs);
    ds.Tables.Add(t);
  }
}

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

Wrong port number in my case. Check if port number when starting Selenium server is the same as in your script.

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

You must have to define no-args or default constructor if you are creating your own constructor.

You can read why default or no argument constructor is required.

why-default-or-no-argument-constructor-java-class.html

Android: Force EditText to remove focus?

In the comments you asked if another view can be focused instead of the EditText. Yes it can. Use .requestFocus() method for the view you want to be focused at the beginning (in onCreate() method)

Also focusing other view will cut out some amount of code. (code for hiding the keyboard for example)

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

I am using wildfly 10 for javaee container . I had experienced "Target Unreachable, 'entity' returned null" issue. Thanks for suggestions by BalusC but the my issue out of the solutions explained. Accidentally using "import com.sun.istack.logging.Logger;" instead of "import org.jboss.logging.Logger;" caused CDI implemented JSF EL. Hope it helps to improve solution .

How to view files in binary from bash?

xxd does both binary and hexadecimal.

bin:

xxd -b file

hex:

xxd file

Common HTTPclient and proxy

Here is how I solved this problem for the old (< 4.3) HttpClient (which I cannot upgrade), using the answer of Santosh Singh (who I gave a +1):

HttpClient httpclient = new HttpClient();
if (System.getProperty("http.proxyHost") != null) {
  try {
    HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
    hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort")));
    httpclient.setHostConfiguration(hostConfiguration);
    this.getLogger().warn("USING PROXY: "+httpclient.getHostConfiguration().getProxyHost());
  } catch (Exception e) {
    throw new ProcessingException("Cannot set proxy!", e);
  }
}

wget: unable to resolve host address `http'

remove the http or https from wget https:github.com/facebook/facebook-php-sdk/archive/master.zip . this worked fine for me.

Setting an environment variable before a command in Bash is not working for the second command in a pipe

How about exporting the variable, but only inside the subshell?:

(export FOO=bar && somecommand someargs | somecommand2)

Keith has a point, to unconditionally execute the commands, do this:

(export FOO=bar; somecommand someargs | somecommand2)

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

How do I reset a jquery-chosen select option with jQuery?

If you are using chosen, a jquery plugin, then to refresh or clear the content of the dropdown use:

$('#dropdown_id').empty().append($('< option>'))

dropdown_id.chosen().trigger("chosen:updated")

chosen:updated event will re-build itself based on the updated content.

Sorting multiple keys with Unix sort

The -k option is what you want.

-k 1.4,1.5n -k 1.14,1.15n

Would use character positions 4-5 in the first field (it's all one field for fixed width) and sort numerically as the first key.

The second key would be characters 14-15 in the first field also.

(edit)

Example (all I have is DOS/cygwin handy):

dir | \cygwin\bin\sort.exe -k 1.4,1.5n -k 1.40,1.60r

for the data:

12/10/2008  01:10 PM         1,564,990 outfile.txt

Sorts the directory listing by month number (pos 4-5) numerically, and then by filename (pos 40-60) in reverse. Since there are no tabs, it's all field 1 to sort.

How to align text below an image in CSS?

Easiest way excpecially if you don't know images widths is to put the caption in it's own div element an define it to be cleared:both !

...

<div class="pics">  
  <img class="marq" src="pic_1.jpg" />
  <div class="caption">My image 1</div>
</div>  
  <div class="pics">    
  <img class="marq" src="pic_2.jpg" />
  <div class="caption">My image 2</div>
  </div>

...

and in style-block define

div.caption: {
  float: left;
  clear: both;
}   

Making href (anchor tag) request POST instead of GET?

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

Best way to parse command line arguments in C#?

This is a handler I wrote based on the Novell Options class.

This one is aimed at console applications that execute a while (input !="exit") style loop, an interactive console such as an FTP console for example.

Example usage:

static void Main(string[] args)
{
    // Setup
    CommandHandler handler = new CommandHandler();
    CommandOptions options = new CommandOptions();

    // Add some commands. Use the v syntax for passing arguments
    options.Add("show", handler.Show)
        .Add("connect", v => handler.Connect(v))
        .Add("dir", handler.Dir);

    // Read lines
    System.Console.Write(">");
    string input = System.Console.ReadLine();

    while (input != "quit" && input != "exit")
    {
        if (input == "cls" || input == "clear")
        {
            System.Console.Clear();
        }
        else
        {
            if (!string.IsNullOrEmpty(input))
            {
                if (options.Parse(input))
                {
                    System.Console.WriteLine(handler.OutputMessage);
                }
                else
                {
                    System.Console.WriteLine("I didn't understand that command");
                }

            }

        }

        System.Console.Write(">");
        input = System.Console.ReadLine();
    }
}

And the source:

/// <summary>
/// A class for parsing commands inside a tool. Based on Novell Options class (http://www.ndesk.org/Options).
/// </summary>
public class CommandOptions
{
    private Dictionary<string, Action<string[]>> _actions;
    private Dictionary<string, Action> _actionsNoParams;

    /// <summary>
    /// Initializes a new instance of the <see cref="CommandOptions"/> class.
    /// </summary>
    public CommandOptions()
    {
        _actions = new Dictionary<string, Action<string[]>>();
        _actionsNoParams = new Dictionary<string, Action>();
    }

    /// <summary>
    /// Adds a command option and an action to perform when the command is found.
    /// </summary>
    /// <param name="name">The name of the command.</param>
    /// <param name="action">An action delegate</param>
    /// <returns>The current CommandOptions instance.</returns>
    public CommandOptions Add(string name, Action action)
    {
        _actionsNoParams.Add(name, action);
        return this;
    }

    /// <summary>
    /// Adds a command option and an action (with parameter) to perform when the command is found.
    /// </summary>
    /// <param name="name">The name of the command.</param>
    /// <param name="action">An action delegate that has one parameter - string[] args.</param>
    /// <returns>The current CommandOptions instance.</returns>
    public CommandOptions Add(string name, Action<string[]> action)
    {
        _actions.Add(name, action);
        return this;
    }

    /// <summary>
    /// Parses the text command and calls any actions associated with the command.
    /// </summary>
    /// <param name="command">The text command, e.g "show databases"</param>
    public bool Parse(string command)
    {
        if (command.IndexOf(" ") == -1)
        {
            // No params
            foreach (string key in _actionsNoParams.Keys)
            {
                if (command == key)
                {
                    _actionsNoParams[key].Invoke();
                    return true;
                }
            }
        }
        else
        {
            // Params
            foreach (string key in _actions.Keys)
            {
                if (command.StartsWith(key) && command.Length > key.Length)
                {

                    string options = command.Substring(key.Length);
                    options = options.Trim();
                    string[] parts = options.Split(' ');
                    _actions[key].Invoke(parts);
                    return true;
                }
            }
        }

        return false;
    }
}

How do I set multipart in axios with react?

ok. I tried the above two ways but it didnt work for me. After trial and error i came to know that actually the file was not getting saved in 'this.state.file' variable.

fileUpload = (e) => {
    let data = e.target.files
    if(e.target.files[0]!=null){
        this.props.UserAction.fileUpload(data[0], this.fallBackMethod)
    }
}

here fileUpload is a different js file which accepts two params like this

export default (file , callback) => {
const formData = new FormData();
formData.append('fileUpload', file);

return dispatch => {
    axios.put(BaseUrl.RestUrl + "ur/url", formData)
        .then(response => {
            callback(response.data);
        }).catch(error => {
         console.log("*****  "+error)
    });
}

}

don't forget to bind method in the constructor. Let me know if you need more help in this.

How to consume REST in Java

Apache Http Client APIs are very commonly used for calling HTTP Rest services.

Here is one of example of consuming HTTP GET call.

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;

public class CallHTTPGetService {

public static void main(String[] args) throws ClientProtocolException, IOException {


    HttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest httpUriRequest = new HttpGet("URL");

    HttpResponse response = client.execute(httpUriRequest);
    System.out.println(response);

}
}

Use following maven dependency if using Maven project.

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.1</version>
    </dependency>

How to tell if homebrew is installed on Mac OS X

Once you install Homebrew, type command brew doctor in terminal.

  • If you get the following message:

    Your system is ready to brew

    then you are good to go and you have successfully installed homebrew.

  • If you get any warnings, you can try fixing it.

How to set the part of the text view is clickable

The solutions provided are pretty decent. However, I generally use a more simple solution.

Here is a linkify utility function

/**
 * Method is used to Linkify words in a TextView
 *
 * @param textView TextView who's text you want to change
 * @param textToLink The text to turn into a link
 * @param url   The url you want to send the user to
 */
fun linkify(textView: TextView, textToLink: String, url: String) {
    val pattern = Pattern.compile(textToLink)
    Linkify.addLinks(textView, pattern, url, { _, _, _ -> true })
    { _, _ -> "" }
}

Using this function is pretty simple. Here is an example

    // terms and privacy
    val tvTerms = findViewById<TextView>(R.id.tv_terms)
    val tvPrivacy = findViewById<TextView>(R.id.tv_privacy)
    Utils.linkify(tvTerms, resources.getString(R.string.terms),
            Constants.TERMS_URL)
    Utils.linkify(tvPrivacy, resources.getString(R.string.privacy),
            Constants.PRIVACY_URL)

Refreshing page on click of a button

I'd suggest <a href='page1.jsp'>Refresh</a>.

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I just had the same message with the following code (in IcedCoffeeScript):

f = (err,cb) ->
  cb null, true

await f defer err, res
console.log err if err  

This seemed to me like regular ICS code. I unfolded the await-defer construct to regular CoffeeScript:

f (err,res) ->
  console.log err if err

What really happend was that I tried to pass 1 callback function( with 2 parameters ) to function f expecting two parameters, effectively not setting cb inside f, which the compiler correctly reported as undefined is not a function.

The mistake happened because I blindly pasted callback-style boilerplate code. f doesn't need an err parameter passed into it, thus should simply be:

f = (cb) ->
  cb null, true
f (err,res) ->
  console.log err if err

In the general case, I'd recommend to double-check function signatures and invocations for matching arities. The call-stack in the error message should be able to provide helpful hints.

In your special case, I recommend looking for function definitions appearing twice in the merged file, with different signatures, or assignments to global variables holding functions.

How to Auto resize HTML table cell to fit the text size

If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.

If you don't want word wrap, assign the CSS style white-space: nowrap to the cells.

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

To easily understand the problem, imagine we wrote this code:

static void Main(string[] args)
{
    string[] test = new string[3];
    test[0]= "hello1";
    test[1]= "hello2";
    test[2]= "hello3";

    for (int i = 0; i <= 3; i++)
    {
        Console.WriteLine(test[i].ToString());
    }
}

Result will be:

hello1
hello2
hello3

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.

Size of array is 3 (indices 0, 1 and 2), but the for-loop loops 4 times (0, 1, 2 and 3).
So when it tries to access outside the bounds with (3) it throws the exception.

How to create a numpy array of all True or all False?

>>> a = numpy.full((2,4), True, dtype=bool)
>>> a[1][3]
True
>>> a
array([[ True,  True,  True,  True],
       [ True,  True,  True,  True]], dtype=bool)

numpy.full(Size, Scalar Value, Type). There is other arguments as well that can be passed, for documentation on that, check https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html

Can we pass an array as parameter in any function in PHP?

<?php

function takes_array($input)

{

    echo "$input[0] + $input[1] = ", $input[0]+$input[1];

}

?>

Android Studio - Failed to apply plugin [id 'com.android.application']

My problem was I had czech characters (c,ú,u,á,ó) in the project folder path.

EC2 instance types's exact network performance?

Bandwidth is tiered by instance size, here's a comprehensive answer:

For t2/m3/c3/c4/r3/i2/d2 instances:

  • t2.nano = ??? (Based on the scaling factors, I'd expect 20-30 MBit/s)
  • t2.micro = ~70 MBit/s (qiita says 63 MBit/s) - t1.micro gets about ~100 Mbit/s
  • t2.small = ~125 MBit/s (t2, qiita says 127 MBit/s, cloudharmony says 125 Mbit/s with spikes to 200+ Mbit/s)
  • *.medium = t2.medium gets 250-300 MBit/s, m3.medium ~400 MBit/s
  • *.large = ~450-600 MBit/s (the most variation, see below)
  • *.xlarge = 700-900 MBit/s
  • *.2xlarge = ~1 GBit/s +- 10%
  • *.4xlarge = ~2 GBit/s +- 10%
  • *.8xlarge and marked specialty = 10 Gbit, expect ~8.5 GBit/s, requires enhanced networking & VPC for full throughput

m1 small, medium, and large instances tend to perform higher than expected. c1.medium is another freak, at 800 MBit/s.

I gathered this by combing dozens of sources doing benchmarks (primarily using iPerf & TCP connections). Credit to CloudHarmony & flux7 in particular for many of the benchmarks (note that those two links go to google searches showing the numerous individual benchmarks).

Caveats & Notes:

The large instance size has the most variation reported:

  • m1.large is ~800 Mbit/s (!!!)
  • t2.large = ~500 MBit/s
  • c3.large = ~500-570 Mbit/s (different results from different sources)
  • c4.large = ~520 MBit/s (I've confirmed this independently, by the way)
  • m3.large is better at ~700 MBit/s
  • m4.large is ~445 Mbit/s
  • r3.large is ~390 Mbit/s

Burstable (T2) instances appear to exhibit burstable networking performance too:

  • The CloudHarmony iperf benchmarks show initial transfers start at 1 GBit/s and then gradually drop to the sustained levels above after a few minutes. PDF links to reports below:

  • t2.small (PDF)

  • t2.medium (PDF)
  • t2.large (PDF)

Note that these are within the same region - if you're transferring across regions, real performance may be much slower. Even for the larger instances, I'm seeing numbers of a few hundred MBit/s.

What is the proper way to test if a parameter is empty in a batch file?

I created this small batch script based on the answers here, as there are many valid ones. Feel free to add to this so long as you follow the same format:

REM Parameter-testing

Setlocal EnableDelayedExpansion EnableExtensions

IF NOT "%~1"=="" (echo Percent Tilde 1 failed with quotes) ELSE (echo SUCCESS)
IF NOT [%~1]==[] (echo Percent Tilde 1 failed with brackets) ELSE (echo SUCCESS)
IF NOT  "%1"=="" (echo Quotes one failed) ELSE (echo SUCCESS)
IF NOT [%1]==[] (echo Brackets one failed) ELSE (echo SUCCESS)
IF NOT "%1."=="." (echo Appended dot quotes one failed) ELSE (echo SUCCESS)
IF NOT [%1.]==[.] (echo Appended dot brackets one failed) ELSE (echo SUCCESS)

pause

download file using an ajax request

You actually don't need ajax at all for this. If you just set "download.php" as the href on the button, or, if it's not a link use:

window.location = 'download.php';

The browser should recognise the binary download and not load the actual page but just serve the file as a download.

How to darken a background using CSS?

It might be possible to do this with box-shadow

however, I can't get it to actually apply to an image. Only on solid color backgrounds

_x000D_
_x000D_
body {_x000D_
  background: #131418;_x000D_
  color: #999;_x000D_
  text-align: center;_x000D_
}_x000D_
.mycooldiv {_x000D_
  width: 400px;_x000D_
  height: 300px;_x000D_
  margin: 2% auto;_x000D_
  border-radius: 100%;_x000D_
}_x000D_
.red {_x000D_
  background: red_x000D_
}_x000D_
.blue {_x000D_
  background: blue_x000D_
}_x000D_
.yellow {_x000D_
  background: yellow_x000D_
}_x000D_
.green {_x000D_
  background: green_x000D_
}_x000D_
#darken {_x000D_
  box-shadow: inset 0px 0px 400px 110px rgba(0, 0, 0, .7);_x000D_
  /*darkness level control - change the alpha value for the color for darken/ligheter effect */_x000D_
}
_x000D_
Red_x000D_
<div class="mycooldiv red"></div>_x000D_
Darkened Red_x000D_
<div class="mycooldiv red" id="darken"></div>_x000D_
Blue_x000D_
<div class="mycooldiv blue"></div>_x000D_
Darkened Blue_x000D_
<div class="mycooldiv blue" id="darken"></div>_x000D_
Yellow_x000D_
<div class="mycooldiv yellow"></div>_x000D_
Darkened Yellow_x000D_
<div class="mycooldiv yellow" id="darken"></div>_x000D_
Green_x000D_
<div class="mycooldiv green"></div>_x000D_
Darkened Green_x000D_
<div class="mycooldiv green" id="darken"></div>
_x000D_
_x000D_
_x000D_

JUnit 4 compare Sets

with hamcrest:

assertThat(s1, is(s2));

with plain assert:

assertEquals(s1, s2);

NB:t the equals() method of the concrete set class is used

Disabling Log4J Output in Java

 log4j.rootLogger=OFF

Add x and y labels to a pandas plot

pandas uses matplotlib for basic dataframe plots. So, if you are using pandas for basic plot you can use matplotlib for plot customization. However, I propose an alternative method here using seaborn which allows more customization of the plot while not going into the basic level of matplotlib.

Working Code:

import pandas as pd
import seaborn as sns
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                   index=['Index 1', 'Index 2'])
ax= sns.lineplot(data=df2, markers= True)
ax.set(xlabel='xlabel', ylabel='ylabel', title='Video streaming dropout by category') 

enter image description here

Display JSON as HTML

If you are deliberately displaying it for the end user, wrap the JSON text in <PRE> and <CODE> tags, e.g.:

<html>
<body>
<pre>
<code>
[
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    },
    {
        color: "blue",
        value: "#00f"
    },
    {
        color: "cyan",
        value: "#0ff"
    },
    {
        color: "magenta",
        value: "#f0f"
    },
    {
        color: "yellow",
        value: "#ff0"
    },
    {
        color: "black",
        value: "#000"
    }
]

</code>
</pre>
</body>
</html>

Otherwise I would use JSON Viewer.

Entity Framework select distinct name

DBContext.TestAddresses.Select(m => m.NAME).Distinct();

if you have multiple column do like this:

DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).Distinct();

In this example no duplicate CategoryId and no CategoryName i hope this will help you

How do I make a Mac Terminal pop-up/alert? Applescript?

This would restore focus to the previous application and exit the script if the answer was empty.

a=$(osascript -e 'try
tell app "SystemUIServer"
set answer to text returned of (display dialog "" default answer "")
end
end
activate app (path to frontmost application as text)
answer' | tr '\r' ' ')
[[ -z "$a" ]] && exit

If you told System Events to display the dialog, there would be a small delay if it wasn't running before.

For documentation about display dialog, open the dictionary of Standard Additions in AppleScript Editor or see the AppleScript Language Guide.

Check the current number of connections to MongoDb

In OS X, too see the connections directly on the network interface, just do:

$ lsof -n -i4TCP:27017

mongod     2191 inanc    7u  IPv4 0xab6d9f844e21142f  0t0  TCP 127.0.0.1:27017 (LISTEN)
mongod     2191 inanc   33u  IPv4 0xab6d9f84604cd757  0t0  TCP 127.0.0.1:27017->127.0.0.1:56078 (ESTABLISHED)
stores.te 18704 inanc    6u  IPv4 0xab6d9f84604d404f  0t0  TCP 127.0.0.1:56078->127.0.0.1:27017 (ESTABLISHED)
  • No need to use grep etc, just use the lsof's arguments.

  • Too see the connections on MongoDb's CLI, see @milan's answer (which I just edited).

Warning - Build path specifies execution environment J2SE-1.4

In Eclipse from your project:

  1. Right-click on your project
  2. Click Properties
  3. Java build path: Libraries; Remove the "JRE System Library[J2SE 1.4]"
  4. Click Add Library -> JRE System Library
  5. Select the new "Execution Environment" or Workspace default JRE

Why am I getting a " Traceback (most recent call last):" error?

I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:

TypeError: 'int' object is not callable

My code for Python 3 is as follows:

# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error

raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: {M_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: {F_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: {G_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: {inches_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    # Printing error in the line below
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

I hope this helps.

When is TCP option SO_LINGER (0) required?

The listen socket on a server can use linger with time 0 to have access to binding back to the socket immediately and to reset any clients whose connections are not yet finished connecting. TIME_WAIT is something that is only interesting when you have a multi-path network and can end up with miss-ordered packets or otherwise are dealing with odd network packet ordering/arrival-timing.

How to use foreach with a hash reference?

So, with Perl 5.20, the new answer is:

foreach my $key (keys $ad_grp_ref->%*) {

(which has the advantage of transparently working with more complicated expressions:

foreach my $key (keys $ad_grp_obj[3]->get_ref()->%*) {

etc.)

See perlref for the full documentation.

Note: in Perl version 5.20 and 5.22, this syntax is considered experimental, so you need

use feature 'postderef';
no warnings 'experimental::postderef';

at the top of any file that uses it. Perl 5.24 and later don't require any pragmas for this feature.

FileSystemWatcher Changed event is raised twice

I wanted to react only on the last event, just in case, also on a linux file change it seemed that the file was empty on the first call and then filled again on the next and did not mind loosing some time just in case the OS decided to do some file/attribute change.

I am using .NET async here to help me do the threading.

    private static int _fileSystemWatcherCounts;
    private async void OnChanged(object sender, FileSystemEventArgs e)
    {
        // Filter several calls in short period of time
        Interlocked.Increment(ref _fileSystemWatcherCounts);
        await Task.Delay(100);
        if (Interlocked.Decrement(ref _fileSystemWatcherCounts) == 0)
            DoYourWork();
    }

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

Python Matplotlib Y-Axis ticks on Right Side of Plot

For right labels use ax.yaxis.set_label_position("right"), i.e.:

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.plot([2,3,4,5])
ax.set_xlabel("$x$ /mm")
ax.set_ylabel("$y$ /mm")
plt.show()

Vue 2 - Mutating props vue-warn

Vue just warns you: you change the prop in the component, but when parent component re-renders, "list" will be overwritten and you lose all your changes. So it is dangerous to do so.

Use computed property instead like this:

Vue.component('task', {
    template: '#task-template',
    props: ['list'],
    computed: {
        listJson: function(){
            return JSON.parse(this.list);
        }
    }
});

Couldn't load memtrack module Logcat Error

do you called the ViewTreeObserver and not remove it.

    mEtEnterlive.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
         // do nothing here can cause such problem
    });

How to copy a file along with directory structure/path using python?

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

What's the difference between JavaScript and Java?

A Re-Introduction to Javascript by the Mozilla team (they make Firefox) should explain it.

Microsoft.Office.Core Reference Missing

I have the same trouble. I went to Add references, COM tab, an select Microsoft Office 15.0 Objetct Library. Ok, and my problem ends.

part of my code is:

EXCEL.Range rango;
            rango = (EXCEL.Range)HojadetrabajoExcel.get_Range("AE13", "AK23");
            rango.Select();
      //      EXCEL.Pictures Lafoto = (EXCEL.Pictures).HojadetrabajoExcel.Pictures(System.Reflection.Missing.Value);
            EXCEL.Pictures Lafoto = HojadetrabajoExcel.Pictures(System.Reflection.Missing.Value);

            HojadetrabajoExcel.Shapes.AddPicture(@"D:\GENETICA HUMANA\Reportes\imagenes\" + Variables.nombreimagen,
                Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue,
                float.Parse(rango.Left.ToString()),float.Parse(rango.Top.ToString()), float.Parse(rango.Width.ToString()),
                float.Parse(rango.Height.ToString()));

Styling HTML email for Gmail

Use inline styles for everything. This site will convert your classes to inline styles: http://premailer.dialect.ca/

Handling the TAB character in Java

You can also use the tab character '\t' to represent a tab, instead of "\t".

char c ='t';
char c =(char)9;

Heroku: How to push different local Git branches to Heroku/master

You should check out heroku_san, it solves this problem quite nicely.

For example, you could:

git checkout BRANCH
rake qa deploy

It also makes it easy to spin up new Heroku instances to deploy a topic branch to new servers:

git checkout BRANCH
# edit config/heroku.yml with new app instance and shortname
rake shortname heroku:create deploy # auto creates deploys and migrates

And of course you can make simpler rake tasks if you do something frequently.

How can the default node version be set using NVM?

You can also like this:

$ nvm alias default lts/fermium

Hash function for a string

-- The way to go these days --

Use SipHash. For your own protection.

-- Old and Dangerous --

unsigned int RSHash(const std::string& str)
{
    unsigned int b    = 378551;
    unsigned int a    = 63689;
    unsigned int hash = 0;

    for(std::size_t i = 0; i < str.length(); i++)
    {
        hash = hash * a + str[i];
        a    = a * b;
    }

    return (hash & 0x7FFFFFFF);
 }

 unsigned int JSHash(const std::string& str)
 {
      unsigned int hash = 1315423911;

      for(std::size_t i = 0; i < str.length(); i++)
      {
          hash ^= ((hash << 5) + str[i] + (hash >> 2));
      }

      return (hash & 0x7FFFFFFF);
 }

Ask google for "general purpose hash function"

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

In my case I was trying to extend "NativeDateAdapter" in order to override "format(date: Date, displayFormat: Object)" method.

In AngularMaterial-2 DatePicker .

So basically I forgot to add @Injectable anotation.

After I add this to my "CustomDateAdapter" class:

@Injectable({
  providedIn: 'root'
})

Error has gone.

How to delete an SVN project from SVN repository

The correct sentence is: svnadmin deltify $PATH. do not forghet to delet the project or repository from the file svn-acl (if you use it). if you simply delete the folder of repository you may corrupt the svn directory depending on how your svn is configured in your environment.

How to convert signed to unsigned integer in python

Since version 3.2 :

def toSigned(n, byte_count): 
  return int.from_bytes(n.to_bytes(byte_count, 'little'), 'little', signed=True)

output :

In [8]: toSigned(5, 1)                                                                                                                                                                                                                                                                                                     
Out[8]: 5

In [9]: toSigned(0xff, 1)                                                                                                                                                                                                                                                                                                  
Out[9]: -1

Differences between key, superkey, minimal superkey, candidate key and primary key

Primary key is a subset of super key. Which is uniquely define and other field are depend on it. In a table their can be just one primary key and rest sub set are candidate key or alternate keys.

Prompt Dialog in Windows Forms

Here's an example in VB.NET

Public Function ShowtheDialog(caption As String, text As String, selStr As String) As String
    Dim prompt As New Form()
    prompt.Width = 280
    prompt.Height = 160
    prompt.Text = caption
    Dim textLabel As New Label() With { _
         .Left = 16, _
         .Top = 20, _
         .Width = 240, _
         .Text = text _
    }
    Dim textBox As New TextBox() With { _
         .Left = 16, _
         .Top = 40, _
         .Width = 240, _
         .TabIndex = 0, _
         .TabStop = True _
    }
    Dim selLabel As New Label() With { _
         .Left = 16, _
         .Top = 66, _
         .Width = 88, _
         .Text = selStr _
    }
    Dim cmbx As New ComboBox() With { _
         .Left = 112, _
         .Top = 64, _
         .Width = 144 _
    }
    cmbx.Items.Add("Dark Grey")
    cmbx.Items.Add("Orange")
    cmbx.Items.Add("None")
    cmbx.SelectedIndex = 0
    Dim confirmation As New Button() With { _
         .Text = "In Ordnung!", _
         .Left = 16, _
         .Width = 80, _
         .Top = 88, _
         .TabIndex = 1, _
         .TabStop = True _
    }
    AddHandler confirmation.Click, Sub(sender, e) prompt.Close()
    prompt.Controls.Add(textLabel)
    prompt.Controls.Add(textBox)
    prompt.Controls.Add(selLabel)
    prompt.Controls.Add(cmbx)
    prompt.Controls.Add(confirmation)
    prompt.AcceptButton = confirmation
    prompt.StartPosition = FormStartPosition.CenterScreen
    prompt.ShowDialog()
    Return String.Format("{0};{1}", textBox.Text, cmbx.SelectedItem.ToString())
End Function

How to determine if Javascript array contains an object with an attribute that equals a given value?

To compare one object to another, I combine a for in loop (used to loop through objects) and some(). You do not have to worry about an array going out of bounds etc, so that saves some code. Documentation on .some can be found here

var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
var  objectsFound = [];

for(let objectNumber in productList){
    var currentId = productList[objectNumber].id;   
    if (theDatabaseList.some(obj => obj.id === currentId)) {
        // Do what you need to do with the matching value here
        objectsFound.push(currentId);
    }
}
console.log(objectsFound);

An alternative way I compare one object to another is to use a nested for loop with Object.keys().length to get the amount of objects in the array. Code below:

var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
var objectsFound = [];

for(var i = 0; i < Object.keys(productList).length; i++){
        for(var j = 0; j < Object.keys(theDatabaseList).length; j++){
        if(productList[i].id === theDatabaseList[j].id){
            objectsFound.push(productList[i].id);
        }       
    }
}
console.log(objectsFound);

To answer your exact question, if are just searching for a value in an object, you can use a single for in loop.

var vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    } 
];

for(var ojectNumbers in vendors){
    if(vendors[ojectNumbers].Name === 'Magenic'){
        console.log('object contains Magenic');
    }
}

Python Socket Multiple Clients

Based on your question:

My question is, using the code below, how would you be able to have multiple clients connected? I've tried lists, but I just can't figure out the format for that. How can this be accomplished where multiple clients are connected at once and I am able to send a message to a specific client?

Using the code you gave, you can do this:

#!/usr/bin/python           # This is server.py file                                                                                                                                                                           

import socket               # Import socket module
import thread

def on_new_client(clientsocket,addr):
    while True:
        msg = clientsocket.recv(1024)
        #do some checks and if msg == someWeirdSignal: break:
        print addr, ' >> ', msg
        msg = raw_input('SERVER >> ')
        #Maybe some code to compute the last digit of PI, play game or anything else can go here and when you are done.
        clientsocket.send(msg)
    clientsocket.close()

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 50000                # Reserve a port for your service.

print 'Server started!'
print 'Waiting for clients...'

s.bind((host, port))        # Bind to the port
s.listen(5)                 # Now wait for client connection.

print 'Got connection from', addr
while True:
   c, addr = s.accept()     # Establish connection with client.
   thread.start_new_thread(on_new_client,(c,addr))
   #Note it's (addr,) not (addr) because second parameter is a tuple
   #Edit: (c,addr)
   #that's how you pass arguments to functions when creating new threads using thread module.
s.close()

As Eli Bendersky mentioned, you can use processes instead of threads, you can also check python threading module or other async sockets framework. Note: checks are left for you to implement how you want and this is just a basic framework.

Including a .js file within a .js file

There is no straight forward way of doing this.

What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).

Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript

My favorite is(not applicable always):

<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");

Google's closure also provides similar functionality.

Axios Delete request with body and headers?

To send an HTTP DELETE with some headers via axios I've done this:

  const deleteUrl = "http//foo.bar.baz";
  const httpReqHeaders = {
    'Authorization': token,
    'Content-Type': 'application/json'
  };
  // check the structure here: https://github.com/axios/axios#request-config
  const axiosConfigObject = {headers: httpReqHeaders}; 

  axios.delete(deleteUrl, axiosConfigObject);

The axios syntax for different HTTP verbs (GET, POST, PUT, DELETE) is tricky because sometimes the 2nd parameter is supposed to be the HTTP body, some other times (when it might not be needed) you just pass the headers as the 2nd parameter.

However let's say you need to send an HTTP POST request without an HTTP body, then you need to pass undefined as the 2nd parameter.

Bare in mind that according to the definition of the configuration object (https://github.com/axios/axios#request-config) you can still pass an HTTP body in the HTTP call via the data field when calling axios.delete, however for the HTTP DELETE verb it will be ignored.

This confusion between the 2nd parameter being sometimes the HTTP body and some other time the whole config object for axios is due to how the HTTP rules have been implemented. Sometimes an HTTP body is not needed for an HTTP call to be considered valid.

DataTable: How to get item value with row name and column name? (VB)

For i = 0 To dt.Rows.Count - 1

    ListV.Items.Add(dt.Rows(i).Item("STU_NUMBER").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("FNAME").ToString & " " & dt.Rows(i).Item("MI").ToString & ". " & dt.Rows(i).Item("LNAME").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("SEX").ToString)

Next

in_array multiple values

if(empty(array_intersect([21,22,23,24], $check_with_this)) {
 print "Not found even a single element";
} else {
 print "Found an element";
}

array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

Returns an array containing all of the values in array1 whose values exist in all of the parameters.


empty() — Determine whether a variable is empty

Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

Laravel where on relationship object

With multiple joins, use something like this code:

$someId = 44;
Event::with(["owner", "participants" => function($q) use($someId){
    $q->where('participants.IdUser', '=', 1);
    //$q->where('some other field', $someId);
}])