Programs & Examples On #Webresponse

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

Send push to Android by C# using FCM (Firebase Cloud Messaging)

You can use this library, makes it seamless to send push notifications using Firebase Service from a C# backend download here

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I experienced this issue when calling my web api endpoint and solved it.

In my case it was an issue in the way the client was encoding the body content. I was not specifying the encoding or media type. Specifying them solved it.

Not specifying encoding type, caused 415 error:

var content = new StringContent(postData);
httpClient.PostAsync(uri, content);

Specifying the encoding and media type, success:

var content = new StringContent(postData, Encoding.UTF8, "application/json");
httpClient.PostAsync(uri, content);

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Code for WebTestPlugIn

public class Protocols : WebTestPlugin
{

    public override void PreRequest(object sender, PreRequestEventArgs e)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    }

}

Calling async method on button click

You're the victim of the classic deadlock. task.Wait() or task.Result is a blocking call in UI thread which causes the deadlock.

Don't block in the UI thread. Never do it. Just await it.

private async void Button_Click(object sender, RoutedEventArgs 
{
      var task = GetResponseAsync<MyObject>("my url");
      var items = await task;
}

Btw, why are you catching the WebException and throwing it back? It would be better if you simply don't catch it. Both are same.

Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse method. StreamReader.ReadToEnd is a blocking call --you should be using StreamReader.ReadToEndAsync.

Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.

Your method should look something like the following when you've addressed all the above concerns.

public static async Task<List<T>> GetResponseAsync<T>(string url)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    string text = await strReader.ReadToEndAsync();

    return JsonConvert.DeserializeObject<List<T>>(text);
}

How to properly make a http web GET request

Another way is using 'HttpClient' like this:

using System;
using System.Net;
using System.Net.Http;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Making API Call...");
            using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
            {
                client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
                HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
                response.EnsureSuccessStatusCode();
                string result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine("Result: " + result);
            }
            Console.ReadLine();
        }
    }
}

Check HttpClient vs HttpWebRequest from stackoverflow and this from other.

Update June 22, 2020: It's not recommended to use httpclient in a 'using' block as it might cause port exhaustion.

private static HttpClient client = null;
    
ContructorMethod()
{
   if(client == null)
   {
        HttpClientHandler handler = new HttpClientHandler()
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        };        
        client = new HttpClient(handler);
   }
   client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
   HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
   response.EnsureSuccessStatusCode();
   string result = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine("Result: " + result);           
 }

If using .Net Core 2.1+, consider using IHttpClientFactory and injecting like this in your startup code.

 var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
            TimeSpan.FromSeconds(60));

 services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        }).AddPolicyHandler(request => timeout);

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

We had this issue whereby a website that was accessing our API was getting the “The underlying connection was closed: An unexpected error occurred on a send.” message.

Their code was a mix of .NET 3.x and 2.2, which as I understand it means they are using TLS 1.0.

The answer below can help you diagnose the issue by enabling TLS 1.0, SSL 2 and SSL3, but to be very clear, you do not want to do that long-term as all three of those protocols are regarded as insecure and should no longer be used:

To get our IIS to respond to their API calls we had to add registry settings on the IIS's server to explicitly enable versions of TLS - NOTE: You have to restart the Windows server (not just the IIS service) after making these changes:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.0\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.0\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.1\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.1\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.2\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.2\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

If that doesn't do it, you could also experiment with adding the entry for SSL 2.0:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

To be clear, this is not a nice solution, and the right solution is to get the caller to use TLS 1.2, but the above can help diagnose that this is the issue.

You can speed adding those reg entries up with this powershell script:

$ProtocolList       = @("SSL 2.0","SSL 3.0","TLS 1.0", "TLS 1.1", "TLS 1.2")
$ProtocolSubKeyList = @("Client", "Server")
$DisabledByDefault = "DisabledByDefault"
$Enabled = "Enabled"
$registryPath = "HKLM:\\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\"

foreach($Protocol in $ProtocolList)
{
    Write-Host " In 1st For loop"
        foreach($key in $ProtocolSubKeyList)
        {         
            $currentRegPath = $registryPath + $Protocol + "\" + $key
            Write-Host " Current Registry Path $currentRegPath"
            if(!(Test-Path $currentRegPath))
            {
                Write-Host "creating the registry"
                    New-Item -Path $currentRegPath -Force | out-Null             
            }
            Write-Host "Adding protocol"
                New-ItemProperty -Path $currentRegPath -Name $DisabledByDefault -Value "0" -PropertyType DWORD -Force | Out-Null
                New-ItemProperty -Path $currentRegPath -Name $Enabled -Value "1" -PropertyType DWORD -Force | Out-Null    
    }
}
 
Exit 0

That's a modified version of the script from the Microsoft help page for Set up TLS for VMM. This basics.net article was the page that originally gave me the idea to look at these settings.

..The underlying connection was closed: An unexpected error occurred on a receive

Setting the HttpWebRequest.KeepAlive to false didn't work for me.

Since I was accessing a HTTPS page I had to set the Service Point Security Protocol to Tls12.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Notice that there are other SecurityProtocolTypes: SecurityProtocolType.Ssl3, SecurityProtocolType.Tls, SecurityProtocolType.Tls11

So if the Tls12 doesn't work for you, try the three remaining options.

Also notice that you can set multiple protocols. This is preferable on most cases.

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

Edit: Since this is a choice of security standards it's obviously best to go with the latest (TLS 1.2 as of writing this), and not just doing what works. In fact, SSL3 has been officially prohibited from use since 2015 and TLS 1.0 and TLS 1.1 will likely be prohibited soon as well. source: @aske-b

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

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

Here's my final working code. My web service needed one file (POST parameter name was "file") & a string value (POST parameter name was "userid").

/// <summary>
/// Occurs when upload backup application bar button is clicked. Author : Farhan Ghumra
 /// </summary>
private async void btnUploadBackup_Click(object sender, EventArgs e)
{
    var dbFile = await ApplicationData.Current.LocalFolder.GetFileAsync(Util.DBNAME);
    var fileBytes = await GetBytesAsync(dbFile);
    var Params = new Dictionary<string, string> { { "userid", "9" } };
    UploadFilesToServer(new Uri(Util.UPLOAD_BACKUP), Params, Path.GetFileName(dbFile.Path), "application/octet-stream", fileBytes);
}

/// <summary>
/// Creates HTTP POST request & uploads database to server. Author : Farhan Ghumra
/// </summary>
private void UploadFilesToServer(Uri uri, Dictionary<string, string> data, string fileName, string fileContentType, byte[] fileData)
{
    string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
    httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    httpWebRequest.Method = "POST";
    httpWebRequest.BeginGetRequestStream((result) =>
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            using (Stream requestStream = request.EndGetRequestStream(result))
            {
                WriteMultipartForm(requestStream, boundary, data, fileName, fileContentType, fileData);
            }
            request.BeginGetResponse(a =>
            {
                try
                {
                    var response = request.EndGetResponse(a);
                    var responseStream = response.GetResponseStream();
                    using (var sr = new StreamReader(responseStream))
                    {
                        using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                        {
                            string responseString = streamReader.ReadToEnd();
                            //responseString is depend upon your web service.
                            if (responseString == "Success")
                            {
                                MessageBox.Show("Backup stored successfully on server.");
                            }
                            else
                            {
                                MessageBox.Show("Error occurred while uploading backup on server.");
                            } 
                        }
                    }
                }
                catch (Exception)
                {

                }
            }, null);
        }
        catch (Exception)
        {

        }
    }, httpWebRequest);
}

/// <summary>
/// Writes multi part HTTP POST request. Author : Farhan Ghumra
/// </summary>
private void WriteMultipartForm(Stream s, string boundary, Dictionary<string, string> data, string fileName, string fileContentType, byte[] fileData)
{
    /// The first boundary
    byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
    /// the last boundary.
    byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
    /// the form data, properly formatted
    string formdataTemplate = "Content-Dis-data; name=\"{0}\"\r\n\r\n{1}";
    /// the form-data file upload, properly formatted
    string fileheaderTemplate = "Content-Dis-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type: {2}\r\n\r\n";

    /// Added to track if we need a CRLF or not.
    bool bNeedsCRLF = false;

    if (data != null)
    {
        foreach (string key in data.Keys)
        {
            /// if we need to drop a CRLF, do that.
            if (bNeedsCRLF)
                WriteToStream(s, "\r\n");

            /// Write the boundary.
            WriteToStream(s, boundarybytes);

            /// Write the key.
            WriteToStream(s, string.Format(formdataTemplate, key, data[key]));
            bNeedsCRLF = true;
        }
    }

    /// If we don't have keys, we don't need a crlf.
    if (bNeedsCRLF)
        WriteToStream(s, "\r\n");

    WriteToStream(s, boundarybytes);
    WriteToStream(s, string.Format(fileheaderTemplate, "file", fileName, fileContentType));
    /// Write the file data to the stream.
    WriteToStream(s, fileData);
    WriteToStream(s, trailer);
}

/// <summary>
/// Writes string to stream. Author : Farhan Ghumra
/// </summary>
private void WriteToStream(Stream s, string txt)
{
    byte[] bytes = Encoding.UTF8.GetBytes(txt);
    s.Write(bytes, 0, bytes.Length);
}

/// <summary>
/// Writes byte array to stream. Author : Farhan Ghumra
/// </summary>
private void WriteToStream(Stream s, byte[] bytes)
{
    s.Write(bytes, 0, bytes.Length);
}

/// <summary>
/// Returns byte array from StorageFile. Author : Farhan Ghumra
/// </summary>
private async Task<byte[]> GetBytesAsync(StorageFile file)
{
    byte[] fileBytes = null;
    using (var stream = await file.OpenReadAsync())
    {
        fileBytes = new byte[stream.Size];
        using (var reader = new DataReader(stream))
        {
            await reader.LoadAsync((uint)stream.Size);
            reader.ReadBytes(fileBytes);
        }
    }

    return fileBytes;
}

I am very much thankful to Darin Rousseau for helping me.

Why I get 411 Length required error?

var requestedURL = "https://accounts.google.com/o/oauth2/token?code=" + code + "&client_id=" + client_id + "&client_secret=" + client_secret + "&redirect_uri=" + redirect_uri + "&grant_type=authorization_code";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(requestedURL);
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.Method = "POST";
//Set content length to 0
authRequest.ContentLength = 0;
WebResponse authResponseTwitter = authRequest.GetResponse();

The ContentLength property contains the value to send as the Content-length HTTP header with the request.

Any value other than -1 in the ContentLength property indicates that the request uploads data and that only methods that upload data are allowed to be set in the Method property.

After the ContentLength property is set to a value, that number of bytes must be written to the request stream that is returned by calling the GetRequestStream method or both the BeginGetRequestStream and the EndGetRequestStream methods.

for more details click here

Calling a rest api with username and password - how to

Here is the solution for Rest API

class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}

HTTP post XML data in C#

In General:

An example of an easy way to post XML data and get the response (as a string) would be the following function:

public string postXMLData(string destinationUrl, string requestXml)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    byte[] bytes;
    bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    request.ContentType = "text/xml; encoding='utf-8'";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();
    HttpWebResponse response;
    response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseStr = new StreamReader(responseStream).ReadToEnd();
        return responseStr;
    }
    return null;
}

In your specific situation:

Instead of:

request.ContentType = "application/x-www-form-urlencoded";

use:

request.ContentType = "text/xml; encoding='utf-8'";

Also, remove:

string postData = "XMLData=" + Sendingxml;

And replace:

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

with:

byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());

How do you send an HTTP Get Web Request in Python?

In Python, you can use urllib2 (http://docs.python.org/2/library/urllib2.html) to do all of that work for you.

Simply enough:

import urllib2
f =  urllib2.urlopen(url)
print f.read() 

Will print the received HTTP response.

To pass GET/POST parameters the urllib.urlencode() function can be used. For more information, you can refer to the Official Urllib2 Tutorial

The remote server returned an error: (403) Forbidden

Its a permissions error. Your VS probably runs using an elevated account or different user account than the user using the installed version.

It may be useful to check your IIS permissions and see what accounts have access to the resource you are accessing. Cross reference that with the account you use and the account the installed versions are using.

Get HTML code from website in C#

I am using AngleSharp and have been very satisfied with it.

Here is a simple example how to fetch a page:

var config = Configuration.Default.WithDefaultLoader();
var document = await BrowsingContext.New(config).OpenAsync("https://www.google.com");

And now you have a web page in document variable. Then you can easily access it by LINQ or other methods. For example if you want to get a string value from a HTML table:

var someStringValue = document.All.Where(m =>
        m.LocalName == "td" &&
        m.HasAttribute("class") &&
        m.GetAttribute("class").Contains("pid-1-bid")
    ).ElementAt(0).TextContent.ToString();

To use CSS selectors please see AngleSharp examples.

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

If its working when you are using a browser and then passing on your username and password for the first time - then this means that once authentication is done Request header of your browser is set with required authentication values, which is then passed on each time a request is made to hosting server.

So start with inspecting Request Header (this could be done using Web Developers tools), Once you established whats required in header then you could pass this within your HttpWebRequest Header.

Example with Digest Authentication:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

namespace NUI
{
    public class DigestAuthFixer
    {
        private static string _host;
        private static string _user;
        private static string _password;
        private static string _realm;
        private static string _nonce;
        private static string _qop;
        private static string _cnonce;
        private static DateTime _cnonceDate;
        private static int _nc;

public DigestAuthFixer(string host, string user, string password)
{
    // TODO: Complete member initialization
    _host = host;
    _user = user;
    _password = password;
}

private string CalculateMd5Hash(
    string input)
{
    var inputBytes = Encoding.ASCII.GetBytes(input);
    var hash = MD5.Create().ComputeHash(inputBytes);
    var sb = new StringBuilder();
    foreach (var b in hash)
        sb.Append(b.ToString("x2"));
    return sb.ToString();
}

private string GrabHeaderVar(
    string varName,
    string header)
{
    var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
    var matchHeader = regHeader.Match(header);
    if (matchHeader.Success)
        return matchHeader.Groups[1].Value;
    throw new ApplicationException(string.Format("Header {0} not found", varName));
}

private string GetDigestHeader(
    string dir)
{
    _nc = _nc + 1;

    var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
    var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
    var digestResponse =
        CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));

    return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
        "algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
        _user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
}

public string GrabResponse(
    string dir)
{
    var url = _host + dir;
    var uri = new Uri(url);

    var request = (HttpWebRequest)WebRequest.Create(uri);

    // If we've got a recent Auth header, re-use it!
    if (!string.IsNullOrEmpty(_cnonce) &&
        DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
    {
        request.Headers.Add("Authorization", GetDigestHeader(dir));
    }

    HttpWebResponse response;
    try
    {
        response = (HttpWebResponse)request.GetResponse();
    }
    catch (WebException ex)
    {
        // Try to fix a 401 exception by adding a Authorization header
        if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
            throw;

        var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
        _realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
        _nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
        _qop = GrabHeaderVar("qop", wwwAuthenticateHeader);

        _nc = 0;
        _cnonce = new Random().Next(123400, 9999999).ToString();
        _cnonceDate = DateTime.Now;

        var request2 = (HttpWebRequest)WebRequest.Create(uri);
        request2.Headers.Add("Authorization", GetDigestHeader(dir));
        response = (HttpWebResponse)request2.GetResponse();
    }
    var reader = new StreamReader(response.GetResponseStream());
    return reader.ReadToEnd();
}

}

Then you could call it:

DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);

if Url is: http://xyz.rss.com/folder/rss then domain: http://xyz.rss.com (domain part) dir: /folder/rss (rest of the url)

you could also return it as stream and use XmlDocument Load() method.

Parsing a JSON array using Json.Net

You can get at the data values like this:

string json = @"
[ 
    { ""General"" : ""At this time we do not have any frequent support requests."" },
    { ""Support"" : ""For support inquires, please see our support page."" }
]";

JArray a = JArray.Parse(json);

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        Console.WriteLine(name + " -- " + value);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

Just in case...
If you are using SoapUI Mock Service (as the Server), calling it from a C# WCF:

WCF --> SoapUI MockService

And in this case you are getting the same error:

The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8).

Edit your Mock Response at SoapUI and add a Header to it: enter image description here

In my scenario, this fix the problem.

HttpWebRequest-The remote server returned an error: (400) Bad Request

What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.

POST string to ASP.NET Web Api application - returns null

I use this code to post HttpRequests.

/// <summary>
        /// Post this message.
        /// </summary>
        /// <param name="url">URL of the document.</param>
        /// <param name="bytes">The bytes.</param>
        public T Post<T>(string url, byte[] bytes)
    {
        T item;
        var request = WritePost(url, bytes);

        using (var response = request.GetResponse() as HttpWebResponse)
        {
            item = DeserializeResponse<T>(response);
            response.Close();
        }

        return item;
    }

    /// <summary>
    /// Writes the post.
    /// </summary>
    /// <param name="url">The URL.</param>
    /// <param name="bytes">The bytes.</param>
    /// <returns></returns>
    private static HttpWebRequest WritePost(string url, byte[] bytes)
    {
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
        Stream stream = null;
        try
        {
            request.Headers.Clear();
            request.PreAuthenticate = true;
            request.Connection = null;
            request.Expect = null;
            request.KeepAlive = false;
            request.ContentLength = bytes.Length;
            request.Timeout = -1;
            request.Method = "POST";
            stream = request.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);
        }
        catch (Exception e)
        {
            GetErrorResponse(url, e);
        }
        finally
        {
            if (stream != null)
            {
                stream.Flush();
                stream.Close();
            }
        }
        return request;
    }

In regards to your code, try it without the content.Type (request.ContentType = "application/x-www-form-urlencoded";)

update

I believe the problem lies with how you are trying to retrieve the value. When you do a POST and send bytes via the Stream, they will not be passed into the action as a parameter. You'll need to retrieve the bytes via the stream on the server.

On the server, try getting the bytes from stream. The following code is what I use.

     /// <summary> Gets the body. </summary>
     /// <returns> The body. </returns>
     protected byte[] GetBytes()
     {
       byte[] bytes;
        using (var binaryReader = new BinaryReader(Request.InputStream))
        {
            bytes = binaryReader.ReadBytes(Request.ContentLength);
        }

         return bytes;
     }

Powershell v3 Invoke-WebRequest HTTPS error

If you run this as administrator, that error should go away

The request was aborted: Could not create SSL/TLS secure channel

The root of this exception in my case was that at some point in code the following was being called:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

This is really bad. Not only is it instructing .NET to use an insecure protocol, but this impacts every new WebClient (and similar) request made afterward within your appdomain. (Note that incoming web requests are unaffected in your ASP.NET app, but new WebClient requests, such as to talk to an external web service, are).

In my case, it was not actually needed, so I could just delete the statement and all my other web requests started working fine again. Based on my reading elsewhere, I learned a few things:

  • This is a global setting in your appdomain, and if you have concurrent activity, you can't reliably set it to one value, do your action, and then set it back. Another action may take place during that small window and be impacted.
  • The correct setting is to leave it default. This allows .NET to continue to use whatever is the most secure default value as time goes on and you upgrade frameworks. Setting it to TLS12 (which is the most secure as of this writing) will work now but in 5 years may start causing mysterious problems.
  • If you really need to set a value, you should consider doing it in a separate specialized application or appdomain and find a way to talk between it and your main pool. Because it's a single global value, trying to manage it within a busy app pool will only lead to trouble. This answer: https://stackoverflow.com/a/26754917/7656 provides a possible solution by way of a custom proxy. (Note I have not personally implemented it.)

HttpClient does not exist in .net 4.0: what can I do?

read this...

Portable HttpClient for .NET Framework and Windows Phone

see paragraph Using HttpClient on .NET Framework 4.0 or Windows Phone 7.5 http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx

Error :The remote server returned an error: (401) Unauthorized

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;

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

For my case, I had an Angular SLA project template with ASP.NET Core.

I was trying to run the IIS Express from the Visual Studio WebUI solution, triggering the "Actively refused it" error.

enter image description here


The problem, in this case, wasn't connected with the Firewall blocking the connection.

It turned out that I had to run the Angular server independently of the Kestrel run because the Server was expecting the UI to run on a specific port but wasn't actually.


For more information, check the official Microsoft documentation.

How do I make calls to a REST API using C#?

Unrelated, I'm sure, but do wrap your IDisposable objects in using blocks to ensure proper disposal:

using System;
using System.Net;
using System.IO;

namespace ConsoleProgram
{
    public class Class1
    {
        private const string URL = "https://sub.domain.com/objects.json?api_key=123";
        private const string DATA = @"{""object"":{""name"":""Name""}}";

        static void Main(string[] args)
        {
            Class1.CreateObject();
        }

        private static void CreateObject()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = DATA.Length;
            using (Stream webStream = request.GetRequestStream())
            using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
            {
                requestWriter.Write(DATA);
            }

            try
            {
                WebResponse webResponse = request.GetResponse();
                using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
                using (StreamReader responseReader = new StreamReader(webStream))
                {
                    string response = responseReader.ReadToEnd();
                    Console.Out.WriteLine(response);
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }
        }
    }
}

System.Net.Http: missing from namespace? (using .net 4.5)

NuGet > Microsoft.AspNet.WebApi.Client package

How to post JSON to a server using C#?

Some different and clean way to achieve this is by using HttpClient like this:

public async Task<HttpResponseMessage> PostResult(string url, ResultObject resultObject)
{
    using (var client = new HttpClient())
    {
        HttpResponseMessage response = new HttpResponseMessage();
        try
        {
            response = await client.PostAsJsonAsync(url, resultObject);
        }
        catch (Exception ex)
        {
            throw ex
        }
        return response;
     }
}

How to convert WebResponse.GetResponseStream return into a string?

You can use StreamReader.ReadToEnd(),

using (Stream stream = response.GetResponseStream())
{
   StreamReader reader = new StreamReader(stream, Encoding.UTF8);
   String responseString = reader.ReadToEnd();
}

How to get error information when HttpWebRequest.GetResponse() fails

Is this possible using HttpWebRequest and HttpWebResponse?

You could have your web server simply catch and write the exception text into the body of the response, then set status code to 500. Now the client would throw an exception when it encounters a 500 error but you could read the response stream and fetch the message of the exception.

So you could catch a WebException which is what will be thrown if a non 200 status code is returned from the server and read its body:

catch (WebException ex)
{
    using (var stream = ex.Response.GetResponseStream())
    using (var reader = new StreamReader(stream))
    {
        Console.WriteLine(reader.ReadToEnd());
    }
}
catch (Exception ex)
{
    // Something more serious happened
    // like for example you don't have network access
    // we cannot talk about a server exception here as
    // the server probably was never reached
}

reading HttpwebResponse json response, C#

First you need an object

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}
  ...
}

Then in here

    using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

        using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
        }

    }

I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.

JavaScriptSerializer System.Web.Script.Serialization

converting a base 64 string to an image and saving it

Here is working code for converting an image from a base64 string to an Image object and storing it in a folder with unique file name:

public void SaveImage()
{
    string strm = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; 

    //this is a simple white background image
    var myfilename= string.Format(@"{0}", Guid.NewGuid());

    //Generate unique filename
    string filepath= "~/UserImages/" + myfilename+ ".jpeg";
    var bytess = Convert.FromBase64String(strm);
    using (var imageFile = new FileStream(filepath, FileMode.Create))
    {
        imageFile.Write(bytess, 0, bytess.Length);
        imageFile.Flush();
    }
}

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

HttpWebRequest using Basic authentication

Following code will solve json response if there Basic Authentication and Proxy implemented.Also IIS 7.5 Hosting Problm will resolve.

public string HttpGetByWebRequ(string uri, string username, string password)
{
//For Basic Authentication
    string authInfo = username + ":" + password;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));

//For Proxy
    WebProxy proxy = new WebProxy("http://10.127.0.1:8080", true);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "GET";
    request.Accept = "application/json; charset=utf-8";
    request.Proxy = proxy;

    request.Headers["Authorization"] = "Basic " + authInfo;

    var response = (HttpWebResponse)request.GetResponse();

    string strResponse = "";
    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        strResponse= sr.ReadToEnd();

    }

    return strResponse;
}

Setting a WebRequest's body data

Update

See my other SO answer.


Original

var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");

string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding

request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;

var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();

500 internal server error at GetResponse()

In my case my request object inherited from base object. Without knowingly I added a property with int? in my request object and my base object also has same property ( same name ) with int datatype. I noticed this and deleted the property which I added in request object and after that it worked fine.

Download image from the site in .NET/C#

I have used Fredrik's code above in a project with some slight modifications, thought I'd share:

private static bool DownloadRemoteImageFile(string uri, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response;
    try
    {
        response = (HttpWebResponse)request.GetResponse();
    }
    catch (Exception)
    {
        return false;
    }

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK ||
        response.StatusCode == HttpStatusCode.Moved ||
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
    {

        // if the remote file was found, download it
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
        return true;
    }
    else
        return false;
}

Main changes are:

  • using a try/catch for the GetResponse() as I was running into an exception when the remote file returned 404
  • returning a boolean

How to get status code from webclient?

Tried it out. ResponseHeaders do not include status code.

If I'm not mistaken, WebClient is capable of abstracting away multiple distinct requests in a single method call (e.g. correctly handling 100 Continue responses, redirects, and the like). I suspect that without using HttpWebRequest and HttpWebResponse, a distinct status code may not be available.

It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.

The status code unfortunately isn't present in the ResponseHeaders dictionary.

How to add parameters into a WebRequest?

Hope this works

webRequest.Credentials= new NetworkCredential("API_User","API_Password");

Read text from response

The accepted answer does not correctly dispose the WebResponse or decode the text. Also, there's a new way to do this in .NET 4.5.

To perform an HTTP GET and read the response text, do the following.

.NET 1.1 - 4.0

public static string GetResponseText(string address)
{
    var request = (HttpWebRequest)WebRequest.Create(address);

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        var encoding = Encoding.GetEncoding(response.CharacterSet);

        using (var responseStream = response.GetResponseStream())
        using (var reader = new StreamReader(responseStream, encoding))
            return reader.ReadToEnd();
    }
}

.NET 4.5

private static readonly HttpClient httpClient = new HttpClient();

public static async Task<string> GetResponseText(string address)
{
    return await httpClient.GetStringAsync(address);
}

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

One more possibility --

Make sure you're trying to open the same IP address as where you're listening. My server app was listening to the host machine's IP address using IPv6, but the client was attempting to connect on the host machine's IPv4 address.

FtpWebRequest Download File

I know this is an old Post but I am adding here for future reference. Here is a solution that I found:

    private void DownloadFileFTP()
    {
        string inputfilepath = @"C:\Temp\FileName.exe";
        string ftphost = "xxx.xx.x.xxx";
        string ftpfilepath = "/Updater/Dir1/FileName.exe";

        string ftpfullpath = "ftp://" + ftphost + ftpfilepath;

        using (WebClient request = new WebClient())
        {
            request.Credentials = new NetworkCredential("UserName", "P@55w0rd");
            byte[] fileData = request.DownloadData(ftpfullpath);

            using (FileStream file = File.Create(inputfilepath))
            {
                file.Write(fileData, 0, fileData.Length);
                file.Close();
            }
            MessageBox.Show("Download Complete");
        }
    }

Updated based upon excellent suggestion by Ilya Kogan

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

It is not an issue it is because of caching...

To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').

After timestamp it should be axios.get(/api/products?${Date.now()}.

It will resolve your 304 status code.

The server committed a protocol violation. Section=ResponseStatusLine ERROR

Sometimes this error occurs when UserAgent request parameter is empty (in github.com api in my case).

Setting this parameter to custom not empty string solved my problem.

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

Using CookieContainer with WebClient class

 WebClient wb = new WebClient();
 wb.Headers.Add(HttpRequestHeader.Cookie, "somecookie");

From Comments

How do you format the name and value of the cookie in place of "somecookie" ?

wb.Headers.Add(HttpRequestHeader.Cookie, "cookiename=cookievalue"); 

For multiple cookies:

wb.Headers.Add(HttpRequestHeader.Cookie, 
              "cookiename1=cookievalue1;" +
              "cookiename2=cookievalue2");

Adjusting HttpWebRequest Connection Timeout in C#

No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.

To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active

public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
    try
    {
        //check the domain first
        if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
        {
            //only now check the url itself
            var request = System.Net.WebRequest.Create(aUrl);
            request.Method = "HEAD";
            request.Timeout = aTimeoutSeconds * 1000;
            var response = (HttpWebResponse)request.GetResponse();
            return response.StatusCode == HttpStatusCode.OK;
        }
    }
    catch
    {
    }
    return false;

}

private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
    try
    {
        using (TcpClient client = new TcpClient())
        {
            var result = client.BeginConnect(aDomain, 80, null, null);

            var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));

            if (!success)
            {
                return false;
            }

            // we have connected
            client.EndConnect(result);
            return true;
        }
    }
    catch
    {
    }
    return false;
}

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:

try
{
    wResp = (HttpWebResponse)wReq.GetResponse();
    wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
    wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}

System.Net.WebException: The operation has timed out

I'm not sure about your first code sample where you use WebClient.UploadValues, it's not really enough to go on, could you paste more of your surrounding code? Regarding your WebRequest code, there are two things at play here:

  1. You're only requesting the headers of the response**, you never read the body of the response by opening and reading (to its end) the ResponseStream. Because of this, the WebRequest client helpfully leaves the connection open, expecting you to request the body at any moment. Until you either read the response body to completion (which will automatically close the stream for you), clean up and close the stream (or the WebRequest instance) or wait for the GC to do its thing, your connection will remain open.

  2. You have a default maximum amount of active connections to the same host of 2. This means you use up your first two connections and then never dispose of them so your client isn't given the chance to complete the next request before it reaches its timeout (which is milliseconds, btw, so you've set it to 0.2 seconds - the default should be fine).

If you don't want the body of the response (or you've just uploaded or POSTed something and aren't expecting a response), simply close the stream, or the client, which will close the stream for you.

The easiest way to fix this is to make sure you use using blocks on disposable objects:

for (int i = 0; i < ops1; i++)
{
    Uri myUri = new Uri(site);
    WebRequest myWebRequest = WebRequest.Create(myUri);
    //myWebRequest.Timeout = 200;
    using (WebResponse myWebResponse = myWebRequest.GetResponse())
    {
        // Do what you want with myWebResponse.Headers.
    } // Your response will be disposed of here
}

Another solution is to allow 200 concurrent connections to the same host. However, unless you're planning to multi-thread this operation so you'd need multiple, concurrent connections, this won't really help you:

 ServicePointManager.DefaultConnectionLimit = 200;

When you're getting timeouts within code, the best thing to do is try to recreate that timeout outside of your code. If you can't, the problem probably lies with your code. I usually use cURL for that, or just a web browser if it's a simple GET request.

** In reality, you're actually requesting the first chunk of data from the response, which contains the HTTP headers, and also the start of the body. This is why it's possible to read HTTP header info (such as Content-Encoding, Set-Cookie etc) before reading from the output stream. As you read the stream, further data is retrieved from the server. WebRequest's connection to the server is kept open until you reach the end of this stream (effectively closing it as it's not seekable), manually close it yourself or it is disposed of. There's more about this here.

Send a file via HTTP POST with C#

Using .NET 4.5 trying to perform form POST file upload. Tried most of the methods above but to no avail. Found the solution here https://www.c-sharpcorner.com/article/upload-any-file-using-http-post-multipart-form-data

But I am not not keen as I do not understand why we still need to deal with such low level programming in these common usages (should be handled nicely by framework)

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

Try providing username and password in your client like below

client.ClientCredentials.UserName.UserName = @"Domain\username"; client.ClientCredentials.UserName.Password = "password";

Call a url from javascript

var req ;

// Browser compatibility check          
if (window.XMLHttpRequest) {
   req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {

 try {
   req = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {

   try {
     req = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e) {}
 }

}


var req = new XMLHttpRequest();
req.open("GET", "test.html",true);
req.onreadystatechange = function () {
    //document.getElementById('divTxt').innerHTML = "Contents : " + req.responseText;
}

req.send(null);

HTTP POST Returns Error: 417 "Expectation Failed."

The web.config approach works for InfoPath form services calls to IntApp web service enabled rules.

  <system.net>
    <defaultProxy />
    <settings> <!-- 20130323 bchauvin -->
        <servicePointManager expect100Continue="false" />
    </settings>
  </system.net>

How do I use WebRequest to access an SSL encrypted site using https?

This one worked for me:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Do I need <class> elements in persistence.xml?

Do I need Class elements in persistence.xml?

No, you don't necessarily. Here is how you do it in Eclipse (Kepler tested):

Right click on the project, click Properties, select JPA, in the Persistence class management tick Discover annotated classes automatically.

enter image description here

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

To refine the answer from Zed, and to answer your comment:

INSERT INTO dues_storage
SELECT d.*, CURRENT_DATE()
FROM dues d
WHERE id = 5;

See T.J. Crowder's comment

How to minify php page html output?

you can check out this set of classes: https://code.google.com/p/minify/source/browse/?name=master#git%2Fmin%2Flib%2FMinify , you'll find html/css/js minification classes there.

you can also try this: http://code.google.com/p/htmlcompressor/

Good luck :)

Replace string within file contents

Something like

file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')

<do stuff with the result>

How to convert a String to a Date using SimpleDateFormat?

Very Simple Example is.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
                Date date = new Date();
                Date date1 = new Date();
            try {
                System.out.println("Date1:   "+date1);
                System.out.println("date" + date);

                date = simpleDateFormat.parse("01-01-2013");
                date1 = simpleDateFormat.parse("06-15-2013");

                System.out.println("Date1 is:"+date1);
                System.out.println("date" + date);

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

VBA check if file exists

something like this

best to use a workbook variable to provide further control (if needed) of the opened workbook

updated to test that file name was an actual workbook - which also makes the initial check redundant, other than to message the user than the Textbox is blank

Dim strFile As String
Dim WB As Workbook
strFile = Trim(TextBox1.Value)
Dim DirFile As String
If Len(strFile) = 0 Then Exit Sub

DirFile = "C:\Documents and Settings\Administrator\Desktop\" & strFile
If Len(Dir(DirFile)) = 0 Then
  MsgBox "File does not exist"
Else
 On Error Resume Next
 Set WB = Workbooks.Open(DirFile)
 On Error GoTo 0
 If WB Is Nothing Then MsgBox DirFile & " is invalid", vbCritical
End If

jQuery selectors on custom data attributes using HTML5

jsFiddle Demo

jQuery provides several selectors (full list) in order to make the queries you are looking for work. To address your question "In other cases is it possible to use other selectors like "contains, less than, greater than, etc..."." you can also use contains, starts with, and ends with to look at these html5 data attributes. See the full list above in order to see all of your options.

The basic querying has been covered above, and using John Hartsock's answer is going to be the best bet to either get every data-company element, or to get every one except Microsoft (or any other version of :not).

In order to expand this to the other points you are looking for, we can use several meta selectors. First, if you are going to do multiple queries, it is nice to cache the parent selection.

var group = $('ul[data-group="Companies"]');

Next, we can look for companies in this set who start with G

var google = $('[data-company^="G"]',group);//google

Or perhaps companies which contain the word soft

var microsoft = $('[data-company*="soft"]',group);//microsoft

It is also possible to get elements whose data attribute's ending matches

var facebook = $('[data-company$="book"]',group);//facebook

_x000D_
_x000D_
//stored selector_x000D_
var group = $('ul[data-group="Companies"]');_x000D_
_x000D_
//data-company starts with G_x000D_
var google = $('[data-company^="G"]',group).css('color','green');_x000D_
_x000D_
//data-company contains soft_x000D_
var microsoft = $('[data-company*="soft"]',group).css('color','blue');_x000D_
_x000D_
//data-company ends with book_x000D_
var facebook = $('[data-company$="book"]',group).css('color','pink');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul data-group="Companies">_x000D_
  <li data-company="Microsoft">Microsoft</li>_x000D_
  <li data-company="Google">Google</li>_x000D_
  <li data-company ="Facebook">Facebook</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Wait until all promises complete even if some rejected

I know that this question has a lot of answers, and I'm sure must (if not all) are correct. However it was very hard for me to understand the logic/flow of these answers.

So I looked at the Original Implementation on Promise.all(), and I tried to imitate that logic - with the exception of not stopping the execution if one Promise failed.

  public promiseExecuteAll(promisesList: Promise<any>[] = []): Promise<{ data: any, isSuccess: boolean }[]>
  {
    let promise: Promise<{ data: any, isSuccess: boolean }[]>;

    if (promisesList.length)
    {
      const result: { data: any, isSuccess: boolean }[] = [];
      let count: number = 0;

      promise = new Promise<{ data: any, isSuccess: boolean }[]>((resolve, reject) =>
      {
        promisesList.forEach((currentPromise: Promise<any>, index: number) =>
        {
          currentPromise.then(
            (data) => // Success
            {
              result[index] = { data, isSuccess: true };
              if (promisesList.length <= ++count) { resolve(result); }
            },
            (data) => // Error
            {
              result[index] = { data, isSuccess: false };
              if (promisesList.length <= ++count) { resolve(result); }
            });
        });
      });
    }
    else
    {
      promise = Promise.resolve([]);
    }

    return promise;
  }

Explanation:
- Loop over the input promisesList and execute each Promise.
- No matter if the Promise resolved or rejected: save the Promise's result in a result array according to the index. Save also the resolve/reject status (isSuccess).
- Once all Promises completed, return one Promise with the result of all others.

Example of use:

const p1 = Promise.resolve("OK");
const p2 = Promise.reject(new Error(":-("));
const p3 = Promise.resolve(1000);

promiseExecuteAll([p1, p2, p3]).then((data) => {
  data.forEach(value => console.log(`${ value.isSuccess ? 'Resolve' : 'Reject' } >> ${ value.data }`));
});

/* Output: 
Resolve >> OK
Reject >> :-(
Resolve >> 1000
*/

Block direct access to a file over http but allow php script access

How about custom module based .htaccess script (like its used in CodeIgniter)? I tried and it worked good in CodeIgniter apps. Any ideas to use it on other apps?

<IfModule authz_core_module>
    Require all denied
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>

How Can I Remove “public/index.php” in the URL Generated Laravel?

Rename the server.php in the your Laravel root folder to index.php and copy the .htaccess file from /public directory to your Laravel root folder.

Link to all Visual Studio $ variables

Ok, I finally wanted to have a pretty complete, searchable list of those variables for reference. Here is a complete (OCR-generated, as I did not easily find something akin to a printenv command) list of defined variables for a Visual C++ project on my machine. Probably not all macros are defined for others (e.g. OCTAVE_EXECUTABLE), but I wanted to err on the side of inclusiveness here.

For example, this is the first time that I see $(Language) (expanding to C++ for this project) being mentioned outside of the IDE.

$(AllowLocalNetworkLoopback)
$(ALLUSERSPROFILE)
$(AndroidTargetsPath)
$(APPDATA)
$(AppxManifestMetadataClHostArchDir)
$(AppxManifestMetadataCITargetArchDir)
$(Attach)
$(BaseIntermediateOutputPath)
$(BuildingInsideVisualStudio)
$(CharacterSet)
$(CLRSupport)
$(CommonProgramFiles)
$(CommonProgramW6432)
$(COMPUTERNAME)
$(ComSpec)
$(Configuration)
$(ConfigurationType)
$(CppWinRT_IncludePath)
$(CrtSDKReferencelnclude)
$(CrtSDKReferenceVersion)
$(CustomAfterMicrosoftCommonProps)
$(CustomBeforeMicrosoftCommonProps)
$(DebugCppRuntimeFilesPath)
$(DebuggerFlavor)
$(DebuggerLaunchApplication)
$(DebuggerRequireAuthentication)
$(DebuggerType)
$(DefaultLanguageSourceExtension)
$(DefaultPlatformToolset)
$(DefaultWindowsSDKVersion)
$(DefineExplicitDefaults)
$(DelayImplib)
$(DesignTimeBuild)
$(DevEnvDir)
$(DocumentLibraryDependencies)
$(DotNetSdk_IncludePath)
$(DotNetSdk_LibraryPath)
$(DotNetSdk_LibraryPath_arm)
$(DotNetSdk_LibraryPath_arm64)
$(DotNetSdk_LibraryPath_x64)
$(DotNetSdk_LibraryPath_x86)
$(DotNetSdkRoot)
$(DriverData)
$(EmbedManifest)
$(EnableManagedIncrementalBuild)
$(EspXtensions)
$(ExcludePath)
$(ExecutablePath)
$(ExtensionsToDeleteOnClean)
$(FPS_BROWSER_APP_PROFILE_STRING)
$(FPS_BROWSER_USER_PROFILE_STRING)
$(FrameworkDir)
$(FrameworkDir_110)
$(FrameworkSdkDir)
$(FrameworkSDKRoot)
$(FrameworkVersion)
$(GenerateManifest)
$(GPURefDebuggerBreakOnAllThreads)
$(HOMEDRIVE)
$(HOMEPATH)
$(IgnorelmportLibrary)
$(ImportByWildcardAfterMicrosoftCommonProps)
$(ImportByWildcardBeforeMicrosoftCommonProps)
$(ImportDirectoryBuildProps)
$(ImportProjectExtensionProps)
$(ImportUserLocationsByWildcardAfterMicrosoftCommonProps)
$(ImportUserLocationsByWildcardBeforeMicrosoftCommonProps)
$(IncludePath)
$(IncludeVersionInInteropName)
$(IntDir)
$(InteropOutputPath)
$(iOSTargetsPath)
$(Keyword)
$(KIT_SHARED_IncludePath)
$(LangID)
$(LangName)
$(Language)
$(LIBJABRA_TRACE_LEVEL)
$(LibraryPath)
$(LibraryWPath)
$(LinkCompiled)
$(LinkIncremental)
$(LOCALAPPDATA)
$(LocalDebuggerAttach)
$(LocalDebuggerDebuggerlType)
$(LocalDebuggerMergeEnvironment)
$(LocalDebuggerSQLDebugging)
$(LocalDebuggerWorkingDirectory)
$(LocalGPUDebuggerTargetType)
$(LOGONSERVER)
$(MicrosoftCommonPropsHasBeenImported)
$(MpiDebuggerCleanupDeployment)
$(MpiDebuggerDebuggerType)
$(MpiDebuggerDeployCommonRuntime)
$(MpiDebuggerNetworkSecurityMode)
$(MpiDebuggerSchedulerNode)
$(MpiDebuggerSchedulerTimeout)
$(MSBuild_ExecutablePath)
$(MSBuildAllProjects)
$(MSBuildAssemblyVersion)
$(MSBuildBinPath)
$(MSBuildExtensionsPath)
$(MSBuildExtensionsPath32)
$(MSBuildExtensionsPath64)
$(MSBuildFrameworkToolsPath)
$(MSBuildFrameworkToolsPath32)
$(MSBuildFrameworkToolsPath64)
$(MSBuildFrameworkToolsRoot)
$(MSBuildLoadMicrosoftTargetsReadOnly)
$(MSBuildNodeCount)
$(MSBuildProgramFiles32)
$(MSBuildProjectDefaultTargets)
$(MSBuildProjectDirectory)
$(MSBuildProjectDirectoryNoRoot)
$(MSBuildProjectExtension)
$(MSBuildProjectExtensionsPath)
$(MSBuildProjectFile)
$(MSBuildProjectFullPath)
$(MSBuildProjectName)
$(MSBuildRuntimeType)
$(MSBuildRuntimeVersion)
$(MSBuildSDKsPath)
$(MSBuildStartupDirectory)
$(MSBuildToolsPath)
$(MSBuildToolsPath32)
$(MSBuildToolsPath64)
$(MSBuildToolsRoot)
$(MSBuildToolsVersion)
$(MSBuildUserExtensionsPath)
$(MSBuildVersion)
$(MultiToolTask)
$(NETFXKitsDir)
$(NETFXSDKDir)
$(NuGetProps)
$(NUMBER_OF_PROCESSORS)
$(OCTAVE_EXECUTABLE)
$(OneDrive)
$(OneDriveCommercial)
$(OS)
$(OutDir)
$(OutDirWasSpecified)
$(OutputType)
$(Path)
$(PATHEXT)
$(PkgDefApplicationConfigFile)
$(Platform)
$(Platform_Actual)
$(PlatformArchitecture)
$(PlatformName)
$(PlatformPropsFound)
$(PlatformShortName)
$(PlatformTarget)
$(PlatformTargetsFound)
$(PlatformToolset)
$(PlatformToolsetVersion)
$(PostBuildEventUseInBuild)
$(PreBuildEventUseInBuild)
$(PreferredToolArchitecture)
$(PreLinkEventUselnBuild)
$(PROCESSOR_ARCHITECTURE)
$(PROCESSOR_ARCHITEW6432)
$(PROCESSOR_IDENTIFIER)
$(PROCESSOR_LEVEL)
$(PROCESSOR_REVISION)
$(ProgramData)
$(ProgramFiles)
$(ProgramW6432)
$(ProjectDir)
$(ProjectExt)
$(ProjectFileName)
$(ProjectGuid)
$(ProjectName)
$(ProjectPath)
$(PSExecutionPolicyPreference)
$(PSModulePath)
$(PUBLIC)
$(ReferencePath)
$(RemoteDebuggerAttach)
$(RemoteDebuggerConnection)
$(RemoteDebuggerDebuggerlype)
$(RemoteDebuggerDeployDebugCppRuntime)
$(RemoteDebuggerServerName)
$(RemoteDebuggerSQLDebugging)
$(RemoteDebuggerWorkingDirectory)
$(RemoteGPUDebuggerTargetType)
$(RetargetAlwaysSupported)
$(RootNamespace)
$(RoslynTargetsPath)
$(SDK35ToolsPath)
$(SDK40ToolsPath)
$(SDKDisplayName)
$(SDKIdentifier)
$(SDKVersion)
$(SESSIONNAME)
$(SolutionDir)
$(SolutionExt)
$(SolutionFileName)
$(SolutionName)
$(SolutionPath)
$(SourcePath)
$(SpectreMitigation)
$(SQLDebugging)
$(SystemDrive)
$(SystemRoot)
$(TargetExt)
$(TargetFrameworkVersion)
$(TargetName)
$(TargetPlatformMinVersion)
$(TargetPlatformVersion)
$(TargetPlatformWinMDLocation)
$(TargetUniversalCRTVersion)
$(TEMP)
$(TMP)
$(ToolsetPropsFound)
$(ToolsetTargetsFound)
$(UCRTContentRoot)
$(UM_IncludePath)
$(UniversalCRT_IncludePath)
$(UniversalCRT_LibraryPath_arm)
$(UniversalCRT_LibraryPath_arm64)
$(UniversalCRT_LibraryPath_x64)
$(UniversalCRT_LibraryPath_x86)
$(UniversalCRT_PropsPath)
$(UniversalCRT_SourcePath)
$(UniversalCRTSdkDir)
$(UniversalCRTSdkDir_10)
$(UseDebugLibraries)
$(UseLegacyManagedDebugger)
$(UseOfATL)
$(UseOfMfc)
$(USERDOMAIN)
$(USERDOMAIN_ROAMINGPROFILE)
$(USERNAME)
$(USERPROFILE)
$(UserRootDir)
$(VBOX_MSI_INSTALL_PATH)
$(VC_ATLMFC_IncludePath)
$(VC_ATLMFC_SourcePath)
$(VC_CRT_SourcePath)
$(VC_ExecutablePath_ARM)
$(VC_ExecutablePath_ARM64)
$(VC_ExecutablePath_x64)
$(VC_ExecutablePath_x64_ARM)
$(VC_ExecutablePath_x64_ARM64)
$(VC_ExecutablePath_x64_x64)
$(VC_ExecutablePath_x64_x86)
$(VC_ExecutablePath_x86)
$(VC_ExecutablePath_x86_ARM)
$(VC_ExecutablePath_x86_ARM64)
$(VC_ExecutablePath_x86_x64)
$(VC_ExecutablePath_x86_x86)
$(VC_IFCPath)
$(VC_IncludePath)
$(VC_LibraryPath_ARM)
$(VC_LibraryPath_ARM64)
$(VC_LibraryPath_ATL_ARM)
$(VC_LibraryPath_ATL_ARM64)
$(VC_LibraryPath_ATL_x64)
$(VC_LibraryPath_ATL_x86)
$(VC_LibraryPath_VC_ARM)
$(VC_LibraryPath_VC_ARM_Desktop)
$(VC_LibraryPath_VC_ARM_OneCore)
$(VC_LibraryPath_VC_ARM_Store)
$(VC_LibraryPath_VC_ARM64)
$(VC_LibraryPath_VC_ARM64_Desktop)
$(VC_LibraryPath_VC_ARM64_OneCore)
$(VC_LibraryPath_VC_ARM64_Store)
$(VC_LibraryPath_VC_x64)
$(VC_LibraryPath_VC_x64_Desktop)
$(VC_LibraryPath_VC_x64_OneCore)
$(VC_LibraryPath_VC_x64_Store)
$(VC_LibraryPath_VC_x86)
$(VC_LibraryPath_VC_x86_Desktop)
$(VC_LibraryPath_VC_x86_OneCore)
$(VC_LibraryPath_VC_x86_Store)
$(VC_LibraryPath_x64)
$(VC_LibraryPath_x86)
$(VC_PGO_RunTime_Dir)
$(VC_ReferencesPath_ARM)
$(VC_ReferencesPath_ARM64)
$(VC_ReferencesPath_ATL_ARM)
$(VC_ReferencesPath_ATL_ARM64)
$(VC_ReferencesPath_ATL_x64)
$(VC_ReferencesPath_ATL_x86)
$(VC_ReferencesPath_VC_ARM)
$(VC_ReferencesPath_VC_ARM64)
$(VC_ReferencesPath_VC_x64)
$(VC_ReferencesPath_VC_x86)
$(VC_ReferencesPath_x64)
$(VC_ReferencesPath_x86)
$(VC_SourcePath)
$(VC_VC_IncludePath)
$(VC_VS_IncludePath)
$(VC_VS_LibraryPath_VC_VS_ARM)
$(VC_VS_LibraryPath_VC_VS_x64)
$(VC_VS_LibraryPath_VC_VS_x86)
$(VC_VS_SourcePath)
$(VCIDEInstallDir)
$(VCIDEInstallDir_150)
$(VCInstallDir)
$(VCInstallDir_150)
$(VCLibPackagePath)
$(VCProjectVersion)
$(VCTargetsPath)
$(VCTargetsPath10)
$(VCTargetsPath11)
$(VCTargetsPath12)
$(VCTargetsPath14)
$(VCTargetsPath15)
$(VCTargetsPathActual)
$(VCTargetsPathEffective)
$(VCToolArchitecture)
$(VCToolsInstallDir)
$(VCToolsInstallDir_150)
$(VCToolsVersion)
$(VisualStudioDir)
$(VisualStudioEdition)
$(VisualStudioVersion)
$(VS_ExecutablePath)
$(VS140COMNTOOLS)
$(VSAPPIDDIR)
$(VSAPPIDNAME)
$(VSInstallDir)
$(VSInstallDir_150)
$(VsInstallRoot)
$(VSLANG)
$(VSSKUEDITION)
$(VSVersion)
$(WDKBinRoot)
$(WebBrowserDebuggerDebuggerlype)
$(WebServiceDebuggerDebuggerlype)
$(WebServiceDebuggerSQLDebugging)
$(WholeProgramOptimization)
$(WholeProgramOptimizationAvailabilityInstrument)
$(WholeProgramOptimizationAvailabilityOptimize)
$(WholeProgramOptimizationAvailabilityTrue)
$(WholeProgramOptimizationAvailabilityUpdate)
$(windir)
$(Windows81SdkInstalled)
$(WindowsAppContainer)
$(WindowsSDK_ExecutablePath)
$(WindowsSDK_ExecutablePath_arm)
$(WindowsSDK_ExecutablePath_arm64)
$(WindowsSDK_ExecutablePath_x64)
$(WindowsSDK_LibraryPath_x86)
$(WindowsSDK_MetadataFoundationPath)
$(WindowsSDK_MetadataPath)
$(WindowsSDK_MetadataPathVersioned)
$(WindowsSDK_PlatformPath)
$(WindowsSDK_SupportedAPIs_arm)
$(WindowsSDK_SupportedAPIs_x64)
$(WindowsSDK_SupportedAPIs_x86)
$(WindowsSDK_UnionMetadataPath)
$(WindowsSDK80Path)
$(WindowsSdkDir)
$(WindowsSdkDir_10)
$(WindowsSdkDir_81)
$(WindowsSdkDir_81A)
$(WindowsSDKToolArchitecture)
$(WindowsTargetPlatformVersion)
$(WinRT_IncludePath)
$(WMSISProject)
$(WMSISProjectDirectory)

Where to find this list within Visual Studio:

  1. Open your C++ project's dialogue Property Pages
  2. Select any textual field that can use a configuration variable. (in the screenshot, I use Target Name)
  3. On the right side of the text box, click the small combobox button and select option <Edit...>.
  4. In the new window (here, title is Target Name), click on button Macros>>.
  5. Scroll through the giant list of environment/linker/macro variables.

Motivational screenshot:

Visual Studio project Property Pages with exemplary Macro variable list

Difference between string and text in rails?

If the attribute is matching f.text_field in form use string, if it is matching f.text_area use text.

Passing html values into javascript functions

Here is the JSfiddle Demo

I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order so you can check if it's greater than zero:

<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p> 

function verifyorder() {
        var order = document.getElementById('value').value;
        if (+order > 0) {
            alert(+order);
            return true;
        }
        else {
            alert("Sorry, you need to enter a positive integer value, try again");
            document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
        }
    }

Unable to establish SSL connection, how do I fix my SSL cert?

SSL23_GET_SERVER_HELLO:unknown protocol

This error happens when OpenSSL receives something other than a ServerHello in a protocol version it understands from the server. It can happen if the server answers with a plain (unencrypted) HTTP. It can also happen if the server only supports e.g. TLS 1.2 and the client does not understand that protocol version. Normally, servers are backwards compatible to at least SSL 3.0 / TLS 1.0, but maybe this specific server isn't (by implementation or configuration).

It is unclear whether you attempted to pass --no-check-certificate or not. I would be rather surprised if that would work.

A simple test is to use wget (or a browser) to request http://example.com:443 (note the http://, not https://); if it works, SSL is not enabled on port 443. To further debug this, use openssl s_client with the -debug option, which right before the error message dumps the first few bytes of the server response which OpenSSL was unable to parse. This may help to identify the problem, especially if the server does not answer with a ServerHello message. To see what exactly OpenSSL is expecting, check the source: look for SSL_R_UNKNOWN_PROTOCOL in ssl/s23_clnt.c.

In any case, looking at the apache error log may provide some insight too.

Excel Define a range based on a cell value

Here is an option. It works by using making an INDIRECT(ADDRESS(...)) from the ROW and COLUMN of the start cell, A1, down to the initial row + the number of rows held in B1.

SUM(INDIRECT(ADDRESS(ROW(A1),COLUMN(A1))):INDIRECT(ADDRESS(ROW(A1)+B1,COLUMN(A1))))

A1: is the start of data in a the "A" column

B1: is the number of rows to sum

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I solved this issue after changing the "Gradle Version" and "Android Plugin version".

You just goto "File>>Project Structure>>Project>>" and make changes here. I have worked a combination of versions from another working project of mine and added to the Project where I was getting this problem.

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Not sure if this is an issue. Endpoint and binding both have the same name

Easy way to convert a unicode list to a list containing python strings?

There are several ways to do this. I converted like this

def clean(s):
    s = s.replace("u'","")
    return re.sub("[\[\]\'\s]", '', s)

EmployeeList = [clean(i) for i in str(EmployeeList).split(',')]

After that you can check

if '1001' in EmployeeList:
    #do something

Hope it will help you.

How do you get a list of the names of all files present in a directory in Node.js?

I've recently built a tool for this that does just this... It fetches a directory asynchronously and returns a list of items. You can either get directories, files or both, with folders being first. You can also paginate the data in case where you don't want to fetch the entire folder.

https://www.npmjs.com/package/fs-browser

This is the link, hope it helps someone!

How to show MessageBox on asp.net?

You could just simply write but you have to use JavaScript regardless.

Page.ClientScript.RegisterStartupScript(Page.GetType(), "Message Box", "<script language = 'javascript'>alert('dd')</script>");

MySQL foreign key constraints, cascade delete

I think (I'm not certain) that foreign key constraints won't do precisely what you want given your table design. Perhaps the best thing to do is to define a stored procedure that will delete a category the way you want, and then call that procedure whenever you want to delete a category.

CREATE PROCEDURE `DeleteCategory` (IN category_ID INT)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
BEGIN

DELETE FROM
    `products`
WHERE
    `id` IN (
        SELECT `products_id`
        FROM `categories_products`
        WHERE `categories_id` = category_ID
    )
;

DELETE FROM `categories`
WHERE `id` = category_ID;

END

You also need to add the following foreign key constraints to the linking table:

ALTER TABLE `categories_products` ADD
    CONSTRAINT `Constr_categoriesproducts_categories_fk`
    FOREIGN KEY `categories_fk` (`categories_id`) REFERENCES `categories` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT `Constr_categoriesproducts_products_fk`
    FOREIGN KEY `products_fk` (`products_id`) REFERENCES `products` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE

The CONSTRAINT clause can, of course, also appear in the CREATE TABLE statement.

Having created these schema objects, you can delete a category and get the behaviour you want by issuing CALL DeleteCategory(category_ID) (where category_ID is the category to be deleted), and it will behave how you want. But don't issue a normal DELETE FROM query, unless you want more standard behaviour (i.e. delete from the linking table only, and leave the products table alone).

Find integer index of rows with NaN in pandas dataframe

in the case you have datetime index and you want to have the values:

df.loc[pd.isnull(df).any(1), :].index.values

Xampp Access Forbidden php

I got the same error because somehow deleted the index.php and accessing the folder without index.php gave same error.

How to reenable event.preventDefault?

function(e){ e.preventDefault();

and its opposite

function(e){ return true; }

cheers!

Bootstrap 3 truncate long text inside rows of a table in a responsive way

You need to use table-layout:fixed in order for CSS ellipsis to work on the table cells.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

demo: http://bootply.com/9njmoY2CmS

How to return the current timestamp with Moment.js?

Here you are assigning an instance of momentjs to CurrentDate:

var CurrentDate = moment();

Here just a string, the result from default formatting of a momentjs instance:

var CurrentDate = moment().format();

And here the number of seconds since january of... well, unix timestamp:

var CurrentDate = moment().unix();

And here another string as ISO 8601 (What's the difference between ISO 8601 and RFC 3339 Date Formats?):

var CurrentDate = moment().toISOString();

And this can be done too:

var a = moment();
var b = moment(a.toISOString());

console.log(a.isSame(b)); // true

Alter user defined type in SQL Server

The simplest way to do this is through Visual Studio's object explorer, which is also supported in the Community edition.

Once you have made a connection to SQL server, browse to the type, right click and select View Code, make your changes to the schema of the user defined type and click update. Visual Studio should show you all of the dependencies for that object and generate scripts to update the type and recompile dependencies.

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

How to print / echo environment variables?

These need to go as different commands e.g.:

NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"

The expansion $NAME to empty string is done by the shell earlier, before running echo, so at the time the NAME variable is passed to the echo command's environment, the expansion is already done (to null string).

To get the same result in one command:

NAME=sam printenv NAME

How to insert close button in popover for Bootstrap

This works with multiple popovers and I also added a little big of extra JS to handle the z-index issues that happen with overlapping popovers:

http://jsfiddle.net/erik1337/fvE22/

JavaScript:

var $elements = $('.my-popover');
$elements.each(function () {
    var $element = $(this);

    $element.popover({
        html: true,
        placement: 'top',
        container: $('body'), // This is just so the btn-group doesn't get messed up... also makes sorting the z-index issue easier
        content: $('#content').html()
    });

    $element.on('shown.bs.popover', function (e) {
        var popover = $element.data('bs.popover');
        if (typeof popover !== "undefined") {
            var $tip = popover.tip();
            zindex = $tip.css('z-index');

            $tip.find('.close').bind('click', function () {
                popover.hide();
            });

            $tip.mouseover(function (e) {
                $tip.css('z-index', function () {
                    return zindex + 1;
                });
            })
                .mouseout(function () {
                $tip.css('z-index', function () {
                    return zindex;
                });
            });
        }
    });
});

HTML:

<div class="container-fluid">
    <div class="well popover-demo col-md-12">
        <div class="page-header">
             <h3 class="page-title">Bootstrap 3.1.1 Popovers with a close button</h3>

        </div>
        <div class="btn-group">
            <button type="button" data-title="Popover One" class="btn btn-primary my-popover">Click me!</button>
            <button type="button" data-title="Popover Two" class="btn btn-primary my-popover">Click me!</button>
            <button type="button" data-title="Popover Three (and the last one gets a really long title!)" class="btn btn-primary my-popover">Click me!</button>
        </div>
    </div>
</div>
<div id="content" class="hidden">
    <button type="button" class="close">&times;</button>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

CSS:

/* Make the well behave for the demo */
 .popover-demo {
    margin-top: 5em
}
/* Popover styles */
 .popover .close {
    position:absolute;
    top: 8px;
    right: 10px;
}
.popover-title {
    padding-right: 30px;
}

Why do you need to invoke an anonymous function on the same line?

One thing I found confusing is that the "()" are grouping operators.

Here is your basic declared function.

Ex. 1:

var message = 'SO';

function foo(msg) {
    alert(msg);
}

foo(message);

Functions are objects, and can be grouped. So let's throw parens around the function.

Ex. 2:

var message = 'SO';

function foo(msg) {  //declares foo
    alert(msg);
}

(foo)(message);     // calls foo

Now instead of declaring and right-away calling the same function, we can use basic substitution to declare it as we call it.

Ex. 3.

var message = 'SO';

(function foo(msg) {
    alert(msg);
})(message);          // declares & calls foo

Finally, we don't have a need for that extra foo because we're not using the name to call it! Functions can be anonymous.

Ex. 4.

var message = 'SO';

(function (msg) {   // remove unnecessary reference to foo
    alert(msg);
})(message);

To answer your question, refer back to Example 2. Your first line declares some nameless function and groups it, but does not call it. The second line groups a string. Both do nothing. (Vincent's first example.)

(function (msg){alert(msg)});  
('SO');                       // nothing.

(foo); 
(msg); //Still nothing.

But

(foo)
(msg); //works

How to use the PI constant in C++

I would do

template<typename T>
T const pi = std::acos(-T(1));

or

template<typename T>
T const pi = std::arg(-std::log(T(2)));

I would not typing in p to the precision you need. What is that even supposed to mean? The precision you need is the precision of T, but we know nothing about T.

You might say: What are you talking about? T will be float, double or long double. So, just type in the precision of long double, i.e.

template<typename T>
T const pi = static_cast<T>(/* long double precision p */);

But do you really know that there won't be a new floating point type in the standard in the future with an even higher precision than long double? You don't.

And that's why the first solution is beautiful. You can be quite sure that the standard would overload the trigonometric functions for a new type.

And please, don't say that the evaluation of a trigonometric function at initialization is a performance penalty.

How to force Eclipse to ask for default workspace?

I had the same problem on my eclipse, and calling eclipse -clean did not solve the problem.

In the end I figured out that within the installation folder of eclipse there is a script called eclipse. This script does some setting of environment variables and then calls eclipse.bin. The call for eclipse.bin contained the command line switch

-data ~/.eclipse

When I removed that switch from start-up script, I got the workspace selection as expected. Maybe that helps others to solve their problems.

Create view with primary key?

I got the error "The table/view 'dbo.vMyView' does not have a primary key defined" after I created a view in SQL server query designer. I solved the problem by using ISNULL on a column to force entity framework to use it as a primary key. You might have to restart visual studio to get the warnings to go away.

CREATE VIEW [dbo].[vMyView]
AS
SELECT ISNULL(Id, -1) AS IdPrimaryKey, Name
FROM  dbo.MyTable

How to use Global Variables in C#?

A useful feature for this is using static

As others have said, you have to create a class for your globals:

public static class Globals {
    public const float PI = 3.14;
}

But you can import it like this in order to no longer write the class name in front of its static properties:

using static Globals;
[...]
Console.WriteLine("Pi is " + PI);

How to add a new column to an existing sheet and name it?

For your question as asked

Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))

If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA

How to run a script at a certain time on Linux?

Usually in Linux you use crontab for this kind of scduled tasks. But you have to specify the time when you "setup the timer" - so if you want it to be configurable in the file itself, you will have to create some mechanism to do that.

But in general, you would use for example:

30 1 * * 5 /path/to/script/script.sh

Would execute the script every Friday at 1:30 (AM) Here:

30 is minutes

1 is hour

next 2 *'s are day of month and month (in that order) and 5 is weekday

What is a "static" function in C?

Minor nit: static functions are visible to a translation unit, which for most practical cases is the file the function is defined in. The error you are getting is commonly referred to as violation of the One Definition Rule.

The standard probably says something like:

"Every program shall contain exactly one definition of every noninline function or object that is used in that program; no diagnostic required."

That is the C way of looking at static functions. This is deprecated in C++ however.

In C++, additionally, you can declare member functions static. These are mostly metafunctions i.e. they do not describe/modify a particular object's behavior/state but act on the whole class itself. Also, this means that you do not need to create an object to call a static member function. Further, this also means, you only get access to static member variables from within such a function.

I'd add to Parrot's example the Singleton pattern which is based on this sort of a static member function to get/use a single object throughout the lifetime of a program.

What ports does RabbitMQ use?

PORT 4369: Erlang makes use of a Port Mapper Daemon (epmd) for resolution of node names in a cluster. Nodes must be able to reach each other and the port mapper daemon for clustering to work.

PORT 35197 set by inet_dist_listen_min/max Firewalls must permit traffic in this range to pass between clustered nodes

RabbitMQ Management console:

  • PORT 15672 for RabbitMQ version 3.x
  • PORT 55672 for RabbitMQ pre 3.x

PORT 5672 RabbitMQ main port.

For a cluster of nodes, they must be open to each other on 35197, 4369 and 5672.

For any servers that want to use the message queue, only 5672 is required.

How to pass data from Javascript to PHP and vice versa?

I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.

Jquery UI tooltip does not support html content

I solved it with a custom data tag, because a title attribute is required anyway.

$("[data-tooltip]").each(function(i, e) {
    var tag = $(e);
    if (tag.is("[title]") === false) {
        tag.attr("title", "");
    }
});

$(document).tooltip({
    items: "[data-tooltip]",
    content: function () {
        return $(this).attr("data-tooltip");
    }
});

Like this it is html conform and the tooltips are only shown for wanted tags.

How to resolve merge conflicts in Git repository?

This is now really easy with Atom. I just open the file in Atom, it shows the conflicting lines, and lets you pick the one you want to use with a click of the mouse, and resolves the conflict.

Add/commit/push and all is well.

How to create JSON object Node.js

The JavaScript Object() constructor makes an Object that you can assign members to.

myObj = new Object()
myObj.key = value;
myObj[key2] = value2;   // Alternative

Delete files older than 15 days using PowerShell

$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Recurse

This will delete old folders and it content.

How to get two or more commands together into a batch file

if I understand you right (not sure), the start parameter /D should help you:

start "cmd" /D %PathName% %comd%

/D sets the start-directory (see start /?)

Change input text border color without changing its height

Is this what you are looking for.

$("input.address_field").on('click', function(){  
     $(this).css('border', '2px solid red');
});

Using the Underscore module with Node.js

Or :

    var _ = require('underscore')._;

Accessing dict keys like an attribute?

You can pull a convenient container class from the standard library:

from argparse import Namespace

to avoid having to copy around code bits. No standard dictionary access, but easy to get one back if you really want it. The code in argparse is simple,

class Namespace(_AttributeHolder):
    """Simple object for storing attributes.

    Implements equality by attribute names and values, and provides a simple
    string representation.
    """

    def __init__(self, **kwargs):
        for name in kwargs:
            setattr(self, name, kwargs[name])

    __hash__ = None

    def __eq__(self, other):
        return vars(self) == vars(other)

    def __ne__(self, other):
        return not (self == other)

    def __contains__(self, key):
        return key in self.__dict__

jQuery ID starts with

Here you go:

$('td[id^="' + value +'"]')

so if the value is for instance 'foo', then the selector will be 'td[id^="foo"]'.

Note that the quotes are mandatory: [id^="...."].

Source: http://api.jquery.com/attribute-starts-with-selector/

Launch Image does not show up in my iOS App

The problem with the accepted answer is that if you don't set the Launch Screen File, your application will be in upscaling mode on devices such as the iPhone 6 & 6+ => blurry rendering.

Below is what I did to have a complete working solution (I'm targeting iOS 7.1 & using Xcode 8) on every device (truly, I was getting crazy about this upscaling problem)

1. Prepare your .xcassets

To simplify it, I'm using a vector .PDF file. It is very convenient and avoid creating multiple images for each resolution (1x, 2x, 3x...). I also assume here you already created your xcassets.

  • Add your launch screen image (or vector file) to your project
  • Go to your .xcassets and create a New Image Set. In the Attributes window of the Image, select Scales -> Single Scale
  • Drag and drop the vector file in the Image Set.

Create an Image Set for your .xcassets

2. Create your Launch Screen file

Create a Launch Screen file

3. Add your image to your Launch Screen file

  • Add an Image View object to your Launch Screen file (delete the labels that were automatically created). This image view should refer to the previous .xcassets Image Set. You can refer it from the Name attribute. At this stage, you should correctly see your launch screen image in your image view.
  • Add constraints to this image view to keep aspect ratio depending on the screen resolution.

Add the splash screen image to your Launch Screen file

4. Add your Launch Screen file to your target

Fianlly, in your Target General properties, refer the Launch Screen file. Target Properties and Launch Screen

Start your app, and your splash screen should be displayed. Try also on iPhone6 & iPhone6+, and your application should be correctly displayed without any upscaling (the Launch Screen file aims to do this).

What does "Changes not staged for commit" mean

What worked for me was to go to the root folder, where .git/ is. I was inside one the child folders and got there error.

Breaking out of a for loop in Java

public class Test {

public static void main(String args[]) {

  for(int x = 10; x < 20; x = x+1) {
     if(x==15)
         break;
     System.out.print("value of x : " + x );
     System.out.print("\n");
  }
}
}

Split and join C# string

You can use string.Split and string.Join:

string theString = "Some Very Large String Here";
var array = theString.Split(' ');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));

If you know you always only want to split off the first element, you can use:

var array = theString.Split(' ', 2);

This makes it so you don't have to join:

string restOfArray = array[1];

Adjust table column width to content size

The problem was the table width. I had used width: 100% for the table. The table columns are adjusted automatically after removing the width tag.

Combating AngularJS executing controller twice

I just went through this, but the issue was different from the accepted answer. I'm really leaving this here for my future self, to include the steps I went through to fix it.

  1. Remove redundant controller declarations
  2. Check trailing slashes in routes
  3. Check for ng-ifs
  4. Check for any unnecessary wrapping ng-view calls (I accidentally had left in an ng-view that was wrapping my actual ng-view. This resulted in three calls to my controllers.)
  5. If you are on Rails, you should remove the turbolinks gem from your application.js file. I wasted a whole day to discover that. Found answer here.
  6. Initializing the app twice with ng-app and with bootstrap. Combating AngularJS executing controller twice
  7. When using $compile on whole element in 'link'-function of directive that also has its own controller defined and uses callbacks of this controller in template via ng-click etc. Found answer here.

invalid conversion from 'const char*' to 'char*'

Well, data.str().c_str() yields a char const* but your function Printfunc() wants to have char*s. Based on the name, it doesn't change the arguments but merely prints them and/or uses them to name a file, in which case you should probably fix your declaration to be

void Printfunc(int a, char const* loc, char const* stream)

The alternative might be to turn the char const* into a char* but fixing the declaration is preferable:

Printfunc(num, addr, const_cast<char*>(data.str().c_str()));

OPTION (RECOMPILE) is Always Faster; Why?

There are times that using OPTION(RECOMPILE) makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:

EXEC sp_updatestats

And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.

Adding OPTION(RECOMPILE) rebuilds the execution plan every time that your query executes. I have never heard that described as creates a new lookup strategy but maybe we are just using different terms for the same thing.

When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but if you are using a parameterized query then this ends up being a stored proc call) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (parameter sniffing), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.

In summary - I don't see any reason that OPTION(RECOMPILE) would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.

And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.

How to check size of a file using Bash?

I would use du's --threshold for this. Not sure if this option is available in all versions of du but it is implemented in GNU's version.

Quoting from du(1)'s manual:

-t, --threshold=SIZE
       exclude entries smaller than SIZE if positive, or entries greater
       than SIZE if negative

Here's my solution, using du --threshold= for OP's use case:

THRESHOLD=90k
if [[ -z "$(du --threshold=${THRESHOLD} file.txt)" ]]; then
    mail -s "file.txt size is below ${THRESHOLD}, please fix. " [email protected] < /dev/null
    mv -f /root/tmp/file.txt /var/www/file.txt
fi

The advantage of that, is that du can accept an argument to that option in a known format - either human as in 10K, 10MiB or what ever you feel comfortable with - you don't need to manually convert between formats / units since du handles that.

For reference, here's the explanation on this SIZE argument from the man page:

The SIZE argument is an integer and optional unit (example: 10K is 
10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers
of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on.

Add Marker function with Google Maps API

<div id="map" style="width:100%;height:500px"></div>

<script>
function myMap() {
  var myCenter = new google.maps.LatLng(51.508742,-0.120850);
  var mapCanvas = document.getElementById("map");
  var mapOptions = {center: myCenter, zoom: 5};
  var map = new google.maps.Map(mapCanvas, mapOptions);
  var marker = new google.maps.Marker({position:myCenter});
  marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>

Angular2 @Input to a property with get/set

You could set the @Input on the setter directly, as described below:

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
@Input() set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}

See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.

Assign variable value inside if-statement

Variables can be assigned but not declared inside the conditional statement:

int v;
if((v = someMethod()) != 0) return true;

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

How to hide soft keyboard on android after clicking outside EditText?

Adding on to a previous answer by @sumit sonawane , this solution will not hide the keyboard if the user is scrolling.

public long pressTime = 0;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        pressTime = System.currentTimeMillis();
    }
    else if (ev.getAction() == MotionEvent.ACTION_UP) {
        long releaseTime = System.currentTimeMillis();
        if (releaseTime-pressTime < 200) {
            if (getCurrentFocus() != null) {
                GhostTube.print("BottomNavActivity", "Touch event with keyboard detected...");
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
            }
        }
    }
    return super.dispatchTouchEvent(ev);
}

Add code to your activity, will also take care of fragments.

Location of ini/config files in linux/unix?

  1. Typically in a dotfile (like .myprogramrc) in the user's home directory.
  2. It is of course up to the programmer but normally command line arguments override everything else. If environment variables are used it is usually as an alternative to the command line arguments or to specify where the configuration is located.

How do I pass command-line arguments to a WinForms application?

The best way to work with args for your winforms app is to use

string[] args = Environment.GetCommandLineArgs();

You can probably couple this with the use of an enum to solidify the use of the array througout your code base.

"And you can use this anywhere in your application, you aren’t just restricted to using it in the main() method like in a console application."

Found at:HERE

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

I had multiple dataframes with different floating point, so thx to Allans idea made dynamic length.

pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)

The minus of this is that if You have last 0 in float, it will cut it. So it will be not 0.000070, but 0.00007.

variable is not declared it may be inaccessible due to its protection level

I have suffered a similar problem, with a Sub not accessible in runtime, but absolutely legal in editor. It was solved by changing destination Framework from 4.5.1 to 4.5. It seems that my IIS only had 4.5 version.

:)

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

Install a Windows service using a Windows command prompt?

Open command prompt as administrator, go to your Folder where your .exe resides. To Install Exe as service

D:\YourFolderName\YourExeName /i

To uninstall use /u.

Access event to call preventdefault from custom function originating from onclick attribute of tag

You can access the event from onclick like this:

<button onclick="yourFunc(event);">go</button>

and at your javascript function, my advice is adding that first line statement as:

function yourFunc(e) {
    e = e ? e : event;
}

then use everywhere e as event variable

#1062 - Duplicate entry for key 'PRIMARY'

What is the exact error message? #1062 means duplicate entry violating a primary key constraint for a column -- which boils down to the point that you cannot have two of the same values in the column. The error message should tell you which of your columns is constrained, I'm guessing "shares".

git checkout tag, git pull fails in branch

You need to set up your tracking (upstream) for the current branch

git branch --set-upstream master origin/master

Is already deprecated instead of that you can use --track flag

git branch --track master origin/master

I also like the doc reference that @casey notice:

-u <upstream>
  Set up <branchname>'s tracking information so <upstream> is considered  
  <branchname>'s upstream branch. If no <branchname> is specified,  
  then it defaults to the current branch.

Convert Dictionary<string,string> to semicolon separated string in c#

using System.Linq;

string s = string.Join(";", myDict.Select(x => x.Key + "=" + x.Value).ToArray());

(And if you're using .NET 4, or newer, then you can omit the final ToArray call.)

Difference between Console.Read() and Console.ReadLine()?

Difference between Read(),Readline() and ReadKey() in C#

Read()-Accept the string value and return the string value. Readline() -Accept the string and return Integer ReadKey() -Accept the character and return Character

Summary:

1.The above mentioned three methods are mainly used in Console application and these are used for return the different values . 2.If we use Read line or Read() we need press Enter button to come back to code. 3.If we using Read key() we can press any key to come back code in application

SQL LIKE condition to check for integer?

Which one of those is indexable?

This one is definitely btree-indexable:

WHERE title >= '0' AND title < ':'

Note that ':' comes after '9' in ASCII.

How to have multiple colors in a Windows batch file?

If you have a modern Windows (that has powershell installed), the following may work fine as well

call :PrintBright Something Something

  (do actual batch stuff here)

call :PrintBright Done!
goto :eof


:PrintBright
powershell -Command Write-Host "%*" -foreground "White"

Adjust the color as you see fit.

How to Run a jQuery or JavaScript Before Page Start to Load

Don't use $(document).ready() just put the script directly in the head section of the page. Pages are processed top to bottom so things at the top are processed first.

How to convert answer into two decimal point

If you have a Decimal or similar numeric type, you can use:

Math.Round(myNumber, 2)

EDIT: So, in your case, it would be:

Public Class Form1
  Private Sub btncalc_Click(ByVal sender As System.Object,
                            ByVal e As System.EventArgs) Handles btncalc.Click
    txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
    txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
  End Sub
End Class

Get first 100 characters from string, respecting full words

Sure. The easiest is probably to write a wrapper around preg_match:

function limitString($string, $limit = 100) {
    // Return early if the string is already shorter than the limit
    if(strlen($string) < $limit) {return $string;}

    $regex = "/(.{1,$limit})\b/";
    preg_match($regex, $string, $matches);
    return $matches[1];
}

EDIT : Updated to not ALWAYS include a space as the last character in the string

What is the difference between user and kernel modes in operating systems?

Other answers already explained the difference between user and kernel mode. If you really want to get into detail you should get a copy of Windows Internals, an excellent book written by Mark Russinovich and David Solomon describing the architecture and inside details of the various Windows operating systems.

How to select only the records with the highest date in LINQ

If you just want the last date for each account, you'd use this:

var q = from n in table
        group n by n.AccountId into g
        select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};

If you want the whole record:

var q = from n in table
        group n by n.AccountId into g
        select g.OrderByDescending(t=>t.Date).FirstOrDefault();

Duplicate / Copy records in the same MySQL table

You can alter the temporarily table to change the ID field to a bigint or so without the NOT NULL requirement, then set the ID to 0 in that temp table. After that add it back to the original table and the NULL will trigger the auto increment.

CREATE TEMPORARY TABLE tmptable SELECT * FROM x WHERE (id='123');
ALTER TABLE tmptable CHANGE id id bigint;
UPDATE tmptable SET id = NULL;
INSERT INTO x SELECT * FROM tmptable;

HTML - Change\Update page contents without refreshing\reloading the page

You've got the right idea, so here's how to go ahead: the onclick handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:

<script type="text/javascript">
function recp(id) {
  $('#myStyle').load('data.php?id=' + id);
}
</script>

<a href="#" onClick="recp('1')" > One   </a>
<a href="#" onClick="recp('2')" > Two   </a>
<a href="#" onClick="recp('3')" > Three </a>

<div id='myStyle'>
</div>

Then you put your PHP code into a separate file: (I've called it data.php in the above example)

<?php
  require ('myConnect.php');     
  $id = $_GET['id'];
  $results = mysql_query("SELECT para FROM content WHERE  para_ID='$id'");   
  if( mysql_num_rows($results) > 0 )
  {
   $row = mysql_fetch_array( $results );
   echo $row['para'];
  }
?>

Typescript: React event types

To combine both Nitzan's and Edwin's answers, I found that something like this works for me:

update = (e: React.FormEvent<EventTarget>): void => {
    let target = e.target as HTMLInputElement;
    this.props.login[target.name] = target.value;
}

Plotting lines connecting points

I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot is capable of plotting multiple lines with one command. If x and y are arrays, then plot draws one line for every column.

In your case, you can do the following:

x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5,  1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')

Have a long list of x's and y's, and want to connect adjacent pairs?

xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])

Want a specified (different) color for the dots and the lines?

plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')

Plot of two pairs of points, each connected by a separate line

How do I get the current absolute URL in Ruby on Rails?

None of the suggestions here in the thread helped me sadly, except the one where someone said he used the debugger to find what he looked for.

I've created some custom error pages instead of the standard 404 and 500, but request.url ended in /404 instead of the expected /non-existing-mumbo-jumbo.

What I needed to use was

request.original_url

Oracle: How to filter by date and time in a where clause

If SESSION_START_DATE_TIME is of type TIMESTAMP you may want to try using the SQL function TO_TIMESTAMP. Here is an example:

     SQL> CREATE TABLE t (ts TIMESTAMP);

     Table created.

     SQL> INSERT INTO t
       2       VALUES (
       3                 TO_TIMESTAMP (
       4                    '1/12/2012 5:03:27.221008 PM'
       5                   ,'mm/dd/yyyy HH:MI:SS.FF AM'
       6                 )
       7              );

     1 row created.

     SQL> SELECT *
       2    FROM t
       3   WHERE ts =
       4            TO_TIMESTAMP (
       5               '1/12/2012 5:03:27.221008 PM'
       6              ,'mm/dd/yyyy HH:MI:SS.FF AM'
       7            );
     TS
     -------------------------------------------------
     12-JAN-12 05.03.27.221008 PM

Difference between innerText, innerHTML and value?

InnerText will only return the text value of the page with each element on a newline in plain text, while innerHTML will return the HTML content of everything inside the body tag, and childNodes will return a list of nodes, as the name suggests.

Git Bash is extremely slow on Windows 7 x64

My Windows home directory is on the network, and I suspected that Git Bash commands were looking there first. Sure enough, when I looked at $PATH, it listed /h/bin first, where /h is a share on a Windows file server, even though /h/bin doesn't exist.
I edited /etc/profile and commented out the export command that puts it first in $PATH:

#export PATH="$HOME/bin:$PATH"

This made my commands run much faster, probably because Git Bash is no longer looking across the network for the executables. My /etc/profile was c:\Program Files (x86)\Git\etc\profile.

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Watching this course https://app.pluralsight.com/library/courses/angular-2-getting-started-update/discussion

The author explains that new version of JavaScript has for of and for in, the for of is to enumerate objects and the for in is to enumerate the index of the array.

Redirecting from cshtml page

Would be safer to do this.

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

So the controller for that action runs as well, to populate any model the view needs.

Source
Redirect from a view to another view

Although as @Satpal mentioned, I do recommend you do the redirecting on your controller.

mySQL select IN range

You can't, but you can use BETWEEN

SELECT job FROM mytable WHERE id BETWEEN 10 AND 15

Note that BETWEEN is inclusive, and will include items with both id 10 and 15.

If you do not want inclusion, you'll have to fall back to using the > and < operators.

SELECT job FROM mytable WHERE id > 10 AND id < 15

jquery: change the URL address without redirecting?

This is achieved through URL rewriting, not through URL obfuscating, which can't be done.

Another way to do this, as has been mentioned is by changing the hashtag, with

window.location.hash = "/2131/"

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)

Is there a simple way to remove unused dependencies from a maven pom.xml?

As others have said, you can use the dependency:analyze goal to find which dependencies are used and declared, used and undeclared, or unused and declared. You may also find dependency:analyze-dep-mgt useful to look for mismatches in your dependencyManagement section.

You can simply remove unwanted direct dependencies from your POM, but if they are introduced by third-party jars, you can use the <exclusions> tags in a dependency to exclude the third-party jars (see the section titled Dependency Exclusions for details and some discussion). Here is an example excluding commons-logging from the Spring dependency:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring</artifactId>
  <version>2.5.5</version>
  <exclusions>
    <exclusion>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
    </exclusion>
  </exclusions> 
</dependency>

key_load_public: invalid format

In the case you copy your public key with clipboard and paste it, it may happen the public key string can be broken which contains new-line.

Make sure your public key string formed as one line.

pip install returning invalid syntax

In windows, you have to run pip install command from( python path)/ scripts path in cmd prompt

C:/python27/scripts

pip install pandas

How can I get the concatenation of two lists in Python without modifying either one?

You can also use sum, if you give it a start argument:

>>> list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
>>> all_lists = sum([list1, list2, list3], [])
>>> all_lists
[1, 2, 3, 'a', 'b', 'c', 7, 8, 9]

This works in general for anything that has the + operator:

>>> sum([(1,2), (1,), ()], ())
(1, 2, 1)

>>> sum([Counter('123'), Counter('234'), Counter('345')], Counter())
Counter({'1':1, '2':2, '3':3, '4':2, '5':1})

>>> sum([True, True, False], False)
2

With the notable exception of strings:

>>> sum(['123', '345', '567'], '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]

FtpWebRequest Download File

    private static DataTable ReadFTP_CSV()
    {
        String ftpserver = "ftp://servername/ImportData/xxxx.csv";
        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));

        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

        Stream responseStream = response.GetResponseStream();

        // use the stream to read file from FTP 
        StreamReader sr = new StreamReader(responseStream);
        DataTable dt_csvFile = new DataTable();

        #region Code
        //Add Code Here To Loop txt or CSV file
        #endregion

        return dt_csvFile;

    }

I hope it can help you.

How to read html from a url in python 3

For python 2

import urllib
some_url = 'https://docs.python.org/2/library/urllib.html'
filehandle = urllib.urlopen(some_url)
print filehandle.read()

PHP, Get tomorrows date from date

First, coming up with correct abstractions is always a key. key to readability, maintainability, and extendability.

Here, quite obvious candidate is an ISO8601DateTime. There are at least two implementations: first one is a parsed datetime from a string, and the second one is tomorrow. Hence, there are two classes that can be used, and their combination results in (almost) desired outcome:

new Tomorrow(new FromISO8601('2013-01-22'));

Both objects are an ISO8601 datetime, so their textual representation is not exactly what you need. So the final stroke is to make them take a date-form:

new Date(
    new Tomorrow(
        new FromISO8601('2013-01-22')
    )
);

Since you need a textual representation, not just an object, you invoke a value() method.

For more about this approach, take a look at this post.

How can I trigger a Bootstrap modal programmatically?

If you are looking for a programmatical modal creation, you might love this:

http://nakupanda.github.io/bootstrap3-dialog/

Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.

Angular: Cannot Get /

The problem was that I ran the commands within the folder /project/src/app. Navigating back to the project folder so to /project and running ng serve from there solved my problem.

Add data dynamically to an Array

$array[] = 'Hi';

pushes on top of the array.

$array['Hi'] = 'FooBar';

sets a specific index.

How to check if a string contains a specific text

You can use strpos() or stripos() to check if the string contain the given needle. It will return the position where it was found, otherwise will return FALSE.

Use the operators === or `!== to differ FALSE from 0 in PHP.

How to remove all line breaks from a string

The answer provided by PointedEars is everything most of us need. But by following Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.

The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.

If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.

// replaces all "new line" characters contained in `someString` with the given `replacementString`
const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing
  const LF = `\u{000a}`; // Line Feed (\n)
  const VT = `\u{000b}`; // Vertical Tab
  const FF = `\u{000c}`; // Form Feed
  const CR = `\u{000d}`; // Carriage Return (\r)
  const CRLF = `${CR}${LF}`; // (\r\n)
  const NEL = `\u{0085}`; // Next Line
  const LS = `\u{2028}`; // Line Separator
  const PS = `\u{2029}`; // Paragraph Separator
  const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`
  let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?
  for (let lineTerminator of lineTerminators) {
    if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`
      let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`
      finalString = finalString.replace(regex, replacementString); // perform the replacement
    };
  };
  return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)
});

How do I localize the jQuery UI Datepicker?

1. You need to load the jQuery UI i18n files:

<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/i18n/jquery-ui-i18n.min.js">
</script>

2. Use $.datepicker.setDefaults function to set defaults for ALL datepickers.

3. In case you want to override setting(s) before setting defaults you can use this:

var options = $.extend(
    {},                                  // empty object
    $.datepicker.regional["fr"],         // fr regional
    { dateFormat: "d MM, y" /*, ... */ } // your custom options
);
$.datepicker.setDefaults(options);

The order of parameters is important because of the way jQuery.extend works. Two incorrect examples:

/*
 * This overwrites the global variable itself instead of creating a
 * customized copy of french regional settings
 */
$.extend($.datepicker.regional["fr"], { dateFormat: "d MM, y"});

/*
 * The desired dateFormat is overwritten by french regional 
 * settings' date format
 */
$.extend({ dateFormat: "d MM, y"}, $.datepicker.regional["fr"]);

Convert DataTable to List<T>

  1. IEnumerable<DataRow> rows = dataTable.AsEnumerable(); (System.Data.DataSetExtensions.dll)
  2. IEnumerable<DataRow> rows = dataTable.Rows.OfType<DataRow>(); (System.Core.dll)

How to change option menu icon in the action bar?

If you want to change icon/title menu in the actionbar/toolbar programmatically,

STEP by STEP

  1. Declare Menu in class

private var mMenu: Menu? = null

  1. Overide onCreateOptionsMenu method and find item so you need to change

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    mMenu = menu
    menuInflater.inflate(R.menu.menu, menu)
    if (mIsFavorite){
        mMenu?.findItem(R.id.action_favorite)?.icon = yourDrawable
    } else {
        mMenu?.findItem(R.id.action_favorite)?.icon = yourDrawable
    }
    return true
    

    }

  2. Use invalidateOptionsMenu() to update some changes in menu after onCreateOptionsMenu executed. This method will re-create menu

Spring MVC Controller redirect using URL parameters instead of in response

Hey you can just do one simple thing instead of using model to send parameter use HttpServletRequest object and do this

HttpServletRequest request;
request.setAttribute("param", "value")

now your parametrs will not be shown in your url header hope it works :)

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

Removing the title text of an iOS UIBarButtonItem

Non of the answers helped me. But a trick did - I just cleared the title of the view controller that pushed (where the back button is going to) just before pushing it.

So when the previous view doesn't have a title, on iOS 7 the back button will only have an arrow, without text.

On viewWillAppear of the pushing view, I placed back the original title.

Using margin:auto to vertically-align a div

Here's the best solution I've found: http://jsfiddle.net/yWnZ2/446/ Works in Chrome, Firefox, Safari, IE8-11 & Edge.

If you have a declared height (height: 1em, height: 50%, etc.) or it's an element where the browser knows the height (img, svg, or canvas for example), then all you need for vertical centering is this:

.message {
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
    margin: auto;
}

You'll usually want to specify a width or max-width so the content doesn't stretch the whole length of the screen/container.

If you're using this for a modal that you want always centered in the viewport overlapping other content, use position: fixed; for both elements instead of position: absolute. http://jsfiddle.net/yWnZ2/445/

Here's a more complete writeup: http://codepen.io/shshaw/pen/gEiDt

Fastest way to convert a dict's keys & values from `unicode` to `str`?

def to_str(key, value):
    if isinstance(key, unicode):
        key = str(key)
    if isinstance(value, unicode):
        value = str(value)
    return key, value

pass key and value to it, and add recursion to your code to account for inner dictionary.

Why does the C++ STL not provide any "tree" containers?

I think there are several reasons why there are no STL trees. Primarily Trees are a form of recursive data structure which, like a container (list, vector, set), has very different fine structure which makes the correct choices tricky. They are also very easy to construct in basic form using the STL.

A finite rooted tree can be thought of as a container which has a value or payload, say an instance of a class A and, a possibly empty collection of rooted (sub) trees; trees with empty collection of subtrees are thought of as leaves.

template<class A>
struct unordered_tree : std::set<unordered_tree>, A
{};

template<class A>
struct b_tree : std::vector<b_tree>, A
{};

template<class A>
struct planar_tree : std::list<planar_tree>, A
{};

One has to think a little about iterator design etc. and which product and co-product operations one allows to define and be efficient between trees - and the original STL has to be well written - so that the empty set, vector or list container is really empty of any payload in the default case.

Trees play an essential role in many mathematical structures (see the classical papers of Butcher, Grossman and Larsen; also the papers of Connes and Kriemer for examples of they can be joined, and how they are used to enumerate). It is not correct to think their role is simply to facilitate certain other operations. Rather they facilitate those tasks because of their fundamental role as a data structure.

However, in addition to trees there are also "co-trees"; the trees above all have the property that if you delete the root you delete everything.

Consider iterators on the tree, probably they would be realised as a simple stack of iterators, to a node, and to its parent, ... up to the root.

template<class TREE>
struct node_iterator : std::stack<TREE::iterator>{
operator*() {return *back();}
...};

However, you can have as many as you like; collectively they form a "tree" but where all the arrows flow in the direction toward the root, this co-tree can be iterated through iterators towards the trivial iterator and root; however it cannot be navigated across or down (the other iterators are not known to it) nor can the ensemble of iterators be deleted except by keeping track of all the instances.

Trees are incredibly useful, they have a lot of structure, this makes it a serious challenge to get the definitively correct approach. In my view this is why they are not implemented in the STL. Moreover, in the past, I have seen people get religious and find the idea of a type of container containing instances of its own type challenging - but they have to face it - that is what a tree type represents - it is a node containing a possibly empty collection of (smaller) trees. The current language permits it without challenge providing the default constructor for container<B> does not allocate space on the heap (or anywhere else) for an B, etc.

I for one would be pleased if this did, in a good form, find its way into the standard.

Access multiple elements of list knowing their index

You can use operator.itemgetter:

from operator import itemgetter 
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)

Or you can use numpy:

import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]

But really, your current solution is fine. It's probably the neatest out of all of them.

What is the best way to determine a session variable is null or empty in C#?

Are you using .NET 3.5? Create an IsNull extension method:

public static bool IsNull(this object input)
{
    input == null ? return true : return false;
}

public void Main()
{
   object x = new object();
   if(x.IsNull)
   {
      //do your thing
   }
}

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

I had the same problem and it works you just have to declare the i outside of the loop:

int i;

for(i = low; i <= high; ++i)

{
        res = runalg(i);
        if (res > highestres)
        {
                highestres = res;
        }

}

Algorithm to detect overlapping periods

There is a wonderful library with good reviews on CodeProject: http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET

That library does a lot of work concerning overlap, intersecting them, etc. It's too big to copy/paste all of it, but I'll see which specific parts which can be useful to you.

Event when window.location.href changes

There is a default onhashchange event that you can use.

Documented HERE

And can be used like this:

function locationHashChanged( e ) {
    console.log( location.hash );
    console.log( e.oldURL, e.newURL );
    if ( location.hash === "#pageX" ) {
        pageX();
    }
}

window.onhashchange = locationHashChanged;

If the browser doesn't support oldURL and newURL you can bind it like this:

//let this snippet run before your hashChange event binding code
if( !window.HashChangeEvent )( function() {
    let lastURL = document.URL;
    window.addEventListener( "hashchange", function( event ) {
        Object.defineProperty( event, "oldURL", { enumerable: true, configurable: true, value: lastURL } );
        Object.defineProperty( event, "newURL", { enumerable: true, configurable: true, value: document.URL } );
        lastURL = document.URL;
    } );
} () );

Check Whether a User Exists

Login to the server. grep "username" /etc/passwd This will display the user details if present.

Need a good hex editor for Linux

I am a VIMer. I can do some rare Hex edits with:

  • :%!xxd to switch into hex mode

  • :%!xxd -r to exit from hex mode

But I strongly recommend ht

apt-cache show ht

Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>

Homepage: http://hte.sourceforge.net/

Note: The package is called ht, whereas the executable is named hte after the package was installed.

  1. Supported file formats
    • common object file format (COFF/XCOFF32)
    • executable and linkable format (ELF)
    • linear executables (LE)
    • standard DO$ executables (MZ)
    • new executables (NE)
    • portable executables (PE32/PE64)
    • java class files (CLASS)
    • Mach exe/link format (MachO)
    • X-Box executable (XBE)
    • Flat (FLT)
    • PowerPC executable format (PEF)
  2. Code & Data Analyser
    • finds branch sources and destinations recursively
    • finds procedure entries
    • creates labels based on this information
    • creates xref information
    • allows to interactively analyse unexplored code
    • allows to create/rename/delete labels
    • allows to create/edit comments
    • supports x86, ia64, alpha, ppc and java code
  3. Target systems
    • DJGPP
    • GNU/Linux
    • FreeBSD
    • OpenBSD
    • Win32

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

I realize this question is old, but I wanted to post an alternate solution in case anyone else (like myself) found this thread while having the same question. I was able to work around the lack of an OR operator by echoing the variable and using findstr to validate.

for /f %%v in ('echo %var% ^| findstr /x /c:"1" /c:"2"') do (
    if %errorlevel% equ 0 echo true
)

UIDevice uniqueIdentifier deprecated - What to do now?

I'm sure Apple have annoyed many people with this change. I develop a bookkeeping app for iOS and have an online service to sync changes made on different devices. The service maintains a database of all devices and the changes that need to be propagated to them. Therefore it's important to know which devices are which. I'm keeping track of devices using the UIDevice uniqueIdentifier and for what it's worth, here are my thoughts.

  • Generate a UUID and store in user defaults? No good because this does not persist when the user deletes the app. If they install again later the online service should not create a new device record, that would waste resources on the server and give a list of devices containing the same one two or more times. Users would see more than one "Bob's iPhone" listed if they re-installed the app.

  • Generate a UUID and store in the keychain? This was my plan, since it persists even when the app is uninstalled. But when restoring an iTunes backup to a new iOS device, the keychain is transferred if the backup is encrypted. This could lead to two devices containing the same device id if the old and new devices are both in service. These should be listed as two devices in the online service, even if the device name is the same.

  • Generate a hash the MAC address and bundle id? This looks like the best solution for what I need. By hashing with the bundle id, the generated device id is not going to enable the device to be tracked across apps and I get a unique ID for the app+device combination.

It's interesting to note that Apple's own documentation refers to validating Mac App Store receipts by computing a hash of the system MAC address plus the bundle id and version. So this seems allowable by policy, whether it passes through app review I don't yet know.

Find all files in a directory with extension .txt in Python

Use fnmatch: https://docs.python.org/2/library/fnmatch.html

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file

When should null values of Boolean be used?

For all the good answers above, I'm just going to give a concrete example in Java servlet HttpSession class. Hope this example helps to clarify some question you may still have.

If you need to store and retrieve values for a session, you use setAttribute(String, Object), and getAttribute(String, Object) method. So for a boolean value, you are forced to use the Boolean class if you want to store it in an http session.

HttpSession sess = request.getSession(false);
Boolean isAdmin = (Boolean) sess.getAttribute("admin");
if (! isAdmin) ...

The last line will cause a NullPointerException if the attribute values is not set. (which is the reason led me to this post). So the 3 logic state is here to stay, whether you prefer to use it or not.

Delete specific line from a text file?

If the line you want to delete is based on the content of the line:

string line = null;
string line_to_delete = "the line i want to delete";

using (StreamReader reader = new StreamReader("C:\\input")) {
    using (StreamWriter writer = new StreamWriter("C:\\output")) {
        while ((line = reader.ReadLine()) != null) {
            if (String.Compare(line, line_to_delete) == 0)
                continue;

            writer.WriteLine(line);
        }
    }
}

Or if it is based on line number:

string line = null;
int line_number = 0;
int line_to_delete = 12;

using (StreamReader reader = new StreamReader("C:\\input")) {
    using (StreamWriter writer = new StreamWriter("C:\\output")) {
        while ((line = reader.ReadLine()) != null) {
            line_number++;

            if (line_number == line_to_delete)
                continue;

            writer.WriteLine(line);
        }
    }
}

How to detect iPhone 5 (widescreen devices)?

Here is our codes, test passed on ios7/ios8 for iphone4,iphone5,ipad,iphone6,iphone6p, no matter on devices or simulator:

#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) // iPhone and       iPod touch style UI

#define IS_IPHONE_5_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 568.0f)
#define IS_IPHONE_6_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 667.0f)
#define IS_IPHONE_6P_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 736.0f)
#define IS_IPHONE_4_AND_OLDER_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height < 568.0f)

#define IS_IPHONE_5_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 568.0f)
#define IS_IPHONE_6_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 667.0f)
#define IS_IPHONE_6P_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 736.0f)
#define IS_IPHONE_4_AND_OLDER_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) < 568.0f)

#define IS_IPHONE_5 ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_5_IOS8 : IS_IPHONE_5_IOS7 )
#define IS_IPHONE_6 ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_6_IOS8 : IS_IPHONE_6_IOS7 )
#define IS_IPHONE_6P ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_6P_IOS8 : IS_IPHONE_6P_IOS7 )
#define IS_IPHONE_4_AND_OLDER ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_4_AND_OLDER_IOS8 : IS_IPHONE_4_AND_OLDER_IOS7 )

How to calculate probability in a normal distribution given mean & standard deviation?

Scipy.stats is a great module. Just to offer another approach, you can calculate it directly using

import math
def normpdf(x, mean, sd):
    var = float(sd)**2
    denom = (2*math.pi*var)**.5
    num = math.exp(-(float(x)-float(mean))**2/(2*var))
    return num/denom

This uses the formula found here: http://en.wikipedia.org/wiki/Normal_distribution#Probability_density_function

to test:

>>> normpdf(7,5,5)  
0.07365402806066466
>>> norm(5,5).pdf(7)
0.073654028060664664

Convert base class to derived class

You can implement the conversion yourself, but I would not recommend that. Take a look at the Decorator Pattern if you want to do this in order to extend the functionality of an existing object.

Javascript "Uncaught TypeError: object is not a function" associativity question

I was getting this same error and spent a day and a half trying to find a solution. Naomi's answer lead me to the solution I needed.

My input (type=button) had an attribute name that was identical to a function name that was being called by the onClick event. Once I changed the attribute name everything worked.

<input type="button" name="clearEmployer" onClick="clearEmployer();">

changed to:

<input type="button" name="clearEmployerBtn" onClick="clearEmployer();">

How to validate an email address in JavaScript

function validatecontactEmail(email) { 

 if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))  
  {  
    return (true)  
  }  

    return (false)  

}

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

Find provisioning profile in Xcode 5

check here:

~/Library/MobileDevice/Provisioning Profiles

How to force NSLocalizedString to use a specific language

You can do something like this:

NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings" inDirectory:nil forLocalization:@"es"];


NSBundle *spanishBundle = [[NSBundle alloc] initWithPath:[bundlePath stringByDeletingLastPathComponent]];

NSLocalizedStringFromTableInBundle(@"House", nil, spanishBundle, nil):

Append to the end of a file in C

Open with append:

pFile2 = fopen("myfile2.txt", "a");

then just write to pFile2, no need to fseek().

Text size of android design TabLayout tabs

Try the snipped which is mentioned below, it works for me also.

In my layout xml where I have my TabLayout, have added style to the TabLayout like below :

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    style="@style/MyCustomTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabGravity="fill"
    app:tabMode="fixed" />

and in my style.xml I have defined the style that is used in my layout xml, check code for styles added below :

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="android:background">YOUR BACKGROUND COLOR</item>
    <item name="tabTextAppearance">@style/MyCustomTabText</item>
    <item name="tabSelectedTextColor">SELECTED TAB TEXT COLOR</item>
    <item name="tabIndicatorColor">SELECTED TAB INDICATOR COLOR</item>
</style>

<style name="MyCustomTabText" parent="TextAppearance.AppCompat.Button">
    <item name="android:textSize">YOUR TEXT SIZE</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@android:color/white</item>
</style>

I hope it will work for you.....

I want to load another HTML page after a specific amount of time

Use Javascript's setTimeout:

<body onload="setTimeout(function(){window.location = 'form2.html';}, 5000)">

How do I line up 3 divs on the same row?

I'm not sure how I ended up on this post but since most of the answers are using floats, absolute positioning, and other options which aren't optimal now a days, I figured I'd give a new answer that's more up to date on it's standards (float isn't really kosher anymore).

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
  flex-direction:row;_x000D_
}_x000D_
_x000D_
.column {_x000D_
  flex: 1 1 0px;_x000D_
  border: 1px solid black;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div class="column">Column 1</div>_x000D_
    <div class="column">Column 2<br>Column 2<br>Column 2<br>Column 2<br></div>_x000D_
    <div class="column">Column 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Remove element from JSON Object

JSfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}

Keep overflow div scrolled to bottom unless user scrolls up

Here is how I approached it. My div height is 650px. I decided that if the scroll height is within 150px of the bottom then auto scroll it. Else, leave it for the user.

if (container_block.scrollHeight - container_block.scrollTop < 800) {
                    container_block.scrollTo(0, container_block.scrollHeight);
}

How to use boolean datatype in C?

As an alternative to James McNellis answer, I always try to use enumeration for the bool type instead of macros: typedef enum bool {false=0; true=1;} bool;. It is safer b/c it lets the compiler do type checking and eliminates macro expansion races

What is compiler, linker, loader?

A Compiler translates lines of code from the programming language into machine language.

A Linker creates a link between two programs.

A Loader loads the program into memory in the main database, program, etc.

What should be in my .gitignore for an Android Studio project?

There is NO NEED to add to the source control any of the following:

.idea/
.gradle/
*.iml
build/
local.properties

So you can configure hgignore or gitignore accordingly.

The first time a developer clones the source control can go:

  1. Open Android Studio
  2. Import Project
  3. Browse for the build.gradle within the cloned repository and open it

That's all

PS: Android Studio will then, through maven, get the gradle plugin assuming that your build.gradle looks similar to this:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.12.2'
    }
}

allprojects {
    repositories {
        mavenCentral()
    }
}

Android studio will generate the content of .idea folder (including the workspace.xml, which shouldn't be in source control because it is generated) and the .gradle folder.

This approach is Eclipse-friendly in the way that the source control does not really know anything about Android Studio. Android Studio just needs the build.gradle to import a project and generate the rest.

Simple jQuery, PHP and JSONP example?

Simple jQuery, PHP and JSONP example is below:

_x000D_
_x000D_
window.onload = function(){_x000D_
 $.ajax({_x000D_
  cache: false,_x000D_
  url: "https://jsonplaceholder.typicode.com/users/2",_x000D_
  dataType: 'jsonp',_x000D_
  type: 'GET',_x000D_
  success: function(data){_x000D_
   console.log('data', data)_x000D_
  },_x000D_
  error: function(data){_x000D_
   console.log(data);_x000D_
  }_x000D_
 });_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How can I call a method in Objective-C?

I suggest you read The Objective-C Programming Language. The part about messaging is specifically what you want here, but the whole thing will help you get started. After that, maybe try doing a few tutorials to get a feel for it before you jump into making your own apps.

Fastest way to check if string contains only digits

Another approach!

string str = "12345";
bool containsOnlyDigits = true;
try { if(Convert.ToInt32(str) < 0){ containsOnlyDigits = false; } }
catch { containsOnlyDigits = false; }

Here, if the statement Convert.ToInt32(str) fails, then string does not contain digits only. Another possibility is that if the string has "-12345" which gets converted to -12345 successfully, then there is a check for verifying that the number converted is not less than zero.

What is a regular expression which will match a valid domain name without a subdomain?

^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,7}$

[domain - lower case letters and 0-9 only] [can have a hyphen] + [TLD - lower case only, must be beween 2 and 7 letters long]
http://rubular.com/ is brilliant for testing regular expressions!
Edit: Updated TLD maximum to 7 characters for '.rentals' as Dan Caddigan pointed out.

Regular expression for checking if capital letters are found consecutively in a string?

Edit: 2015-10-26: thanks for the upvotes - but take a look at tchrist's answer, especially if you develop for the web or something more "international".

Oren Trutners answer isn't quite right (see sample input of "RightHerE" which must be matched but isn't)

Here is the correct solution:

(?!^.*[A-Z]{2,}.*$)^[A-Za-z]*$

edit:

(?!^.*[A-Z]{2,}.*$)  // don't match the whole expression if there are two or more consecutive uppercase letters
^[A-Za-z]*$          // match uppercase and lowercase letters

/edit

the key for the solution is a negative lookahead see: http://www.regular-expressions.info/lookaround.html

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

This could happen for any number of reasons. If you have tried through all of the above and still getting the same error, I have one more solution.

Another reason this could happen is that

  1. If you have the same code base running before you started to run the fresh solution, you might encounter this error. The reason is that IIS Express is trying to run on the same port as it was for the old solution which has the physical path registered for the application start URL.
  2. Since the IIS cannot figure out the physical path to run the solution, it might not be able to locate all the dlls required to start the application.

Solutions:

  1. Try to change the application port to default. For example., Use http://localhost/ instead of http://localhost:25836/

  2. Try changing to any other port if you have already used the default port for the previous application. ex: http://localhost:25364/ instead of http://localhost/

This will allow the IIS/IIS Express to point to the default bin path of the newer application you are trying to run which will have all the required dlls to start the application.

get basic SQL Server table structure information

Name and datatype:

USE OurDatabaseName
GO

SELECT 
    sc.name AS [Columne Name], 
    st1.name AS [User Type],
    st2.name AS [Base Type]
FROM dbo.syscolumns sc
    INNER JOIN dbo.systypes st1 ON st1.xusertype = sc.xusertype
    INNER JOIN dbo.systypes st2 ON st2.xusertype = sc.xtype
-- STEP TWO: Change OurTableName to the table name
WHERE sc.id = OBJECT_ID('OurTableName')
ORDER BY sc.colid

Or:

SELECT COLUMN_NAME AS ColumnName, DATA_TYPE AS DataType, CHARACTER_MAXIMUM_LENGTH AS CharacterLength
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'OurTableName'

Excel Create Collapsible Indented Row Hierarchies

Create a Pivot Table. It has these features and many more.

If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.

How do you set your pythonpath in an already-created virtualenv?

  1. Initialize your virtualenv
cd venv

source bin/activate
  1. Just set or change your python path by entering command following:
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
  1. for checking python path enter in python:
   python

      \>\> import sys

      \>\> sys.path

How can I generate a list of consecutive numbers?

Just to give you another example, although range(value) is by far the best way to do this, this might help you later on something else.

list = []
calc = 0

while int(calc) < 9:
    list.append(calc)
    calc = int(calc) + 1

print list
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Chrome doesn't delete session cookies

Have you tried to Remove hangouts extension in Google Chrome? because it forces chrome to keep running even you close all the windows.

I was also facing the problem but it resolved now.

Ansible: Store command's stdout in new variable?

If you want to go further and extract the exact information you want from the Playbook results, use JSON query language like jmespath, an example:

  - name: Sample Playbook
    // Fill up your task
    no_log: True
    register: example_output

  - name: Json Query
    set_fact:
      query_result:
        example_output:"{{ example_output | json_query('results[*].name') }}"

Measure the time it takes to execute a t-sql query

Another way is using a SQL Server built-in feature named Client Statistics which is accessible through Menu > Query > Include Client Statistics.

You can run each query in separated query window and compare the results which is given in Client Statistics tab just beside the Messages tab.

For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.

Result

You can read all 3 ways for acquiring execution time in here. You may even need to display Estimated Execution Plan ctrlL for further investigation about your query.

Abort Ajax requests using jQuery

Just call xhr.abort() whether it's jquery ajax object or native XMLHTTPRequest object.

example:

//jQuery ajax
$(document).ready(function(){
    var xhr = $.get('/server');
    setTimeout(function(){xhr.abort();}, 2000);
});

//native XMLHTTPRequest
var xhr = new XMLHttpRequest();
xhr.open('GET','/server',true);
xhr.send();
setTimeout(function(){xhr.abort();}, 2000);

MySQL: When is Flush Privileges in MySQL really needed?

TL;DR

You should use FLUSH PRIVILEGES; only if you modify the grant tables directly using statements such as INSERT, UPDATE, or DELETE.

Webfont Smoothing and Antialiasing in Firefox and Opera

Adding

font-weight: normal;

To your @font-face fonts will fix the bold appearance in Firefox.

How to select last one week data from today's date

  1. The query is correct

2A. As far as last seven days have much less rows than whole table an index can help

2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size

How can I open Java .class files in a human-readable way?

That's compiled code, you'll need to use a decompiler like JAD: http://www.kpdus.com/jad.html

Trust Anchor not found for Android SSL Connection

I had the same problem what i found was that the certificate .crt file i provided missing an intermediate certificate. So I asked all .crt files from my server admin, then concatinated them in reverse order.

Ex. 1. Root.crt 2. Inter.crt 3. myCrt.crt

in windows i executed copy Inter.crt + Root.crt newCertificate.crt

(Here i ignored myCrt.crt)

Then i provided newCertificate.crt file into code via inputstream. Work done.

echo key and value of an array without and with loop

array_walk($v, function(&$value, $key) {
   echo $key . '--'. $value;
 });

Learn more about array_walk

set serveroutput on in oracle procedure

If you want to execute any procedure then firstly you have to set serveroutput on in the sqldeveloper work environment like.

->  SET SERVEROUTPUT ON;
-> BEGIN
dbms_output.put_line ('Hello World..');
dbms_output.put_line('Its displaying the values only for the Testing purpose');
END;
/

How to install cron

On CentOS/RHEL:

yum install cronie

AngularJS : Initialize service with asynchronous data

I used a similar approach to the one described by @XMLilley but wanted to have the ability to use AngularJS services like $http to load the configuration and do further initialization without the use of low level APIs or jQuery.

Using resolve on routes was also not an option because I needed the values to be available as constants when my app is started, even in module.config() blocks.

I created a small AngularJS app that loads the config, sets them as constants on the actual app and bootstraps it.

// define the module of your app
angular.module('MyApp', []);

// define the module of the bootstrap app
var bootstrapModule = angular.module('bootstrapModule', []);

// the bootstrapper service loads the config and bootstraps the specified app
bootstrapModule.factory('bootstrapper', function ($http, $log, $q) {
  return {
    bootstrap: function (appName) {
      var deferred = $q.defer();

      $http.get('/some/url')
        .success(function (config) {
          // set all returned values as constants on the app...
          var myApp = angular.module(appName);
          angular.forEach(config, function(value, key){
            myApp.constant(key, value);
          });
          // ...and bootstrap the actual app.
          angular.bootstrap(document, [appName]);
          deferred.resolve();
        })
        .error(function () {
          $log.warn('Could not initialize application, configuration could not be loaded.');
          deferred.reject();
        });

      return deferred.promise;
    }
  };
});

// create a div which is used as the root of the bootstrap app
var appContainer = document.createElement('div');

// in run() function you can now use the bootstrapper service and shutdown the bootstrapping app after initialization of your actual app
bootstrapModule.run(function (bootstrapper) {

  bootstrapper.bootstrap('MyApp').then(function () {
    // removing the container will destroy the bootstrap app
    appContainer.remove();
  });

});

// make sure the DOM is fully loaded before bootstrapping.
angular.element(document).ready(function() {
  angular.bootstrap(appContainer, ['bootstrapModule']);
});

See it in action (using $timeout instead of $http) here: http://plnkr.co/edit/FYznxP3xe8dxzwxs37hi?p=preview

UPDATE

I would recommend to use the approach described below by Martin Atkins and JBCP.

UPDATE 2

Because I needed it in multiple projects, I just released a bower module that takes care of this: https://github.com/philippd/angular-deferred-bootstrap

Example that loads data from the back-end and sets a constant called APP_CONFIG on the AngularJS module:

deferredBootstrapper.bootstrap({
  element: document.body,
  module: 'MyApp',
  resolve: {
    APP_CONFIG: function ($http) {
      return $http.get('/api/demo-config');
    }
  }
});

pyplot scatter plot marker size

It is the area of the marker. I mean if you have s1 = 1000 and then s2 = 4000, the relation between the radius of each circle is: r_s2 = 2 * r_s1. See the following plot:

plt.scatter(2, 1, s=4000, c='r')
plt.scatter(2, 1, s=1000 ,c='b')
plt.scatter(2, 1, s=10, c='g')

enter image description here

I had the same doubt when I saw the post, so I did this example then I used a ruler on the screen to measure the radii.

Can I set variables to undefined or pass undefined as an argument?

The basic difference is that undefined and null represent different concepts.

If only null was available, you would not be able to determine whether null was set intentionally as the value or whether the value has not been set yet unless you used cumbersome error catching: eg

var a;

a == null; // This is true
a == undefined; // This is true;
a === undefined; // This is true;

However, if you intentionally set the value to null, strict equality with undefined fails, thereby allowing you to differentiate between null and undefined values:

var b = null;
b == null; // This is true
b == undefined; // This is true;
b === undefined; // This is false;

Check out the reference here instead of relying on people dismissively saying junk like "In summary, undefined is a JavaScript-specific mess, which confuses everyone". Just because you are confused, it does not mean that it is a mess.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

This behaviour is also not specific to JavaScript and it completes the generalised concept that a boolean result can be true, false, unknown (null), no value (undefined), or something went wrong (error).

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

How can I use threading in Python?

For me, the perfect example for threading is monitoring asynchronous events. Look at this code.

# thread_test.py
import threading
import time

class Monitor(threading.Thread):
    def __init__(self, mon):
        threading.Thread.__init__(self)
        self.mon = mon

    def run(self):
        while True:
            if self.mon[0] == 2:
                print "Mon = 2"
                self.mon[0] = 3;

You can play with this code by opening an IPython session and doing something like:

>>> from thread_test import Monitor
>>> a = [0]
>>> mon = Monitor(a)
>>> mon.start()
>>> a[0] = 2
Mon = 2
>>>a[0] = 2
Mon = 2

Wait a few minutes

>>> a[0] = 2
Mon = 2

How to download Javadoc to read offline?

You can use something called Dash: Offline API Documentation for Mac. For Windows and Linux you have an alternative called Zeal.

Both of them are very similar. And you can get offline documentation for most of the APIs out there like Java, android, Angular, HTML5 etc .. almost everything.

I have also written a post on How to install Zeal on Ubuntu 14.04

How can I set a UITableView to grouped style

Swift 4+:

let myTableViewController = UITableViewController(style: .grouped)

Assign a synthesizable initial value to a reg in Verilog

You should use what your FPGA documentation recommends. There is no portable way to initialize register values other than using a reset net. This has a hardware cost associated with it on most synthesis targets.

How to compare LocalDate instances Java 8

LocalDate ld ....;
LocalDateTime ldtime ...;

ld.isEqual(LocalDate.from(ldtime));

Delete directory with files in it?

I do not remember from where I copied this function, but it looks like it is not listed and it is working for me

function rm_rf($path) {
    if (@is_dir($path) && is_writable($path)) {
        $dp = opendir($path);
        while ($ent = readdir($dp)) {
            if ($ent == '.' || $ent == '..') {
                continue;
            }
            $file = $path . DIRECTORY_SEPARATOR . $ent;
            if (@is_dir($file)) {
                rm_rf($file);
            } elseif (is_writable($file)) {
                unlink($file);
            } else {
                echo $file . "is not writable and cannot be removed. Please fix the permission or select a new path.\n";
            }
        }
        closedir($dp);
        return rmdir($path);
    } else {
        return @unlink($path);
    }
}

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

I don't think that x[[1,3]][:,[1,3]] is hardly readable. If you want to be more clear on your intent, you can do:

a[[1,3],:][:,[1,3]]

I am not an expert in slicing but typically, if you try to slice into an array and the values are continuous, you get back a view where the stride value is changed.

e.g. In your inputs 33 and 34, although you get a 2x2 array, the stride is 4. Thus, when you index the next row, the pointer moves to the correct position in memory.

Clearly, this mechanism doesn't carry well into the case of an array of indices. Hence, numpy will have to make the copy. After all, many other matrix math function relies on size, stride and continuous memory allocation.

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

In this particular case (assuming that the Class#forName() didn't throw an exception; your code is namely continuing with running instead of throwing the exception), this SQLException means that Driver#acceptsURL() has returned false for any of the loaded drivers.

And indeed, your JDBC URL is wrong:

String url = "'jdbc:mysql://localhost:3306/mysql";

Remove the singlequote:

String url = "jdbc:mysql://localhost:3306/mysql";

See also:

Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?

Try this:

CREATE TABLE `test_table` (
`id` INT( 10 ) NOT NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT 0,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE = INNODB;

Use JAXB to create Object from XML String

Or if you want a simple one-liner:

Person person = JAXB.unmarshal(new StringReader("<?xml ..."), Person.class);

Canvas width and height in HTML5

A canvas has 2 sizes, the dimension of the pixels in the canvas (it's backingstore or drawingBuffer) and the display size. The number of pixels is set using the the canvas attributes. In HTML

<canvas width="400" height="300"></canvas>

Or in JavaScript

someCanvasElement.width = 400;
someCanvasElement.height = 300;

Separate from that are the canvas's CSS style width and height

In CSS

canvas {  /* or some other selector */
   width: 500px;
   height: 400px;
}

Or in JavaScript

canvas.style.width = "500px";
canvas.style.height = "400px";

The arguably best way to make a canvas 1x1 pixels is to ALWAYS USE CSS to choose the size then write a tiny bit of JavaScript to make the number of pixels match that size.

function resizeCanvasToDisplaySize(canvas) {
   // look up the size the canvas is being displayed
   const width = canvas.clientWidth;
   const height = canvas.clientHeight;

   // If it's resolution does not match change it
   if (canvas.width !== width || canvas.height !== height) {
     canvas.width = width;
     canvas.height = height;
     return true;
   }

   return false;
}

Why is this the best way? Because it works in most cases without having to change any code.

Here's a full window canvas:

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
body { margin: 0; }_x000D_
canvas { display: block; width: 100vw; height: 100vh; }
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

And Here's a canvas as a float in a paragraph

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width  / spacing + 1;_x000D_
  const down   = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y <= down; ++y) {_x000D_
    for (let x = 0; x <= across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
span { _x000D_
   width: 250px; _x000D_
   height: 100px; _x000D_
   float: left; _x000D_
   padding: 1em 1em 1em 0;_x000D_
   display: inline-block;_x000D_
}_x000D_
canvas {_x000D_
   width: 100%;_x000D_
   height: 100%;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim <span class="diagram"><canvas id="c"></canvas></span>_x000D_
vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
<br/><br/>_x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_
</p>
_x000D_
_x000D_
_x000D_

Here's a canvas in a sizable control panel

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}_x000D_
_x000D_
// ----- the code above related to the canvas does not change ----_x000D_
// ---- the code below is related to the slider ----_x000D_
const $ = document.querySelector.bind(document);_x000D_
const left = $(".left");_x000D_
const slider = $(".slider");_x000D_
let dragging;_x000D_
let lastX;_x000D_
let startWidth;_x000D_
_x000D_
slider.addEventListener('mousedown', e => {_x000D_
 lastX = e.pageX;_x000D_
 dragging = true;_x000D_
});_x000D_
_x000D_
window.addEventListener('mouseup', e => {_x000D_
 dragging = false;_x000D_
});_x000D_
_x000D_
window.addEventListener('mousemove', e => {_x000D_
  if (dragging) {_x000D_
    const deltaX = e.pageX - lastX;_x000D_
    left.style.width = left.clientWidth + deltaX + "px";_x000D_
    lastX = e.pageX;_x000D_
  }_x000D_
});
_x000D_
body { _x000D_
  margin: 0;_x000D_
}_x000D_
.frame {_x000D_
  display: flex;_x000D_
  align-items: space-between;_x000D_
  height: 100vh;_x000D_
}_x000D_
.left {_x000D_
  width: 70%;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
}  _x000D_
canvas {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
pre {_x000D_
  padding: 1em;_x000D_
}_x000D_
.slider {_x000D_
  width: 10px;_x000D_
  background: #000;_x000D_
}_x000D_
.right {_x000D_
  flex 1 1 auto;_x000D_
}
_x000D_
<div class="frame">_x000D_
  <div class="left">_x000D_
     <canvas id="c"></canvas>_x000D_
  </div>_x000D_
  <div class="slider">_x000D_
  _x000D_
  </div>_x000D_
  <div class="right">_x000D_
     <pre>_x000D_
* controls_x000D_
* go _x000D_
* here_x000D_
_x000D_
&lt;- drag this_x000D_
     </pre>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

here's a canvas as a background

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
body { margin: 0; }_x000D_
canvas { _x000D_
  display: block; _x000D_
  width: 100vw; _x000D_
  height: 100vh;  _x000D_
  position: fixed;_x000D_
}_x000D_
#content {_x000D_
  position: absolute;_x000D_
  margin: 0 1em;_x000D_
  font-size: xx-large;_x000D_
  font-family: sans-serif;_x000D_
  font-weight: bold;_x000D_
  text-shadow: 2px  2px 0 #FFF, _x000D_
              -2px -2px 0 #FFF,_x000D_
              -2px  2px 0 #FFF,_x000D_
               2px -2px 0 #FFF;_x000D_
}
_x000D_
<canvas id="c"></canvas>_x000D_
<div id="content">_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
</p>_x000D_
<p>_x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_
</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Because I didn't set the attributes the only thing that changed in each sample is the CSS (as far as the canvas is concerned)

Notes:

  • Don't put borders or padding on a canvas element. Computing the size to subtract from the number of dimensions of the element is troublesome

Xampp-mysql - "Table doesn't exist in engine" #1932

For me I removed whole data folder from xampp\mysql\ and pasted data folder of previous one here which solved my problem...

How do I use Assert to verify that an exception has been thrown?

if you use NUNIT, you can do something like this:

Assert.Throws<ExpectedException>(() => methodToTest());


It is also possible to store the thrown exception in order to validate it further:

ExpectedException ex = Assert.Throws<ExpectedException>(() => methodToTest());
Assert.AreEqual( "Expected message text.", ex.Message );
Assert.AreEqual( 5, ex.SomeNumber);

See: http://nunit.org/docs/2.5/exceptionAsserts.html

_DEBUG vs NDEBUG

Be consistent and it doesn't matter which one. Also if for some reason you must interop with another program or tool using a certain DEBUG identifier it's easy to do

#ifdef THEIRDEBUG
#define MYDEBUG
#endif //and vice-versa

Finding moving average from data points in Python

A moving average is a convolution, and numpy will be faster than most pure python operations. This will give you the 10 point moving average.

import numpy as np
smoothed = np.convolve(data, np.ones(10)/10)

I would also strongly suggest using the great pandas package if you are working with timeseries data. There are some nice moving average operations built in.

SVN how to resolve new tree conflicts when file is added on two branches

I just managed to wedge myself pretty thoroughly trying to follow user619330's advice above. The situation was: (1): I had added some files while working on my initial branch, branch1; (2) I created a new branch, branch2 for further development, branching it off from the trunk and then merging in my changes from branch1 (3) A co-worker had copied my mods from branch1 to his own branch, added further mods, and then merged back to the trunk; (4) I now wanted to merge the latest changes from trunk into my current working branch, branch2. This is with svn 1.6.17.

The merge had tree conflicts with the new files, and I wanted the new version from the trunk where they differed, so from a clean copy of branch2, I did an svn delete of the conflicting files, committed these branch2 changes (thus creating a temporary version of branch2 without the files in question), and then did my merge from the trunk. I did this because I wanted the history to match the trunk version so that I wouldn't have more problems later when trying to merge back to trunk. Merge went fine, I got the trunk version of the files, svn st shows all ok, and then I hit more tree conflicts while trying to commit the changes, between the delete I had done earlier and the add from the merge. Did an svn resolve of the conflicts in favor of my working copy (which now had the trunk version of the files), and got it to commit. All should be good, right?

Well, no. An update of another copy of branch2 resulted in the old version of the files (pre-trunk merge). So now I have two different working copies of branch2, supposedly updated to the same version, with two different versions of the files, and both insisting that they are fully up to date! Checking out a clean copy of branch2 resulted in the old (pre-trunk) version of the files. I manually update these to the trunk version and commit the changes, go back to my first working copy (from which I had submitted the trunk changes originally), try to update it, and now get a checksum error on the files in question. Blow the directory in question away, get a new version via update, and finally I have what should be a good version of branch2 with the trunk changes. I hope. Caveat developer.

Check if a Windows service exists and delete in PowerShell

I used the "-ErrorAction SilentlyContinue" solution but then later ran into the problem that it leaves an ErrorRecord behind. So here's another solution to just checking if the Service exists using "Get-Service".

# Determines if a Service exists with a name as defined in $ServiceName.
# Returns a boolean $True or $False.
Function ServiceExists([string] $ServiceName) {
    [bool] $Return = $False
    # If you use just "Get-Service $ServiceName", it will return an error if 
    # the service didn't exist.  Trick Get-Service to return an array of 
    # Services, but only if the name exactly matches the $ServiceName.  
    # This way you can test if the array is emply.
    if ( Get-Service "$ServiceName*" -Include $ServiceName ) {
        $Return = $True
    }
    Return $Return
}

[bool] $thisServiceExists = ServiceExists "A Service Name"
$thisServiceExists 

But ravikanth has the best solution since the Get-WmiObject will not throw an error if the Service didn't exist. So I settled on using:

Function ServiceExists([string] $ServiceName) {
    [bool] $Return = $False
    if ( Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'" ) {
        $Return = $True
    }
    Return $Return
}

So to offer a more complete solution:

# Deletes a Service with a name as defined in $ServiceName.
# Returns a boolean $True or $False.  $True if the Service didn't exist or was 
# successfully deleted after execution.
Function DeleteService([string] $ServiceName) {
    [bool] $Return = $False
    $Service = Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'" 
    if ( $Service ) {
        $Service.Delete()
        if ( -Not ( ServiceExists $ServiceName ) ) {
            $Return = $True
        }
    } else {
        $Return = $True
    }
    Return $Return
}

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a little tricky, you might want to check out this wrap function.

What does "TypeError 'xxx' object is not callable" means?

The exception is raised when you try to call not callable object. Callable objects are (functions, methods, objects with __call__)

>>> f = 1
>>> callable(f)
False
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Uncaught TypeError: Cannot read property 'length' of undefined

You are accessing an object that is not defined.

The solution is check for null or undefined (to see whether the object exists) and only then iterate.

Highlight the difference between two strings in PHP

If you want a robust library, Text_Diff (a PEAR package) looks to be pretty good. It has some pretty cool features.

How do I convert a number to a letter in Java?

for(int i=0;i<ar.length();i++) {
            char ch = ar.charAt(i);
                    System.out.println((char)(ch+16));;
        }

How do I allow HTTPS for Apache on localhost?

Running Apache on Windows 10 here. I couldn't get Chrome to trust the certificate made in the top answer by Simon. What I ended up doing was using PowerShell to generate a self signed certificate.

Step 1 - Generate Self-Signed certificate

In PowerShell
New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My" 1

Step 2 - Configure and Export Certificate

Type Certificate into the Windows search bar, click the Manage Computer Certificates control panel item that is suggested.

From the Certificate Management program that comes up (certlm), you should now see a localhost key under Personal >> Certificates.

I copied this certificate into Trusted Root Certification Authorities. I'll be honest in that I'm not sure if that's necessary.

Selecting the newly copied certificate, double click on it (the localhost certificate). From the Certificate modal, click the Details tab, then the Copy to File... button.

This will bring up and Export Wizard, I chose to export the private key, click next. I also chose to Export all extended properties (again, I'm not certain if that was necessary). I chose to use a simple password (pass) and the default encryption. Choose a folder to export to and name the file. You can always move and rename the file if necessary. For simplicity's sake let's copy it to your conf folder under your Apache installation (In my case: C:\apache\conf) and name the file myCert (the resulting file will be a .pfx file)

Step 3 - Convert .pfx file for use with Apache

From here I basically followed the tutorial here, but I'll add instructions here (tweaked for our settings) in case that site goes down.

Open your Command Prompt in the /apache/conf/ folder
Run the following commands: Note: This assumes you have openssl.exe in the bin folder in the apache root folder (this should be standard/default)

..\bin\openssl pkcs12 -in myCert.pfx -nocerts -out privateKey.pem

This will prompt you for a password, enter what you input for Step 2 when you exported the .pfx file. In my case, this is pass. I entered the same password for the PEM phrase and again to verify. This will create a new file called privateKey.pem in your conf folder.

Then, run

..\bin\openssl rsa -in privateKey.pem -out private.pem

Again you will be prompted for a password (Enter pass phrase for privateKey.pem:), use the password you set for privateKey.pem. (In my case, pass)
You should see a message that says writing RSA key and a new file called private.pem in your conf/ folder. This will be your SSLCertificateKeyFile.

Now to generate the corresponding Server Certificate. Run:

..\bin\openssl pkcs12 -in myCert.pfx -clcerts -nokeys -out EntrustCert.pem

This will prompt you for a password, enter what you input for Step 2 when you exported the .pfx file. Enter it and you will now have a file called EntrustCert.pem in your conf folder. This is your SSLCertificateFile

Step 4 - Configure httpd.conf

Use the new files created as you server's key and certificate. Be sure to change your document root to where your files are!

ServerName localhost:80
Protocols h2 h2c http/1.1
<Directory />
    Options FollowSymLinks
    AllowOverride All
</Directory>

<VirtualHost _default_:443>
  ServerName localhost:443
  DocumentRoot ${SRVROOT}/htdocs/MYSITE
  SSLEngine on
  SSLCertificateFile "${SRVROOT}/conf/EntrustCert.pem"
  SSLCertificateKeyFile "${SRVROOT}/conf/private.pem"
</VirtualHost>

Also in httpd.conf:

  • Make sure LoadModule ssl_module modules/mod_ssl.so is uncommented (no # in front)
  • Uncomment LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
  • Uncomment LoadModule http2_module modules/mod_http2.so
  • Uncomment Include conf/extra/httpd-ssl.conf (NOTE: Ensure that's where the file is!)

I also have curl and open ssl libraries included:

# load curl and open ssl libraries
LoadFile "C:\php\libeay32.dll"
LoadFile "C:\php\ssleay32.dll"
LoadFile "C:\php\libssh2.dll"

These modules shouldn't be necessary, but I'll note that I have them enabled:
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule filter_module modules/mod_filter.so
LoadModule deflate_module modules/mod_deflate.so

Step 5 - Config httpd-ssl.conf

In the extra/ folder in the conf/ folder you should see a file called httpd-ssl.conf.

5a. Change the DocumentRoot - Change the DocumentRoot from the default to the directory where your files are.

5b. Change the ServerName - Change the ServerName from the default (something like www.example.com:443) to localhost:443

5c. Change the SSLCertificateFile
Change the SSLCertificateFile from the default (${SRVROOT}/conf/server.crt) to ${SRVROOT}/conf/EntrustCert.pem

5c. Change the SSLCertificateKeyFile
Change the SSLCertificateKeyFile from the default (${SRVROOT}/conf/server.key) to ${SRVROOT}/conf/private.pem

All together, in the <VirtualHost _default_:443> tag.

#   General setup for the virtual host
DocumentRoot "${SRVROOT}/htdocs/MYSITE"
ServerName localhost:443
ServerAdmin [email protected]
ErrorLog "${SRVROOT}/logs/error.log"
TransferLog "${SRVROOT}/logs/access.log"

#   SSL Engine Switch:
#   Enable/Disable SSL for this virtual host.
SSLEngine on

#   Server Certificate:
#   Point SSLCertificateFile at a PEM encoded certificate.  If
#   the certificate is encrypted, then you will be prompted for a
#   pass phrase.  Note that a kill -HUP will prompt again.  Keep
#   in mind that if you have both an RSA and a DSA certificate you
#   can configure both in parallel (to also allow the use of DSA
#   ciphers, etc.)
#   Some ECC cipher suites (http://www.ietf.org/rfc/rfc4492.txt)
#   require an ECC certificate which can also be configured in
#   parallel.
SSLCertificateFile "${SRVROOT}/conf/EntrustCert.pem"
#SSLCertificateFile "${SRVROOT}/conf/server-dsa.crt"
#SSLCertificateFile "${SRVROOT}/conf/server-ecc.crt"

#   Server Private Key:
#   If the key is not combined with the certificate, use this
#   directive to point at the key file.  Keep in mind that if
#   you've both a RSA and a DSA private key you can configure
#   both in parallel (to also allow the use of DSA ciphers, etc.)
#   ECC keys, when in use, can also be configured in parallel
SSLCertificateKeyFile "${SRVROOT}/conf/private.pem"
#SSLCertificateKeyFile "${SRVROOT}/conf/server-dsa.key"
#SSLCertificateKeyFile "${SRVROOT}/conf/server-ecc.key"

Restart Apache

After making these changes you should be able to restart Apache and navigate to https://localhost without a security warning and a little padlock!

Secured localhost

I hope this helps someone!

Sources:
1.) Auri Rahimzadeh's answer on creating a self-signed certificate
2.) Entrust Datacard - How do I convert a .pfx to be used with an Apache server?

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

Initialize 2D array

Shorter way is do it as follows:

private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

Axios having CORS issue

your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

Statement interface Doc

SUMMARY: void setFetchSize(int rows) Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed.

Read this ebook J2EE and beyond By Art Taylor

Python: OSError: [Errno 2] No such file or directory: ''

I had this error because I was providing a string of arguments to subprocess.call instead of an array of arguments. To prevent this, use shlex.split:

import shlex, subprocess
command_line = "ls -a"
args = shlex.split(command_line)
p = subprocess.Popen(args)