Programs & Examples On #Servicepoint

The .NET ServicePoint class is used to implement web service end-points.

bypass invalid SSL certificate in .net core

In .NetCore, you can add the following code snippet at services configure method , I added a check to make sure only that we by pass the SSL certificate in development environment only

services.AddHttpClient("HttpClientName", client => {
// code to configure headers etc..
}).ConfigurePrimaryHttpMessageHandler(() => {
                  var handler = new HttpClientHandler();
                  if (hostingEnvironment.IsDevelopment())
                  {
                      handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
                  }
                  return handler;
              });

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

move this line: ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Before this line: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

Original post: KB4344167 security update breaks TLS Code

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

For .Net 4 use:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;

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

After six days I find the answer which make me crazy! The answer is disable proxy at web.config file:

<system.net>
  <defaultProxy> 
    <proxy usesystemdefault="False"/> 
  </defaultProxy>
</system.net>

Default SecurityProtocol in .NET 4.5

I'm running under .NET 4.5.2, and I wasn't happy with any of these answers. As I'm talking to a system which supports TLS 1.2, and seeing as SSL3, TLS 1.0, and TLS 1.1 are all broken and unsafe for use, I don't want to enable these protocols. Under .NET 4.5.2, the SSL3 and TLS 1.0 protocols are both enabled by default, which I can see in code by inspecting ServicePointManager.SecurityProtocol. Under .NET 4.7, there's the new SystemDefault protocol mode which explicitly hands over selection of the protocol to the OS, where I believe relying on registry or other system configuration settings would be appropriate. That doesn't seem to be supported under .NET 4.5.2 however. In the interests of writing forwards-compatible code, that will keep making the right decisions even when TLS 1.2 is inevitably broken in the future, or when I upgrade to .NET 4.7+ and hand over more responsibility for selecting an appropriate protocol to the OS, I adopted the following code:

SecurityProtocolType securityProtocols = ServicePointManager.SecurityProtocol;
if (securityProtocols.HasFlag(SecurityProtocolType.Ssl3) || securityProtocols.HasFlag(SecurityProtocolType.Tls) || securityProtocols.HasFlag(SecurityProtocolType.Tls11))
{
    securityProtocols &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11);
    if (securityProtocols == 0)
    {
        securityProtocols |= SecurityProtocolType.Tls12;
    }
    ServicePointManager.SecurityProtocol = securityProtocols;
}

This code will detect when a known insecure protocol is enabled, and in this case, we'll remove these insecure protocols. If no other explicit protocols remain, we'll then force enable TLS 1.2, as the only known secure protocol supported by .NET at this point in time. This code is forwards compatible, as it will take into consideration new protocol types it doesn't know about being added in the future, and it will also play nice with the new SystemDefault state in .NET 4.7, meaning I won't have to re-visit this code in the future. I'd strongly recommend adopting an approach like this, rather than hard-coding any particular security protocol states unconditionally, otherwise you'll have to recompile and replace your client with a new version in order to upgrade to a new security protocol when TLS 1.2 is inevitably broken, or more likely you'll have to leave the existing insecure protocols turned on for years on your server, making your organisation a target for attacks.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

After messing with this for days, my final fix for our issues required two things;

1) We added this line of code to all of our .Net libraries that make out bound api calls to other vendors that had also disabled their SSL v3.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // (.Net 4 and below)

2) This is the final and FULL registry changes you will need when you are running ASP.Net 4.0 sites and will need to be slightly changed after you upgrade to ASP.Net 4.5.

After we rebooted the servers - all problems went away after this.

Windows Registry Editor Version 5.00

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

@Eddie Loeffen's answer seems to be the most popular answer to this question, but it has some bad long term effects. If you review the documentation page for System.Net.ServicePointManager.SecurityProtocol here the remarks section implies that the negotiation phase should just address this (and forcing the protocol is bad practice because in the future, TLS 1.2 will be compromised as well). However, we wouldn't be looking for this answer if it did.

Researching, it appears that the ALPN negotiation protocol is required to get to TLS1.2 in the negotiation phase. We took that as our starting point and tried newer versions of the .Net framework to see where support starts. We found that .Net 4.5.2 does not support negotiation to TLS 1.2, but .Net 4.6 does.

So, even though forcing TLS1.2 will get the job done now, I recommend that you upgrade to .Net 4.6 instead. Since this is a PCI DSS issue for June 2016, the window is short, but the new framework is a better answer.

UPDATE: Working from the comments, I built this:

ServicePointManager.SecurityProtocol = 0;    
foreach (SecurityProtocolType protocol in SecurityProtocolType.GetValues(typeof(SecurityProtocolType)))
    {
        switch (protocol)
        {
            case SecurityProtocolType.Ssl3:
            case SecurityProtocolType.Tls:
            case SecurityProtocolType.Tls11:
                break;
            default:
                ServicePointManager.SecurityProtocol |= protocol;
            break;
        }
    }

In order to validate the concept, I or'd together SSL3 and TLS1.2 and ran the code targeting a server that supports only TLS 1.0 and TLS 1.2 (1.1 is disabled). With the or'd protocols, it seems to connect fine. If I change to SSL3 and TLS 1.1, that failed to connect. My validation uses HttpWebRequest from System.Net and just calls GetResponse(). For instance, I tried this and failed:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11;
        request.GetResponse();

while this worked:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
        request.GetResponse();

This has an advantage over forcing TLS 1.2 in that, if the .Net framework is upgraded so that there are more entries in the Enum, they will be supported by the code as is. It has a disadvantage over just using .Net 4.6 in that 4.6 uses ALPN and should support new protocols if no restriction is specified.

Edit 4/29/2019 - Microsoft published this article last October. It has a pretty good synopsis of their recommendation of how this should be done in the various versions of .net framework.

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

https://support.microsoft.com/en-us/kb/938397

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:

http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

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

I've been having the same issue for days now with an integration that also just "used to work before".

Out of sheer depression, I just tried

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

This solved it for me..even though the integration strictly only makes use of SSLv3.

I came to the realization that something if off since Fiddler reported saying that there is an "empty TLS negotiation cipher" or something of the like.

Hopefully it works!

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

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

netstat -ano | findstr <your port number>

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

netsh interface ipv4 show excludedportrange protocol=tcp

Deciding between HttpClient and WebClient

Firstly, I am not an authority on WebClient vs. HttpClient, specifically. Secondly, from your comments above, it seems to suggest that WebClient is Sync ONLY whereas HttpClient is both.

I did a quick performance test to find how WebClient (Sync calls), HttpClient (Sync and Async) perform. and here are the results.

I see that as a huge difference when thinking for future, i.e. long running processes, responsive GUI, etc. (add to the benefit you suggest by framework 4.5 - which in my actual experience is hugely faster on IIS)

How to simulate POST request?

Dont forget to add user agent since some server will block request if there's no server agent..(you would get Forbidden resource response) example :

curl -X POST -A 'Mozilla/5.0 (X11; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0' -d "field=acaca&name=afadxx" https://example.com

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

Multidimensional Array [][] vs [,]

In the first instance you are trying to create what is called a jagged array.

double[][] ServicePoint = new double[10][9].

The above statement would have worked if it was defined like below.

double[][] ServicePoint = new double[10][]

what this means is you are creating an array of size 10 ,that can store 10 differently sized arrays inside it.In simple terms an Array of arrays.see the below image,which signifies a jagged array.

enter image description here

http://msdn.microsoft.com/en-us/library/2s05feca(v=vs.80).aspx

The second one is basically a two dimensional array and the syntax is correct and acceptable.

  double[,] ServicePoint = new double[10,9];//<-ok (2)

And to access or modify a two dimensional array you have to pass both the dimensions,but in your case you are passing just a single dimension,thats why the error

Correct usage would be

ServicePoint[0][2] ,Refers to an item on the first row ,third column.

Pictorial rep of your two dimensional array

enter image description here

How to ignore the certificate check when ssl

This worked for me:

System.Net.ServicePointManager.ServerCertificateValidationCallback +=
delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                        System.Security.Cryptography.X509Certificates.X509Chain chain,
                        System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
        return true; // **** Always accept
    };

Snippet from here: http://www.west-wind.com/weblog/posts/2011/Feb/11/HttpWebRequest-and-Ignoring-SSL-Certificate-Errors

Powershell v3 Invoke-WebRequest HTTPS error

An alternative implementation in pure (without Add-Type of source):

#requires -Version 5
#requires -PSEdition Desktop

class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
    [bool] CheckValidationResult([System.Net.ServicePoint] $a,
                                 [System.Security.Cryptography.X509Certificates.X509Certificate] $b,
                                 [System.Net.WebRequest] $c,
                                 [int] $d) {
        return $true
    }
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()

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

After many long hours with this same issue I found that the ASP.NET account the client service was running under didn't have access to the certificate. I fixed it by going into the IIS Application Pool that the web app runs under, going into Advanced Settings, and changing the Identity to the LocalSystem account from NetworkService.

A better solution is to get the certificate working with the default NetworkService account but this works for quick functional testing.

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

I had a similar issue. In my case the service would work fine on the developer machine but fail when on a QA machine. It turned out that on the QA machine the application wasn't being run as an administrator and didn't have permission to register the endpoint:

HTTP could not register URL http://+:12345/Foo.svc/]. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).

Refer here for how to get it working without being an admin user: https://stackoverflow.com/a/885765/38258

Could not establish secure channel for SSL/TLS with authority '*'

Yes an Untrusted certificate can cause this. Look at the certificate path for the webservice by opening the websservice in a browser and use the browser tools to look at the certificate path. You may need to install one or more intermediate certificates onto the computer calling the webservice. In the browser you may see "Certificate errors" with an option to "Install Certificate" when you investigate further - this could be the certificate you missing.

My particular problem was a Geotrust Geotrust DV SSL CA intermediate certificate missing following an upgrade to their root server in July 2010 https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422

(2020 update deadlink preserved here: https://web.archive.org/web/20140724085537/https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422 )

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

I had this issue happening often. I found SQL Server Agent service was not running. Once I started the service manually, it got fixed. Double check if the service is running or not:

  1. Run prompt, type services.msc and hit enter
  2. Find the service name - SQL Server Agent(Instance Name)

If SQL Server Agent is not running, double-click the service to open properties window. Then click on Start button. Hope it will help someone.

How can I send emails through SSL SMTP with the .NET Framework?

It works with System.Web.Mail (which is marked as obsolete):

private const string SMTP_SERVER        = "http://schemas.microsoft.com/cdo/configuration/smtpserver";
private const string SMTP_SERVER_PORT   = "http://schemas.microsoft.com/cdo/configuration/smtpserverport";
private const string SEND_USING         = "http://schemas.microsoft.com/cdo/configuration/sendusing";
private const string SMTP_USE_SSL       = "http://schemas.microsoft.com/cdo/configuration/smtpusessl";
private const string SMTP_AUTHENTICATE  = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate";
private const string SEND_USERNAME      = "http://schemas.microsoft.com/cdo/configuration/sendusername";
private const string SEND_PASSWORD      = "http://schemas.microsoft.com/cdo/configuration/sendpassword";

System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();

mail.Fields[SMTP_SERVER] = "tempurl.org";
mail.Fields[SMTP_SERVER_PORT] = 465;
mail.Fields[SEND_USING] = 2;
mail.Fields[SMTP_USE_SSL] = true;
mail.Fields[SMTP_AUTHENTICATE] = 1;
mail.Fields[SEND_USERNAME] = "username";
mail.Fields[SEND_PASSWORD] = "password";

System.Web.Mail.SmtpMail.Send(mail);

What is your point of view regarding obsolete namespace usage?

How to move text up using CSS when nothing is working

footerText {
    line-height: 20px;
}

you don't need to start playing with position or even layout of other elements... use this simple solution

mongodb: insert if not exists

Sounds like you want to do an "upsert". MongoDB has built-in support for this. Pass an extra parameter to your update() call: {upsert:true}. For example:

key = {'key':'value'}
data = {'key2':'value2', 'key3':'value3'};
coll.update(key, data, upsert=True); #In python upsert must be passed as a keyword argument

This replaces your if-find-else-update block entirely. It will insert if the key doesn't exist and will update if it does.

Before:

{"key":"value", "key2":"Ohai."}

After:

{"key":"value", "key2":"value2", "key3":"value3"}

You can also specify what data you want to write:

data = {"$set":{"key2":"value2"}}

Now your selected document will update the value of "key2" only and leave everything else untouched.

Delete files older than 10 days using shell script in Unix

If you can afford working via the file data, you can do

find -mmin +14400 -delete

How can I switch my signed in user in Visual Studio 2013?

For VS 2013, community edition, you have to delete the registry keys found under: hkey_current_user\software\Microsoft\VSCommon\12.0\clientservices\tokenstorge\visualstudio\ideuser

Replace Multiple String Elements in C#

Another option using linq is

[TestMethod]
public void Test()
{
  var input = "it's worth a lot of money, if you can find a buyer.";
  var expected = "its worth a lot of money if you can find a buyer";
  var removeList = new string[] { ".", ",", "'" };
  var result = input;

  removeList.ToList().ForEach(o => result = result.Replace(o, string.Empty));

  Assert.AreEqual(expected, result);
}

EXCEL VBA Check if entry is empty or not 'space'

Most terse version I can think of

Len(Trim(TextBox1.Value)) = 0

If you need to do this multiple times, wrap it in a function

Public Function HasContent(text_box as Object) as Boolean
    HasContent = (Len(Trim(text_box.Value)) > 0)
End Function

Usage

If HasContent(TextBox1) Then
    ' ...

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

This is not just a Chrome/Safari issue, I experienced a quite similar behavior with Firefox 18.0.1. The funny part is that this does not happen on MSIE! The problem here is the first mouseup event that forces to unselect the input content, so just ignore the first occurence.

$(':text').focus(function(){
    $(this).one('mouseup', function(event){
        event.preventDefault();
    }).select();
});

The timeOut approach causes a strange behavior, and blocking every mouseup event you can not remove the selection clicking again on the input element.

SyntaxError: Cannot use import statement outside a module

In Case your running nodemon for the node version 12 ,use this command. server.js is the "main" inside package.json file ,replace it with relevant file inside your package.json file

nodemon --experimental-modules server.js

Remove Datepicker Function dynamically

Just bind the datepicker to a class rather than binding it to the id . Remove the class when you want to revoke the datepicker...

$("#ddlSearchType").change(function () { 
  if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date")                   { 
    $("#txtSearch").addClass("mydate");
    $(".mydate").datepicker()
  } else { 
    $("#txtSearch").removeClass("mydate");
  } 
}); 

How to change Android usb connect mode to charge only?

Nothing worked until I went this way: Settings>Developer options>Default USB configuration now you can choose your default USB connection purpose.

Determine what attributes were changed in Rails after_save callback?

For those who want to know the changes just made in an after_save callback:

Rails 5.1 and greater

model.saved_changes

Rails < 5.1

model.previous_changes

Also see: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-previous_changes

Listen to port via a Java socket

You need to use a ServerSocket. You can find an explanation here.

When to encode space to plus (+) or %20?

What's the difference: See other answers.

When use + instead of %20? Use + if, for some reason, you want to make the URL query string (?.....) or hash fragment (#....) more readable. Example: You can actually read this:

https://www.google.se/#q=google+doesn%27t+encode+:+and+uses+%2B+instead+of+spaces (%2B = +)

But the following is a lot harder to read: (at least to me)

https://www.google.se/#q=google%20doesn%27t%20oops%20:%20%20this%20text%20%2B%20is%20different%20spaces

I would think + is unlikely to break anything, since Google uses + (see the 1st link above) and they've probably thought about this. I'm going to use + myself just because readable + Google thinks it's OK.

How to Find the Default Charset/Encoding in Java?

I have set the vm argument in WAS server as -Dfile.encoding=UTF-8 to change the servers' default character set.

How to Automatically Start a Download in PHP?

Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

How to Disable GUI Button in Java

Rather than using booleans, why not just set the button to false when its clicked, so you do that in your actionPerformed method. Its more efficient..

if (command.equals("w"))
{
    FileConverter fc = new FileConverter();
    btnConvertDocuments.setEnabled(false);
}

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

starting file download with JavaScript

I'd suggest window.open() to open a popup window. If it's a download, there will be no window and you will get your file. If there is a 404 or something, the user will see it in a new window (hence, their work will not be bothered, but they will still get an error message).

How to get first two characters of a string in oracle query?

Easy:

SELECT SUBSTR(OrderNo, 1, 2) FROM shipment;

What is the default font of Sublime Text?

On my system (Windows 8.1), Sublime 2 shows default font "Consolas". You can find yours by following this procedure:

  1. go to View menu and select Show Console
  2. Then enter this command: view.settings().get('font_face')

You will find your default font.

Convert JS Object to form data

Recursively

_x000D_
_x000D_
const toFormData = (f => f(f))(h => f => f(x => h(h)(f)(x)))(f => fd => pk => d => {_x000D_
  if (d instanceof Object) {_x000D_
    Object.keys(d).forEach(k => {_x000D_
      const v = d[k]_x000D_
      if (pk) k = `${pk}[${k}]`_x000D_
      if (v instanceof Object && !(v instanceof Date) && !(v instanceof File)) {_x000D_
        return f(fd)(k)(v)_x000D_
      } else {_x000D_
        fd.append(k, v)_x000D_
      }_x000D_
    })_x000D_
  }_x000D_
  return fd_x000D_
})(new FormData())()_x000D_
_x000D_
let data = {_x000D_
  name: 'John',_x000D_
  age: 30,_x000D_
  colors: ['red', 'green', 'blue'],_x000D_
  children: [_x000D_
    { name: 'Max', age: 3 },_x000D_
    { name: 'Madonna', age: 10 }_x000D_
  ]_x000D_
}_x000D_
console.log('data', data)_x000D_
document.getElementById("data").insertAdjacentHTML('beforeend', JSON.stringify(data))_x000D_
_x000D_
let formData = toFormData(data)_x000D_
_x000D_
for (let key of formData.keys()) {_x000D_
  console.log(key, formData.getAll(key).join(','))_x000D_
  document.getElementById("item").insertAdjacentHTML('beforeend', `<li>${key} = ${formData.getAll(key).join(',')}</li>`)_x000D_
}
_x000D_
<p id="data"></p>_x000D_
<ul id="item"></ul>
_x000D_
_x000D_
_x000D_

Spring Resttemplate exception handling

Here is my POST method with HTTPS which returns a response body for any type of bad responses.

public String postHTTPSRequest(String url,String requestJson)
{
    //SSL Context
    CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    //Initiate REST Template
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    //Send the Request and get the response.
    HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
    ResponseEntity<String> response;
    String stringResponse = "";
    try {
        response = restTemplate.postForEntity(url, entity, String.class);
        stringResponse = response.getBody();
    }
    catch (HttpClientErrorException e)
    {
        stringResponse = e.getResponseBodyAsString();
    }
    return stringResponse;
}

How to make Unicode charset in cmd.exe by default?

Reg file

Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Console]
"CodePage"=dword:fde9

Command Prompt

REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 0xfde9

PowerShell

sp -t d HKCU:\Console CodePage 0xfde9

Cygwin

regtool set /user/Console/CodePage 0xfde9

Oracle find a constraint

maybe this can help..

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

BigDecimal setScale and round

There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:

http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html

Keep overflow div scrolled to bottom unless user scrolls up

I managed to get this working. The trick is to calculate: (a) current div user scroll position and (b) div scroll height, both BEFORE appending the new element.

If a === b, we know the user is at the bottom before appending the new element.

    let div = document.querySelector('div.scrollableBox');

    let span = document.createElement('span');
    span.textContent = 'Hello';

    let divCurrentUserScrollPosition = div.scrollTop + div.offsetHeight;
    let divScrollHeight = div.scrollHeight;

    // We have the current scroll positions saved in
    // variables, so now we can append the new element.
    div.append(span);

    
    if ((divScrollHeight === divCurrentUserScrollPosition)) {
        // Scroll to bottom of div
        div.scrollTo({ left: 0, top: div.scrollHeight });
    }

New to MongoDB Can not run command mongo

Specify the database path explicitly like so, and see if that resolves the issue.

mongod --dbpath data/db

How can I remove leading and trailing quotes in SQL Server?

you could replace the quotes with an empty string...

SELECT AllRemoved = REPLACE(CAST(MyColumn AS varchar(max)), '"', ''),
       LeadingAndTrailingRemoved = CASE 
           WHEN MyTest like '"%"' THEN SUBSTRING(Mytest, 2, LEN(CAST(MyTest AS nvarchar(max)))-2)
           ELSE MyTest
           END  
FROM   MyTable

Convert string to title case with JavaScript

Robust Functional programming way to do Title Case Function

Exaplin Version

function toTitleCase(input){
    let output = input
        .split(' ')  // 'HOw aRe YOU' => ['HOw' 'aRe' 'YOU']
        .map((letter) => {
            let firstLetter = letter[0].toUpperCase() // H , a , Y  => H , A , Y
            let restLetters = letter.substring(1).toLowerCase() // Ow, Re, OU => ow, re, ou
            return firstLetter + restLetters // conbine together
        })
        .join(' ') //['How' 'Are' 'You'] => 'How Are You'
    return output
}

Implementation version

function toTitleCase(input){
    return input
            .split(' ')
            .map(i => i[0].toUpperCase() + i.substring(1).toLowerCase())
            .join(' ') 
}

toTitleCase('HoW ARe yoU') // reuturn 'How Are You'

Why use pip over easy_install?

As an addition to fuzzyman's reply:

pip won't install binary packages and isn't well tested on Windows.

As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.

Here is a trick on Windows:

  • you can use easy_install <package> to install binary packages to avoid building a binary

  • you can use pip uninstall <package> even if you used easy_install.

This is just a work-around that works for me on windows. Actually I always use pip if no binaries are involved.

See the current pip doku: http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install

I will ask on the mailing list what is planned for that.

Here is the latest update:

The new supported way to install binaries is going to be wheel! It is not yet in the standard, but almost. Current version is still an alpha: 1.0.0a1

https://pypi.python.org/pypi/wheel

http://wheel.readthedocs.org/en/latest/

I will test wheel by creating an OS X installer for PySide using wheel instead of eggs. Will get back and report about this.

cheers - Chris

A quick update:

The transition to wheel is almost over. Most packages are supporting wheel.

I promised to build wheels for PySide, and I did that last summer. Works great!

HINT: A few developers failed so far to support the wheel format, simply because they forget to replace distutils by setuptools. Often, it is easy to convert such packages by replacing this single word in setup.py.

PHP - Get bool to echo false when false

This will print out boolean value as it is, instead of 1/0.

    $bool = false;

    echo json_encode($bool);   //false

Why does AngularJS include an empty option in select?

A grind solution with jQuery when you haven't the control of the options

html:

<select id="selector" ng-select="selector" data-ng-init=init() >
...
</select>

js:

$scope.init = function () {
    jQuery('#selector option:first').remove();
    $scope.selector=jQuery('#selector option:first').val();
}

android edittext onchange listener

In Kotlin Android EditText listener is set using,

   val searchTo : EditText = findViewById(R.id.searchTo)
   searchTo.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable) {

        // you can call or do what you want with your EditText here

        // yourEditText...
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

Illegal string offset Warning PHP

In my case i change mysql_fetch_assoc to mysql_fetch_array and solve. It takes 3 days to solve :-( and the other versions of my proyect run with fetch assoc.

How to avoid "StaleElementReferenceException" in Selenium?

Usually StaleElementReferenceException when element we try to access has appeared but other elements may affect the position of element we are intrested in hence when we try to click or getText or try to do some action on WebElement we get exception which usually says element not attached with DOM.

Solution I tried is as follows:

 protected void clickOnElement(By by) {
        try {
            waitForElementToBeClickableBy(by).click();
        } catch (StaleElementReferenceException e) {
            for (int attempts = 1; attempts < 100; attempts++) {
                try {
                    waitFor(500);
                    logger.info("Stale element found retrying:" + attempts);
                    waitForElementToBeClickableBy(by).click();
                    break;
                } catch (StaleElementReferenceException e1) {
                    logger.info("Stale element found retrying:" + attempts);
                }
            }
        }

protected WebElement waitForElementToBeClickableBy(By by) {
        WebDriverWait wait = new WebDriverWait(getDriver(), 10);
        return wait.until(ExpectedConditions.elementToBeClickable(by));
    }

In above code I first try to wait and then click on element if exception occurs then I catch it and try to loop it as there is a possibility that still all elements may not be loaded and again exception can occur.

Convert Text to Uppercase while typing in Text box

There is a specific property for this. It is called CharacterCasing and you could set it to Upper

  TextBox1.CharacterCasing = CharacterCasing.Upper;

In ASP.NET you could try to add this to your textbox style

  style="text-transform:uppercase;"

You could find an example here: http://www.w3schools.com/cssref/pr_text_text-transform.asp

Is there a way to run Python on Android?

Not at the moment and you would be lucky to get Jython to work soon. If you're planning to start your development now you would be better off with just sticking to Java for now on.

How to create PDFs in an Android app?

If you are developing for devices with API level 19 or higher you can use the built in PrintedPdfDocument: http://developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html

// open a new document
PrintedPdfDocument document = new PrintedPdfDocument(context,
     printAttributes);

// start a page
Page page = document.startPage(0);

// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());

// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());

//close the document
document.close();

How to determine the number of days in a month in SQL Server?

DECLARE @date DATETIME = GETDATE(); --or '12/1/2018' (month/day/year) 
SELECT DAY(EOMONTH ( @date )) AS 'This Month'; 
SELECT DAY(EOMONTH ( @date, 1 )) AS 'Next Month';

result: This Month 31

Next Month 30

How to find reason of failed Build without any error or warning

If nuget package 'Microsoft.Net.Compilers' is installed, make sure that it suits version of your Visual Studio (Build Tools version).

Versions 1.x mean C# 6.0 (Visual Studio 2015 and updates). For instance, 1.3.2

So don't upgrade to version above 1.x if you use VS2015

https://stackoverflow.com/a/44397905/3862615

Clear text area

I agree with @Jakub Arnold's answer. The problem should be somewhere else. I could not figure out the problem but found a work around.

Wrap your concerned element with a parent element and cause its html to create a new element with the id you are concerned with. See below

<div id="theParent">
    <div id="vinanghinguyen_images_bbocde"></div>
</div>

'onSelect'    : function(event,ID,fileObj) {
 $("#theParent").html("<div id='vinanghinguyen_images_bbocde'></div>");
 $("#vinanghinguyen_result").hide();
 $(".uploadifyQueue").height(315);
}

How can I reset eclipse to default settings?

Yes, Eclipse can be a pain, as almost any IDE can. Please remain factual, however.

Switching to a new workspace should help you. Eclipse has almost no settings that are stored outside your workspace.

Enum "Inheritance"

Enums are not actual classes, even if they look like it. Internally, they are treated just like their underlying type (by default Int32). Therefore, you can only do this by "copying" single values from one enum to another and casting them to their integer number to compare them for equality.

How to set up subdomains on IIS 7

As DotNetMensch said but you DO NOT need to add another site in IIS as this can also cause further problems and make things more complicated because you then have a website within a website so the file paths, masterpage paths and web.config paths may need changing. You just need to edit teh bindings of the existing site and add the new subdomain there.

So:

  1. Add sub-domain to DNS records. My host (RackSpace) uses a web portal to do this so you just log in and go to Network->Domains(DNS)->Actions->Create Zone, and enter your subdomain as mysubdomain.domain.com etc, leave the other settings as default

  2. Go to your domain in IIS, right-click->Edit Bindings->Add, and add your new subdomain leaving everything else the same e.g. mysubdomain.domain.com

You may need to wait 5-10 mins for the DNS records to update but that's all you need.

Locking pattern for proper use of .NET MemoryCache

It is difficult to choose which one is better; lock or ReaderWriterLockSlim. You need real world statistics of read and write numbers and ratios etc.

But if you believe using "lock" is the correct way. Then here is a different solution for different needs. I also include the Allan Xu's solution in the code. Because both can be needed for different needs.

Here are the requirements, driving me to this solution:

  1. You don't want to or cannot supply the 'GetData' function for some reason. Perhaps the 'GetData' function is located in some other class with a heavy constructor and you do not want to even create an instance till ensuring it is unescapable.
  2. You need to access the same cached data from different locations/tiers of the application. And those different locations don't have access to same locker object.
  3. You don't have a constant cache key. For example; need of caching some data with the sessionId cache key.

Code:

using System;
using System.Runtime.Caching;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace CachePoc
{
    class Program
    {
        static object everoneUseThisLockObject4CacheXYZ = new object();
        const string CacheXYZ = "CacheXYZ";
        static object everoneUseThisLockObject4CacheABC = new object();
        const string CacheABC = "CacheABC";

        static void Main(string[] args)
        {
            //Allan Xu's usage
            string xyzData = MemoryCacheHelper.GetCachedDataOrAdd<string>(CacheXYZ, everoneUseThisLockObject4CacheXYZ, 20, SomeHeavyAndExpensiveXYZCalculation);
            string abcData = MemoryCacheHelper.GetCachedDataOrAdd<string>(CacheABC, everoneUseThisLockObject4CacheXYZ, 20, SomeHeavyAndExpensiveXYZCalculation);

            //My usage
            string sessionId = System.Web.HttpContext.Current.Session["CurrentUser.SessionId"].ToString();
            string yvz = MemoryCacheHelper.GetCachedData<string>(sessionId);
            if (string.IsNullOrWhiteSpace(yvz))
            {
                object locker = MemoryCacheHelper.GetLocker(sessionId);
                lock (locker)
                {
                    yvz = MemoryCacheHelper.GetCachedData<string>(sessionId);
                    if (string.IsNullOrWhiteSpace(yvz))
                    {
                        DatabaseRepositoryWithHeavyConstructorOverHead dbRepo = new DatabaseRepositoryWithHeavyConstructorOverHead();
                        yvz = dbRepo.GetDataExpensiveDataForSession(sessionId);
                        MemoryCacheHelper.AddDataToCache(sessionId, yvz, 5);
                    }
                }
            }
        }


        private static string SomeHeavyAndExpensiveXYZCalculation() { return "Expensive"; }
        private static string SomeHeavyAndExpensiveABCCalculation() { return "Expensive"; }

        public static class MemoryCacheHelper
        {
            //Allan Xu's solution
            public static T GetCachedDataOrAdd<T>(string cacheKey, object cacheLock, int minutesToExpire, Func<T> GetData) where T : class
            {
                //Returns null if the string does not exist, prevents a race condition where the cache invalidates between the contains check and the retreival.
                T cachedData = MemoryCache.Default.Get(cacheKey, null) as T;

                if (cachedData != null)
                    return cachedData;

                lock (cacheLock)
                {
                    //Check to see if anyone wrote to the cache while we where waiting our turn to write the new value.
                    cachedData = MemoryCache.Default.Get(cacheKey, null) as T;

                    if (cachedData != null)
                        return cachedData;

                    cachedData = GetData();
                    MemoryCache.Default.Set(cacheKey, cachedData, DateTime.Now.AddMinutes(minutesToExpire));
                    return cachedData;
                }
            }

            #region "My Solution"

            readonly static ConcurrentDictionary<string, object> Lockers = new ConcurrentDictionary<string, object>();
            public static object GetLocker(string cacheKey)
            {
                CleanupLockers();

                return Lockers.GetOrAdd(cacheKey, item => (cacheKey, new object()));
            }

            public static T GetCachedData<T>(string cacheKey) where T : class
            {
                CleanupLockers();

                T cachedData = MemoryCache.Default.Get(cacheKey) as T;
                return cachedData;
            }

            public static void AddDataToCache(string cacheKey, object value, int cacheTimePolicyMinutes)
            {
                CleanupLockers();

                MemoryCache.Default.Add(cacheKey, value, DateTimeOffset.Now.AddMinutes(cacheTimePolicyMinutes));
            }

            static DateTimeOffset lastCleanUpTime = DateTimeOffset.MinValue;
            static void CleanupLockers()
            {
                if (DateTimeOffset.Now.Subtract(lastCleanUpTime).TotalMinutes > 1)
                {
                    lock (Lockers)//maybe a better locker is needed?
                    {
                        try//bypass exceptions
                        {
                            List<string> lockersToRemove = new List<string>();
                            foreach (var locker in Lockers)
                            {
                                if (!MemoryCache.Default.Contains(locker.Key))
                                    lockersToRemove.Add(locker.Key);
                            }

                            object dummy;
                            foreach (string lockerKey in lockersToRemove)
                                Lockers.TryRemove(lockerKey, out dummy);

                            lastCleanUpTime = DateTimeOffset.Now;
                        }
                        catch (Exception)
                        { }
                    }
                }

            }
            #endregion
        }
    }

    class DatabaseRepositoryWithHeavyConstructorOverHead
    {
        internal string GetDataExpensiveDataForSession(string sessionId)
        {
            return "Expensive data from database";
        }
    }

}

Find everything between two XML tags with RegEx

You should be able to match it with: /<primaryAddress>(.+?)<\/primaryAddress>/

The content between the tags will be in the matched group.

Asynchronous vs synchronous execution, what does it really mean?

In regards to the "at the same time" definition of synchronous execution (which is sometimes confusing), here's a good way to understand it:

Synchronous Execution: All tasks within a block of code are all executed at the same time.

Asynchronous Execution: All tasks within a block of code are not all executed at the same time.

How to Export Private / Secret ASC Key to Decrypt GPG Files

All the above replies are correct, but might be missing one crucial step, you need to edit the imported key and "ultimately trust" that key

gpg --edit-key (keyIDNumber)
gpg> trust

Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)

  1 = I don't know or won't say
  2 = I do NOT trust
  3 = I trust marginally
  4 = I trust fully
  5 = I trust ultimately
  m = back to the main menu

and select 5 to enable that imported private key as one of your keys

Clearing Magento Log Data

No need to do this yourself, the Magento system has a built-in for cleaning up log information. If you go to

System > Configuration > Advanced > System > Log Cleaning

You can configure your store to automatically clean up these logs.

Error: Cannot find module html

This is what i did for rendering html files. And it solved the errors. Install consolidate and mustache by executing the below command in your project folder.

$ sudo npm install consolidate mustache --save

And make the following changes to your app.js file

var engine = require('consolidate');

app.set('views', __dirname + '/views');
app.engine('html', engine.mustache);
app.set('view engine', 'html');

And now html pages will be rendered properly.

Get the index of a certain value in an array in PHP

The problem is that you don't have a numerical index on your array.
Using array_values() will create a zero indexed array that you can then search using array_search() bypassing the need to use a for loop.

$list = ['string1', 'string2', 'string3'];
$index = array_search('string2',array_values($list));

What is Dependency Injection?

Before going to the technical description first visualize it with a real-life example because you will find a lot of technical stuff to learn dependency injection but the majority of the people can't get the core concept of it.

In the first picture, assume that you have a car factory with a lot of units. A car is actually built in the assembly unit but it needs engine, seats as well as wheels. So an assembly unit is dependent on these all units and they are the dependencies of the factory.

You can feel that now it is too complicated to maintain all of the tasks in this factory because along with the main task (assembling a car in the Assembly unit) you have to also focus on other units. It is now very costly to maintain and the factory building is huge so it takes your extra bucks for rent.

Now, look at the second picture. If you find some provider companies that will provide you with the wheel, seat, and engine for cheaper than your self-production cost then now you don't need to make them in your factory. You can rent a smaller building now just for your assembly unit which will lessen your maintenance task and reduce your extra rental cost. Now you can also focus only on your main task (Car assembly).

Now we can say that all the dependencies for assembling a car are injected on the factory from the providers. It is an example of a real-life Dependency Injection (DI).

Now in the technical word, dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. So, transferring the task of creating the object to someone else and directly using the dependency is called dependency injection.

This will help you now to learn DI with a technical explanation. This will show when to use DI and when you should not.

All in one car factory.

Simple car factory

Notice: Undefined variable: _SESSION in "" on line 9

Add

session_start();

at the beginning of your page before any HTML

You will have something like :

<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...

Don't forget to remove the space you have before

Mobile Redirect using htaccess

I modified Tim Stone's solution even further. This allows the cookie to be in 2 states, 1 for mobile and 0 for full. When the mobile cookie is set to 0 even a mobile browser will go to the full site.

Here is the code:

<IfModule mod_rewrite.c>
    RewriteBase /
    RewriteEngine On

    # Check if mobile=1 is set and set cookie 'mobile' equal to 1
    RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$)
    RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}]

    # Check if mobile=0 is set and set cookie 'mobile' equal to 0
    RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
    RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}]

    # cookie can't be set and read in the same request so check
    RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
    RewriteRule ^ - [S=1]

    # Check if this looks like a mobile device
    RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
    RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
    RewriteCond %{HTTP:Profile}       !^$

    # Check if we're not already on the mobile site
    RewriteCond %{HTTP_HOST}          !^m\.
    # Check to make sure we haven't set the cookie before
    RewriteCond %{HTTP:Cookie}        !\mobile=0(;|$)
    # Now redirect to the mobile site
    RewriteRule ^ http://m.example.com%{REQUEST_URI} [R,L]
</IfModule>

Laravel form html with PUT method for PUT routes

in your view blade change to

{{ Form::open(['action' => 'postcontroller@edit', 'method' => 'PUT', 'class' = 'your class here']) }}

<div>
{{ Form::textarea('textareanamehere', 'default value here', ['placeholder' => 'your place holder here', 'class' => 'your class here']) }}
</div>

<div>
{{ Form::submit('Update', ['class' => 'btn class here'])}}
</div>

{{ Form::close() }}

actually you can use raw form like your question. but i dont recomended it. dan itulah salah satu alasan agan belajar framework, simple, dan cepat. so kenapa pake raw form kalo ada yang lebih mudah. hehe. proud to be indonesian.

reference: Laravel Blade Form

android.content.Context.getPackageName()' on a null object reference

Put fragment name before the activity

Intent mIntent = new Intent(SigninFragment.this.getActivity(),MusicHome.class);

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

I was facing this issue today. Mine was Asp.Net Core API and it uses Postgresql as the database. We have configured this database as a Docker container. So the first step I did was to check whether I am able to access the database or not. To do that I searched for PgAdmin in the start as I have configured the same. Clicking on the resulted application will redirect you to the http://127.0.0.1:23722/browser/. There you can try access your database on the left menu. For me I was getting an error as in the below image.

enter image description here

Enter the password and try whether you are able to access it or not. For me it was not working. As it is a Docker container, I decided to restart my Docker desktop, to do that right click on the docker icon in the task bar and click restart.

Once after restarting the Docker, I was able to login and see the Database and also the error was gone when I restart the application in Visual Studio.

Hope it helps.

How to effectively work with multiple files in Vim

Some answers in this thread suggest using tabs and others suggest using buffer to accomplish the same thing. Tabs and Buffers are different. I strongly suggest you read this article "Vim Tab madness - Buffers vs Tabs".

Here's a nice summary I pulled from the article:

Summary:

  • A buffer is the in-memory text of a file.
  • A window is a viewport on a buffer.
  • A tab page is a collection of windows.

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

UPDATE: This question was the subject of my blog on May 12th 2011. Thanks for the great question!

Suppose you have an interface as you describe, and a hundred classes that implement it. Then you decide to make one of the parameters of one of the interface's methods optional. Are you suggesting that the right thing to do is for the compiler to force the developer to find every implementation of that interface method, and make the parameter optional as well?

Suppose we did that. Now suppose the developer did not have the source code for the implementation:


// in metadata:
public class B 
{ 
    public void TestMethod(bool b) {}
}

// in source code
interface MyInterface 
{ 
    void TestMethod(bool b = false); 
}
class D : B, MyInterface {}
// Legal because D's base class has a public method 
// that implements the interface method

How is the author of D supposed to make this work? Are they required in your world to call up the author of B on the phone and ask them to please ship them a new version of B that makes the method have an optional parameter?

That's not going to fly. What if two people call up the author of B, and one of them wants the default to be true and one of them wants it to be false? What if the author of B simply refuses to play along?

Perhaps in that case they would be required to say:

class D : B, MyInterface 
{
    public new void TestMethod(bool b = false)
    {
        base.TestMethod(b);
    }
}

The proposed feature seems to add a lot of inconvenience for the programmer with no corresponding increase in representative power. What's the compelling benefit of this feature which justifies the increased cost to the user?


UPDATE: In the comments below, supercat suggests a language feature that would genuinely add power to the language and enable some scenarios similar to the one described in this question. FYI, that feature -- default implementations of methods in interfaces -- will be added to C# 8.

In jQuery, how do I select an element by its name attribute?

This works great for me. For example you have two radio buttons with the same "name", and you just wanted to get the value of the checked one. You may try this one.

$valueOfTheCheckedRadio = $('[name=radioName]:checked').val();

How can I get name of element with jQuery?

var name = $('#myElement').attr('name');

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1 is null or ConfigurationManager.AppSettings.Get("Url") is returning null.

open program minimized via command prompt

You could try using the third-party tool called NirCmd. It is a genuine, free command line utility. If or when you have it, use this code in a batch file:

title Open Word
nircmd win hide title "Open Word"
start "C:\Program" "Files" "(x86)\Microsoft" "Office\Office12\WINWORD.exe
nircmd wait 20
nircmd win min foreground
exit

This program, in order, changes its title, hides itself according to its title, starts Word, waits 20 milliseconds as a buffer for Word to settle, minimizes Word by assuming it is now the top window, and then exits itself. This program should work as intended as long as their are no key presses or clicks in that ~50 millisecond time window, which shouldn't be hard.

As for installing nircmd on your computer, use this link, and click "Download NirCmd" at the bottom of the page. Save the .zip folder to a normal directory (like "My Documents"), extract it, and copy "nircmd.exe" to %systemroot%\system32, and there you go. Now you have nircmd included with your command line utilities.

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

An HTML response from the web server normally indicates that an error page has been served instead of the response from the WCF service. My first suggestion would be to check that the user you're running the WCF client under has access to the resource.

Sending the bearer token with axios

The second parameter of axios.post is data (not config). config is the third parameter. Please see this for details: https://github.com/mzabriskie/axios#axiosposturl-data-config

HTML.ActionLink method

I think what you want is this:

ASP.NET MVC1

Html.ActionLink(article.Title, 
                "Login",  // <-- Controller Name.
                "Item",   // <-- ActionMethod
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string controllerName,
                                string actionName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC2

two arguments have been switched around

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC3+

arguments are in the same order as MVC2, however the id value is no longer required:

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This avoids hard-coding any routing logic into the link.

 <a href="/Item/Login/5">Title</a> 

This will give you the following html output, assuming:

  1. article.Title = "Title"
  2. article.ArticleID = 5
  3. you still have the following route defined

. .

routes.MapRoute(
    "Default",     // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

Upgrading Node.js to latest version

There is good explanation for linux users how to update node version step by step. P.S type instead of sudo n stable sudo n latest for receive latest node version.

If you receive following error

Error: Module version mismatch. Expected 48, got 46.

You have just rebuilt npm by the following command npm rebuild it should fix the problem.

Are there .NET implementation of TLS 1.2?

I fixed my problem by switching to the latest .Net Framework. So your target Framework sets your Security Protocol.

when you have this in Web.config

<system.web>
  <httpRuntime targetFramework="4.5"/>
</system.web>

you will get this by default:

ServicePointManager.SecurityProtocol = Ssl3 | Tls

when you have this in Web.config

<system.web>
  <httpRuntime targetFramework="4.6.1"/>
</system.web>

you will get this by default:

ServicePointManager.SecurityProtocol = Tls12 | Tls11 | Tls

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

  1. The legend is part of the default options of the ChartJs library. So you do not need to explicitly add it as an option.

  2. The library generates the HTML. It is merely a matter of adding that to the your page. For example, add it to the innerHTML of a given DIV. (Edit the default options if you are editing the colors, etc)


<div>
    <canvas id="chartDiv" height="400" width="600"></canvas>
    <div id="legendDiv"></div>
</div>

<script>
   var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "The Flash's Speed",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
                label: "Superman's Speed",
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

    var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
    document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>

Rails Root directory path?

In addition to all the other correct answers, since Rails.root is a Pathname object, this won't work:

Rails.root + '/app/assets/...'

You could use something like join

Rails.root.join('app', 'assets')

If you want a string use this:

Rails.root.join('app', 'assets').to_s

Is it not possible to stringify an Error using JSON.stringify?

As no one is talking about the why part, I'm gonna answer it.

Why this JSON.stringify returns an empty object?

> JSON.stringify(error);
'{}'

Answer

From the document of JSON.stringify(),

For all the other Object instances (including Map, Set, WeakMap and WeakSet), only their enumerable properties will be serialized.

and Error object doesn't have its enumerable properties, that's why it prints an empty object.

Define an alias in fish shell

If you add an abbr instead of an alias you'll get better auto-complete. In fish abbr more closely matches the behavior of a bash alias.

abbr -a gco git checkout

Will -add a new abbreviation gco that expands to git checkout.

Here's a video demo of the resulting auto-complete features

How do I check if an array includes a value in JavaScript?

function inArray(elem,array)
{
    var len = array.length;
    for(var i = 0 ; i < len;i++)
    {
        if(array[i] == elem){return i;}
    }
    return -1;
} 

Returns array index if found, or -1 if not found

Rename file with Git

You can rename a file using git's mv command:

$ git mv file_from file_to

Example:

$ git mv helo.txt hello.txt

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   renamed:    helo.txt -> hello.txt
#

$ git commit -m "renamed helo.txt to hello.txt"
[master 14c8c4f] renamed helo.txt to hello.txt
 1 files changed, 0 insertions(+), 0 deletions(-)
 rename helo.txt => hello.txt (100%)

Could not load file or assembly '' or one of its dependencies

  • Goto :Solution -> Package
  • Click on Advanced Tab (Find below the page)
  • Add your dll to additional assemblies(this way we can add external dlls in sharepoint).

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/

"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:

Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."

PHP: HTML: send HTML select option attribute in POST

You will have to use JavaScript. The browser will only send the value of the selected option (so its not PHP's fault).

What your JS should do is hook into the form's submit event and create a hidden field with the value of the selected option's stud_name value. This hidden field will then get sent to the server.

That being said ... you shouldn't relay on the client to provide the correct data. You already know what stud_name should be for a given value on the server (since you are outputting it). So just apply the same logic when you are processing the form.

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

You can start with Instant.ofEpochMilli(long):

LocalDate date =
  Instant.ofEpochMilli(startDateLong)
  .atZone(ZoneId.systemDefault())
  .toLocalDate();

How to kill all active and inactive oracle sessions for user

The KILL SESSION command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.

Check the status to confirm:

SELECT sid, serial#, status, username FROM v$session;

You could also use IMMEDIATE clause:

ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;

The IMMEDIATE clause does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill. Have a look at Killing Oracle Sessions.

Update If you want to kill all the sessions, you could just prepare a small script.

SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' FROM v$session;

Spool the above to a .sql file and execute it, or, copy paste the output and run it.

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.

How to change Format of a Cell to Text using VBA

To answer your direct question, it is:

Range("A1").NumberFormat = "@"

Or

Cells(1,1).NumberFormat = "@"

However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.

transparent navigation bar ios

I had been working on this, and I was facing a problem using the responses provided here by different users. Problem was a white box behind my NavigationBar transparent image on iOS 13+

enter image description here

My solution is this one

if #available(iOS 13, *) {
    navBar?.standardAppearance.backgroundColor = UIColor.clear
    navBar?.standardAppearance.backgroundEffect = nil
    navBar?.standardAppearance.shadowImage = UIImage()
    navBar?.standardAppearance.shadowColor = .clear
    navBar?.standardAppearance.backgroundImage = UIImage()
}

Hope this helps anyone with same problem

How do I perform HTML decoding/encoding using Python/Django?

I found this in the Cheetah source code (here)

htmlCodes = [
    ['&', '&amp;'],
    ['<', '&lt;'],
    ['>', '&gt;'],
    ['"', '&quot;'],
]
htmlCodesReversed = htmlCodes[:]
htmlCodesReversed.reverse()
def htmlDecode(s, codes=htmlCodesReversed):
    """ Returns the ASCII decoded version of the given HTML string. This does
        NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode()."""
    for code in codes:
        s = s.replace(code[1], code[0])
    return s

not sure why they reverse the list, I think it has to do with the way they encode, so with you it may not need to be reversed. Also if I were you I would change htmlCodes to be a list of tuples rather than a list of lists... this is going in my library though :)

i noticed your title asked for encode too, so here is Cheetah's encode function.

def htmlEncode(s, codes=htmlCodes):
    """ Returns the HTML encoded version of the given string. This is useful to
        display a plain ASCII text string on a web page."""
    for code in codes:
        s = s.replace(code[0], code[1])
    return s

Using AngularJS date filter with UTC date

If you do use moment.js you would use the moment().utc() function to convert a moment object to UTC. You can also handle a nice format inside the controller instead of the view by using the moment().format() function. For example:

moment(myDate).utc().format('MM/DD/YYYY')

How to download image using requests

Following code snippet downloads a file.

The file is saved with its filename as in specified url.

import requests

url = "http://example.com/image.jpg"
filename = url.split("/")[-1]
r = requests.get(url, timeout=0.5)

if r.status_code == 200:
    with open(filename, 'wb') as f:
        f.write(r.content)

Remove First and Last Character C++

std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; } 
else {
    while(str.at(0) == ' ') { str.erase(0, 1);}
    while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
    return str ;
    } 
}

How to save image in database using C#

Try this method. It should work when field when you want to store image is of type byte. First it creates byte[] for image. Then it saves it to the DB using IDataParameter of type binary.

using System.Drawing;
using System.Drawing.Imaging;
using System.Data;

    public static void PerisitImage(string path, IDbConnection connection)
    {
        using (var command = connection.CreateCommand ())
        {
            Image img = Image.FromFile (path);
            MemoryStream tmpStream = new MemoryStream();
            img.Save (tmpStream, ImageFormat.Png); // change to other format
            tmpStream.Seek (0, SeekOrigin.Begin);
            byte[] imgBytes = new byte[MAX_IMG_SIZE];
            tmpStream.Read (imgBytes, 0, MAX_IMG_SIZE);

            command.CommandText = "INSERT INTO images(payload) VALUES (:payload)";
            IDataParameter par = command.CreateParameter();
            par.ParameterName = "payload";
            par.DbType = DbType.Binary;
            par.Value = imgBytes;
            command.Parameters.Add(par);
            command.ExecuteNonQuery ();
        }
    }

Hash and salt passwords in C#

Actually this is kind of strange, with the string conversions - which the membership provider does to put them into config files. Hashes and salts are binary blobs, you don't need to convert them to strings unless you want to put them into text files.

In my book, Beginning ASP.NET Security, (oh finally, an excuse to pimp the book) I do the following

static byte[] GenerateSaltedHash(byte[] plainText, byte[] salt)
{
  HashAlgorithm algorithm = new SHA256Managed();

  byte[] plainTextWithSaltBytes = 
    new byte[plainText.Length + salt.Length];

  for (int i = 0; i < plainText.Length; i++)
  {
    plainTextWithSaltBytes[i] = plainText[i];
  }
  for (int i = 0; i < salt.Length; i++)
  {
    plainTextWithSaltBytes[plainText.Length + i] = salt[i];
  }

  return algorithm.ComputeHash(plainTextWithSaltBytes);            
}

The salt generation is as the example in the question. You can convert text to byte arrays using Encoding.UTF8.GetBytes(string). If you must convert a hash to its string representation you can use Convert.ToBase64String and Convert.FromBase64String to convert it back.

You should note that you cannot use the equality operator on byte arrays, it checks references and so you should simply loop through both arrays checking each byte thus

public static bool CompareByteArrays(byte[] array1, byte[] array2)
{
  if (array1.Length != array2.Length)
  {
    return false;
  }

  for (int i = 0; i < array1.Length; i++)
  {
    if (array1[i] != array2[i])
    {
      return false;
    }
  }

  return true;
}

Always use a new salt per password. Salts do not have to be kept secret and can be stored alongside the hash itself.

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

in my case, the version of wheel/pip/setuptools created by venv is too old. this works:

venv/bin/pip  install --upgrade pip wheel setuptools

How to create a service running a .exe file on Windows 2012 Server?

You can use PowerShell.

New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"

Refer - https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-3.0

jQuery convert line breaks to br (nl2br equivalent)

In the spirit of changing the rendering instead of changing the content, the following CSS makes each newline behave like a <br>:

white-space: pre;
white-space: pre-line;

Why two rules: pre-line only affects newlines (thanks for the clue, @KevinPauli). IE6-7 and other old browsers fall back to the more extreme pre which also includes nowrap and renders multiple spaces. Details on these and other settings (pre-wrap) at mozilla and css-tricks (thanks @Sablefoste).

While I'm generally averse to the S.O. predilection for second-guessing the question rather than answering it, in this case replacing newlines with <br> markup may increase vulnerability to injection attack with unwashed user input. You're crossing a bright red line whenever you find yourself changing .text() calls to .html() which the literal question implies would have to be done. (Thanks @AlexS for highlighting this point.) Even if you rule out a security risk at the time, future changes could unwittingly introduce it. Instead, this CSS allows you to get hard line breaks without markup using the safer .text().

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

Deep Learning

Gather at least a few hundred images containing cola cans, annotate the bounding box around them as positive classes, include cola bottles and other cola products label them negative classes as well as random objects.

Unless you collect a very large dataset, perform the trick of using deep learning features for small dataset. Ideally using a combination of Support Vector Machines(SVM) with deep neural nets.

Once you feed the images to a previously trained deep learning model(e.g. GoogleNet), instead of using neural network's decision (final) layer to do classifications, use previous layer(s)' data as features to train your classifier.

OpenCV and Google Net: http://docs.opencv.org/trunk/d5/de7/tutorial_dnn_googlenet.html

OpenCV and SVM: http://docs.opencv.org/2.4/doc/tutorials/ml/introduction_to_svm/introduction_to_svm.html

How to extract the nth word and count word occurrences in a MySQL string?

Shorter option to extract the second word in a sentence:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('THIS IS A TEST', ' ',  2), ' ', -1) as FoundText

MySQL docs for SUBSTRING_INDEX

SQL Server database backup restore on lower version

Here are my 2 cents on different options for completing this:

Third party tools: Probably the easiest way to get the job done is to create an empty database on lower version and then use third party tools to read the backup and synchronize new newly created database with the backup.

Red gate is one of the most popular but there are many others like ApexSQL Diff , ApexSQL Data Diff, Adept SQL, Idera …. All of these are premium tools but you can get the job done in trial mode ;)

Generating scripts: as others already mentioned you can always script structure and data using SSMS but you need to take into consideration the order of execution. By default object scripts are not ordered correctly and you’ll have to take care of the dependencies. This may be an issue if database is big and has a lot of objects.

Import and export wizard: This is not an ideal solution as it will not restore all objects but only data tables but you can consider it for quick and dirty fixes when it’s needed.

python: restarting a loop

Changing the index variable i from within the loop is unlikely to do what you expect. You may need to use a while loop instead, and control the incrementing of the loop variable yourself. Each time around the for loop, i is reassigned with the next value from range(). So something like:

i = 2
while i < n:
    if(something):
        do something
    else:
        do something else
        i = 2 # restart the loop
        continue
    i += 1

In my example, the continue statement jumps back up to the top of the loop, skipping the i += 1 statement for that iteration. Otherwise, i is incremented as you would expect (same as the for loop).

"Operation must use an updateable query" error in MS Access

There is no error in the code, but the error is thrown due to the following:

 - Please check whether you have given Read-write permission to MS-Access database file.
 - The Database file where it is stored (say in Folder1) is read-only..? 

suppose you are stored the database (MS-Access file) in read only folder, while running your application the connection is not force-fully opened. Hence change the file permission / its containing folder permission like in C:\Program files all most all c drive files been set read-only so changing this permission solves this Problem.

How do you change the text in the Titlebar in Windows Forms?

If you want to update it later, once "this" no longer references it, I had some luck with assigning a variable to point to the main form.

  static Form f0;
  public OrdUpdate()
  {
   InitializeComponent();
   f0=this;
  }
  // then later you can say
  f0.Text="New text";

When do you use POST and when do you use GET?

The original intent was that GET was used for getting data back and POST was to be anything. The rule of thumb that I use is that if I'm sending anything back to the server, I use POST. If I'm just calling an URL to get back data, I use GET.

Hash function for a string

-- The way to go these days --

Use SipHash. For your own protection.

-- Old and Dangerous --

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

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

    return (hash & 0x7FFFFFFF);
 }

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

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

      return (hash & 0x7FFFFFFF);
 }

Ask google for "general purpose hash function"

How do I syntax check a Bash script without running it?

sh  -n   script-name 

Run this. If there are any syntax errors in the script, then it returns the same error message. If there are no errors, then it comes out without giving any message. You can check immediately by using echo $?, which will return 0 confirming successful without any mistake.

It worked for me well. I ran on Linux OS, Bash Shell.

What is sys.maxint in Python 3?

Python 3.0 doesn't have sys.maxint any more since Python 3's ints are of arbitrary length. Instead of sys.maxint it has sys.maxsize; the maximum size of a positive sized size_t aka Py_ssize_t.

Get exit code for command in bash/ksh

Try

safeRunCommand() {
   "$@"

   if [ $? != 0 ]; then
      printf "Error when executing command: '$1'"
      exit $ERROR_CODE
   fi
}

Select something that has more/less than x character

Today I was trying same in db2 and used below, in my case I had spaces at the end of varchar column data

SELECT EmployeeName FROM EmployeeTable WHERE LENGTH(TRIM(EmployeeName))> 4;

How do I replace whitespaces with underscore?

You don't need regular expressions. Python has a built-in string method that does what you need:

mystring.replace(" ", "_")

android.app.Application cannot be cast to android.app.Activity

You are passing the Application Context not the Activity Context with

getApplicationContext();

Wherever you are passing it pass this or ActivityName.this instead.

Since you are trying to cast the Context you pass (Application not Activity as you thought) to an Activity with

(Activity)

you get this exception because you can't cast the Application to Activity since Application is not a sub-class of Activity.

How to grep for contents after pattern?

grep 'potato:' file.txt | sed 's/^.*: //'

grep looks for any line that contains the string potato:, then, for each of these lines, sed replaces (s/// - substitute) any character (.*) from the beginning of the line (^) until the last occurrence of the sequence : (colon followed by space) with the empty string (s/...// - substitute the first part with the second part, which is empty).

or

grep 'potato:' file.txt | cut -d\   -f2

For each line that contains potato:, cut will split the line into multiple fields delimited by space (-d\ - d = delimiter, \ = escaped space character, something like -d" " would have also worked) and print the second field of each such line (-f2).

or

grep 'potato:' file.txt | awk '{print $2}'

For each line that contains potato:, awk will print the second field (print $2) which is delimited by default by spaces.

or

grep 'potato:' file.txt | perl -e 'for(<>){s/^.*: //;print}'

All lines that contain potato: are sent to an inline (-e) Perl script that takes all lines from stdin, then, for each of these lines, does the same substitution as in the first example above, then prints it.

or

awk '{if(/potato:/) print $2}' < file.txt

The file is sent via stdin (< file.txt sends the contents of the file via stdin to the command on the left) to an awk script that, for each line that contains potato: (if(/potato:/) returns true if the regular expression /potato:/ matches the current line), prints the second field, as described above.

or

perl -e 'for(<>){/potato:/ && s/^.*: // && print}' < file.txt

The file is sent via stdin (< file.txt, see above) to a Perl script that works similarly to the one above, but this time it also makes sure each line contains the string potato: (/potato:/ is a regular expression that matches if the current line contains potato:, and, if it does (&&), then proceeds to apply the regular expression described above and prints the result).

How to check if mysql database exists

I am using simply the following query:

"USE 'DBname'"

Then check if the result is FALSE. Otherwise, there might be an access denied error, but I cannot know that. So, in case of privileges involved, one can use:

"SHOW DATABASES LIKE 'DBname'"

as already mentioned earlier.

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

tl;dr:

concat and append currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True to silence it. In the future the default will change to not sort, so it's best to specify either sort=True or False now, or better yet ensure that your non-concatenation indices match.


The warning is new in pandas 0.23.0:

In a future version of pandas pandas.concat() and DataFrame.append() will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned, link.

More information from linked very old github issue, comment by smcinerney :

When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.

This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.

After some time the parameter sort was implemented in pandas.concat and DataFrame.append:

sort : boolean, default None

Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.

Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.

This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

So if both DataFrames have the same columns in the same order, there is no warning and no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])

print (pd.concat([df1, df2]))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort is explicitly set (sort=None is the default value):

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=True))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=False))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a and b from df1 with a and b from df2 in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.

Lastly, if you pass sort=True, columns are sorted alphanumerically. If sort=False and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]}, 
                    columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]}, 
                    columns=['c','b','a','d'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=True))
   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=False))

   b  a    e    c    d
0  0  1  5.0  NaN  NaN
1  8  2  0.0  NaN  NaN
0  7  4  NaN  2.0  7.0
1  3  5  NaN  8.0  0.0

In your code:

placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
                                                       .append(placement_by_video_summary_new, sort=True)
                                                       .sort_index()

How do I execute cmd commands through a batch file?

cmd /c "command" syntax works well. Also, if you want to include an executable that contains a space in the path, you will need two sets of quotes.

cmd /c ""path to executable""

and if your executable needs a file input with a space in the path a another set

cmd /c ""path to executable" -f "path to file"" 

Remove folder and its contents from git/GitHub's history

It appears that the up-to-date answer to this is to not use filter-branch directly (at least git itself does not recommend it anymore), and defer that work to an external tool. In particular, git-filter-repo is currently recommended. The author of that tool provides arguments on why using filter-branch directly can lead to issues.

Most of the multi-line scripts above to remove dir from the history could be re-written as:

git filter-repo --path dir --invert-paths

The tool is more powerful than just that, apparently. You can apply filters by author, email, refname and more (full manpage here). Furthermore, it is fast. Installation is easy - it is distributed in a variety of formats.

SQL to LINQ Tool

I know that this isn't what you asked for but LINQPad is a really great tool to teach yourself LINQ (and it's free :o).

When time isn't critical, I have been using it for the last week or so instead or a query window in SQL Server and my LINQ skills are getting better and better.

It's also a nice little code snippet tool. Its only downside is that the free version doesn't have IntelliSense.

JSON.stringify output to div in pretty print way

Consider your REST API returns:

{"Intent":{"Command":"search","SubIntent":null}}

Then you can do the following to print it in a nice format:

<pre id="ciResponseText">Output will de displayed here.</pre>   

var ciResponseText = document.getElementById('ciResponseText');
var obj = JSON.parse(http.response);
ciResponseText.innerHTML = JSON.stringify(obj, undefined, 2);   

Origin http://localhost is not allowed by Access-Control-Allow-Origin

You've got two ways to go forward:

JSONP


If this API supports JSONP, the easiest way to fix this issue is to add &callback to the end of the URL. You can also try &callback=. If that doesn't work, it means the API does not support JSONP, so you must try the other solution.

Proxy Script


You can create a proxy script on the same domain as your website in order to avoid the cross-origin issues. This will only work with HTTP URLs, not HTTPS URLs, but it shouldn't be too difficult to modify if you need that.

<?php
// File Name: proxy.php
if (!isset($_GET['url'])) {
    die(); // Don't do anything if we don't have a URL to work with
}
$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url); // Avoid accessing the file system
echo file_get_contents($url); // You should probably use cURL. The concept is the same though

Then you just call this script with jQuery. Be sure to urlencode the URL.

$.ajax({
    url      : 'proxy.php?url=http%3A%2F%2Fapi.master18.tiket.com%2Fsearch%2Fautocomplete%2Fhotel%3Fq%3Dmah%26token%3D90d2fad44172390b11527557e6250e50%26secretkey%3D83e2f0484edbd2ad6fc9888c1e30ea44%26output%3Djson',
    type     : 'GET',
    dataType : 'json'
}).done(function(data) {
    console.log(data.results.result[1].category); // Do whatever you want here
});

The Why


You're getting this error because of XMLHttpRequest same origin policy, which basically boils down to a restriction of ajax requests to URLs with a different port, domain or protocol. This restriction is in place to prevent cross-site scripting (XSS) attacks.

More Information

Our solutions by pass these problems in different ways.

JSONP uses the ability to point script tags at JSON (wrapped in a javascript function) in order to receive the JSON. The JSONP page is interpreted as javascript, and executed. The JSON is passed to your specified function.

The proxy script works by tricking the browser, as you're actually requesting a page on the same origin as your page. The actual cross-origin requests happen server-side.

CSS Circle with border

You are missing the border width and the border style properties in the Border shorthand property :

_x000D_
_x000D_
.circle {
    border: 2px solid red;
    background-color: #FFFFFF;
    height: 100px;
    border-radius:50%;
    width: 100px;
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_


Also, You can use percentages for the border-radius property so that the value isn't dependent of the circle width/height. That is why I used 50% for border-radius (more info on border-radius in pixels and percent).

Side note : In your example, you didn't specify the border-radius property without vendor prefixes whitch you propably don't need as only browsers before chrome 4 safari 4 and Firefox 3.6 use them (see canIuse).

How to set custom location for local installation of npm package?

On Windows 7 for example, the following set of commands/operations could be used.

Create an personal environment variable, double backslashes are mandatory:

  • Variable name: %NPM_HOME%
  • Variable value: C:\\SomeFolder\\SubFolder\\

Now, set the config values to the new folders (examplary file names):

  • Set the npm folder

npm config set prefix "%NPM_HOME%\\npm"

  • Set the npm-cache folder

npm config set cache "%NPM_HOME%\\npm-cache"

  • Set the npm temporary folder

npm config set tmp "%NPM_HOME%\\temp"

Optionally, you can purge the contents of the original folders before the config is changed.

  • Delete the npm-cache npm cache clear

  • List the npm modules npm -g ls

  • Delete the npm modules npm -g rm name_of_package1 name_of_package2

Tuples( or arrays ) as Dictionary keys in C#

Between tuple and nested dictionaries based approaches, it's almost always better to go for tuple based.

From maintainability point of view,

  • its much easier to implement a functionality that looks like:

    var myDict = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();
    

    than

    var myDict = new Dictionary<TypeA, Dictionary<TypeB, Dictionary<TypeC, string>>>();
    

    from the callee side. In the second case each addition, lookup, removal etc require action on more than one dictionary.

  • Furthermore, if your composite key require one more (or less) field in future, you will need to change code a significant lot in the second case (nested dictionary) since you have to add further nested dictionaries and subsequent checks.

From performance perspective, the best conclusion you can reach is by measuring it yourself. But there are a few theoretical limitations which you can consider beforehand:

  • In the nested dictionary case, having an additional dictionary for every keys (outer and inner) will have some memory overhead (more than what creating a tuple would have).

  • In the nested dictionary case, every basic action like addition, updation, lookup, removal etc need to be carried out in two dictionaries. Now there is a case where nested dictionary approach can be faster, i.e., when the data being looked up is absent, since the intermediate dictionaries can bypass the full hash code computation & comparison, but then again it should be timed to be sure. In presence of data, it should be slower since lookups should be performed twice (or thrice depending on nesting).

  • Regarding tuple approach, .NET tuples are not the most performant when they're meant to be used as keys in sets since its Equals and GetHashCode implementation causes boxing for value types.

I would go with tuple based dictionary, but if I want more performance, I would use my own tuple with better implementation.


On a side note, few cosmetics can make the dictionary cool:

  1. Indexer style calls can be a lot cleaner and intuitive. For eg,

    string foo = dict[a, b, c]; //lookup
    dict[a, b, c] = ""; //update/insertion
    

    So expose necessary indexers in your dictionary class which internally handles the insertions and lookups.

  2. Also, implement a suitable IEnumerable interface and provide an Add(TypeA, TypeB, TypeC, string) method which would give you collection initializer syntax, like:

    new MultiKeyDictionary<TypeA, TypeB, TypeC, string> 
    { 
        { a, b, c, null }, 
        ...
    };
    

Parse JSON in TSQL

CREATE FUNCTION dbo.parseJSON( @JSON NVARCHAR(MAX))
RETURNS @hierarchy TABLE
  (
   element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
   sequenceNo [int] NULL, /* the place in the sequence for the element */
   parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
   Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
   NAME NVARCHAR(2000),/* the name of the object */
   StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
   ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/
  )
AS
BEGIN
  DECLARE
    @FirstObject INT, --the index of the first open bracket found in the JSON string
    @OpenDelimiter INT,--the index of the next open bracket found in the JSON string
    @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
    @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
    @Type NVARCHAR(10),--whether it denotes an object or an array
    @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
    @Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression
    @Start INT, --index of the start of the token that you are parsing
    @end INT,--index of the end of the token that you are parsing
    @param INT,--the parameter at the end of the next Object/Array token
    @EndOfName INT,--the index of the start of the parameter at end of Object/Array token
    @token NVARCHAR(200),--either a string or object
    @value NVARCHAR(MAX), -- the value as a string
    @SequenceNo int, -- the sequence number within a list
    @name NVARCHAR(200), --the name as a string
    @parent_ID INT,--the next parent ID to allocate
    @lenJSON INT,--the current length of the JSON String
    @characters NCHAR(36),--used to convert hex to decimal
    @result BIGINT,--the value of the hex symbol being parsed
    @index SMALLINT,--used for parsing the hex value
    @Escape INT --the index of the next escape character


  DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
    (
     String_ID INT IDENTITY(1, 1),
     StringValue NVARCHAR(MAX)
    )
  SELECT--initialise the characters to convert hex to ascii
    @characters='0123456789abcdefghijklmnopqrstuvwxyz',
    @SequenceNo=0, --set the sequence no. to something sensible.
  /* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
    @parent_ID=0;
  WHILE 1=1 --forever until there is nothing more to do
    BEGIN
      SELECT
        @start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string
      IF @start=0 BREAK --no more so drop through the WHILE loop
      IF SUBSTRING(@json, @start+1, 1)='"'
        BEGIN --Delimited Name
          SET @start=@Start+1;
          SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);
        END
      IF @end=0 --no end delimiter to last string
        BREAK --no more
      SELECT @token=SUBSTRING(@json, @start+1, @end-1)
      --now put in the escaped control characters
      SELECT @token=REPLACE(@token, FROMString, TOString)
      FROM
        (SELECT
          '\"' AS FromString, '"' AS ToString
         UNION ALL SELECT '\\', '\'
         UNION ALL SELECT '\/', '/'
         UNION ALL SELECT '\b', CHAR(08)
         UNION ALL SELECT '\f', CHAR(12)
         UNION ALL SELECT '\n', CHAR(10)
         UNION ALL SELECT '\r', CHAR(13)
         UNION ALL SELECT '\t', CHAR(09)
        ) substitutions
      SELECT @result=0, @escape=1
  --Begin to take out any hex escape codes
      WHILE @escape>0
        BEGIN
          SELECT @index=0,
          --find the next hex escape sequence
          @escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)
          IF @escape>0 --if there is one
            BEGIN
              WHILE @index<4 --there are always four digits to a \x sequence  
                BEGIN
                  SELECT --determine its value
                    @result=@result+POWER(16, @index)
                    *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),
                                @characters)-1), @index=@index+1 ;

                END
                -- and replace the hex sequence by its unicode value
              SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))
            END
        END
      --now store the string away
      INSERT INTO @Strings (StringValue) SELECT @token
      -- and replace the string with a token
      SELECT @JSON=STUFF(@json, @start, @end+1,
                    '@string'+CONVERT(NVARCHAR(5), @@identity))
    END
  -- all strings are now removed. Now we find the first leaf. 
  WHILE 1=1  --forever until there is nothing more to do
  BEGIN

  SELECT @parent_ID=@parent_ID+1
  --find the first object or list by looking for the open bracket
  SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array
  IF @FirstObject = 0 BREAK
  IF (SUBSTRING(@json, @FirstObject, 1)='{')
    SELECT @NextCloseDelimiterChar='}', @type='object'
  ELSE
    SELECT @NextCloseDelimiterChar=']', @type='array'
  SELECT @OpenDelimiter=@firstObject

  WHILE 1=1 --find the innermost object or list...
    BEGIN
      SELECT
        @lenJSON=LEN(@JSON+'|')-1
  --find the matching close-delimiter proceeding after the open-delimiter
      SELECT
        @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,
                                      @OpenDelimiter+1)
  --is there an intervening open-delimiter of either type
      SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',
             RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object
      IF @NextOpenDelimiter=0
        BREAK
      SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter
      IF @NextCloseDelimiter<@NextOpenDelimiter
        BREAK
      IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{'
        SELECT @NextCloseDelimiterChar='}', @type='object'
      ELSE
        SELECT @NextCloseDelimiterChar=']', @type='array'
      SELECT @OpenDelimiter=@NextOpenDelimiter
    END
  ---and parse out the list or name/value pairs
  SELECT
    @contents=SUBSTRING(@json, @OpenDelimiter+1,
                        @NextCloseDelimiter-@OpenDelimiter-1)
  SELECT
    @JSON=STUFF(@json, @OpenDelimiter,
                @NextCloseDelimiter-@OpenDelimiter+1,
                '@'+@type+CONVERT(NVARCHAR(5), @parent_ID))
  WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0
    BEGIN
      IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null
        BEGIN
          SELECT
            @SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name.
          SELECT  @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA
          SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),
            @endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),
            @param=RIGHT(@token, LEN(@token)-@endofname+1)
          SELECT
            @token=LEFT(@token, @endofname-1),
            @Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)
          SELECT  @name=stringvalue FROM @strings
            WHERE string_id=@param --fetch the name
        END
      ELSE
        SELECT @Name=null,@SequenceNo=@SequenceNo+1
      SELECT
        @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null
      IF @end=0
        SELECT  @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin)
          +1
       SELECT
        @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)
      --select @start,@end, LEN(@contents+'|'), @contents 
      SELECT
        @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),
        @Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)
      IF SUBSTRING(@value, 1, 7)='@object'
        INSERT INTO @hierarchy
          (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
          SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5),
            SUBSTRING(@value, 8, 5), 'object'
      ELSE
        IF SUBSTRING(@value, 1, 6)='@array'
          INSERT INTO @hierarchy
            (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
            SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5),
              SUBSTRING(@value, 7, 5), 'array'
        ELSE
          IF SUBSTRING(@value, 1, 7)='@string'
            INSERT INTO @hierarchy
              (NAME, SequenceNo, parent_ID, StringValue, ValueType)
              SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'
              FROM @strings
              WHERE string_id=SUBSTRING(@value, 8, 5)
          ELSE
            IF @value IN ('true', 'false')
              INSERT INTO @hierarchy
                (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'
            ELSE
              IF @value='null'
                INSERT INTO @hierarchy
                  (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                  SELECT @name, @SequenceNo, @parent_ID, @value, 'null'
              ELSE
                IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'real'
                ELSE
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'int'
      if @Contents=' ' Select @SequenceNo=0
    END
  END
INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
  SELECT '-',1, NULL, '', @parent_id-1, @type
--
   RETURN
END
GO

---Pase JSON

Declare @pars varchar(MAX) = 
' {"shapes":[{"type":"polygon","geofenceName":"","geofenceDescription":"",
"geofenceCategory":"1","color":"#1E90FF","paths":[{"path":[{
"lat":"26.096254906968525","lon":"65.709228515625"}
,{"lat":"28.38173504322308","lon":"66.741943359375"}
,{"lat":"26.765230565697482","lon":"68.983154296875"}
,{"lat":"26.254009699865737","lon":"68.609619140625"}
,{"lat":"25.997549919572112","lon":"68.104248046875"}
,{"lat":"26.843677401113002","lon":"67.115478515625"}
,{"lat":"25.363882272740255","lon":"65.819091796875"}]}]}]}'
Select * from parseJSON(@pars) AS MyResult 

Python Set Comprehension

You can generate pairs like this:

{(x, x + 2) for x in r if x + 2 in r}

Then all that is left to do is to get a condition to make them prime, which you have already done in the first example.

A different way of doing it: (Although slower for large sets of primes)

{(x, y) for x in r for y in r if x + 2 == y}

Iterating through a range of dates in Python

What about the following for doing a range incremented by days:

for d in map( lambda x: startDate+datetime.timedelta(days=x), xrange( (stopDate-startDate).days ) ):
  # Do stuff here
  • startDate and stopDate are datetime.date objects

For a generic version:

for d in map( lambda x: startTime+x*stepTime, xrange( (stopTime-startTime).total_seconds() / stepTime.total_seconds() ) ):
  # Do stuff here
  • startTime and stopTime are datetime.date or datetime.datetime object (both should be the same type)
  • stepTime is a timedelta object

Note that .total_seconds() is only supported after python 2.7 If you are stuck with an earlier version you can write your own function:

def total_seconds( td ):
  return float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

In AngularJS, what's the difference between ng-pristine and ng-dirty?

pristine tells us if a field is still virgin, and dirty tells us if the user has already typed anything in the related field:

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>_x000D_
<form ng-app="" name="myForm">_x000D_
  <input name="email" ng-model="data.email">_x000D_
  <div class="info" ng-show="myForm.email.$pristine">_x000D_
    Email is virgine._x000D_
  </div>_x000D_
  <div class="error" ng-show="myForm.email.$dirty">_x000D_
    E-mail is dirty_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

A field that has registred a single keydown event is no more virgin (no more pristine) and is therefore dirty for ever.

Editing in the Chrome debugger

Pretty easy, go to the 'scripts' tab. And select the source file you want and double-click any line to edit it.

How to force a component's re-rendering in Angular 2?

tx, found the workaround I needed:

  constructor(private zone:NgZone) {
    // enable to for time travel
    this.appStore.subscribe((state) => {
        this.zone.run(() => {
            console.log('enabled time travel');
        });
    });

running zone.run will force the component to re-render

What is difference between Axios and Fetch?

  1. Fetch API, need to deal with two promises to get the response data in JSON Object property. While axios result into JSON object.

  2. Also error handling is different in fetch, as it does not handle server side error in the catch block, the Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. While in axios you can catch all error in catch block.

I will say better to use axios, straightforward to handle interceptors, headers config, set cookies and error handling.

Refer this

Getting the last n elements of a vector. Is there a better way than using the length() function?

You can do exactly the same thing in R with two more characters:

x <- 0:9
x[-5:-1]
[1] 5 6 7 8 9

or

x[-(1:5)]

Why do I get the "Unhandled exception type IOException"?

You should add "throws IOException" to your main method:

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

You can read a bit more about checked exceptions (which are specific to Java) in JLS.

How to call a Python function from Node.js

You could take your python, transpile it, and then call it as if it were javascript. I have done this succesfully for screeps and even got it to run in the browser a la brython.

Display TIFF image in all web browser

You can try converting your image from tiff to PNG, here is how to do it:

import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.PNGEncodeParam;
import com.sun.media.jai.codec.TIFFDecodeParam;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javaxt.io.Image;

public class ImgConvTiffToPng {

    public static byte[] convert(byte[] tiff) throws Exception {

        byte[] out = new byte[0];
        InputStream inputStream = new ByteArrayInputStream(tiff);

        TIFFDecodeParam param = null;

        ImageDecoder dec = ImageCodec.createImageDecoder("tiff", inputStream, param);
        RenderedImage op = dec.decodeAsRenderedImage(0);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        PNGEncodeParam jpgparam = null;
        ImageEncoder en = ImageCodec.createImageEncoder("png", outputStream, jpgparam);
        en.encode(op);
        outputStream = (ByteArrayOutputStream) en.getOutputStream();
        out = outputStream.toByteArray();
        outputStream.flush();
        outputStream.close();

        return out;

    }

How to print third column to last column?

awk -v m="\x0a" -v N="3" '{$N=m$N ;print substr($0, index($0,m)+1)}'

This chops what is before the given field nr., N, and prints all the rest of the line, including field nr.N and maintaining the original spacing (it does not reformat). It doesn't mater if the string of the field appears also somewhere else in the line, which is the problem with daisaa's answer.

Define a function:

fromField () { 
awk -v m="\x0a" -v N="$1" '{$N=m$N; print substr($0,index($0,m)+1)}'
}

And use it like this:

$ echo "  bat   bi       iru   lau bost   " | fromField 3
iru   lau bost   
$ echo "  bat   bi       iru   lau bost   " | fromField 2
bi       iru   lau bost 

Output maintains everything, including trailing spaces

Works well for files where '/n' is the record separator so you don't have that new-line char inside the lines. If you want to use it with other record separators then use:

awk -v m="\x01" -v N="3" '{$N=m$N ;print substr($0, index($0,m)+1)}'

for example. Works well with almost all files as long as they don't use hexadecimal char nr. 1 inside the lines.

Eclipse JPA Project Change Event Handler (waiting)

There is another way to disable JPA tools for the project, that doesn't require to uninstall JPA features/plug-ins. I tested on https://github.com/Jasig/uPortal project wich was mentioned in https://bugs.eclipse.org/bugs/show_bug.cgi?id=386171 and claims to have similar problems:

  1. Switch to Eclipse Projects Explorer View to see the projects with JPA Facet Enabled (there should be "JPA Content" node);
  2. Select the project of interest which has "JPA Content" node and select Properties from context menu or press Alt+Enter to show Properties dialog for the project;
  3. Select "Project Facets" node in tree with categories;
  4. Clear JPA check box in project facets list and press OK.

After disabling JPA facet for uportal-war project form repository above I don't see any JPA related jobs in Eclipse Progress View.

Find the nth occurrence of substring in a string

Here's a more Pythonic version of the straightforward iterative solution:

def find_nth(haystack, needle, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+len(needle))
        n -= 1
    return start

Example:

>>> find_nth("foofoofoofoo", "foofoo", 2)
6

If you want to find the nth overlapping occurrence of needle, you can increment by 1 instead of len(needle), like this:

def find_nth_overlapping(haystack, needle, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+1)
        n -= 1
    return start

Example:

>>> find_nth_overlapping("foofoofoofoo", "foofoo", 2)
3

This is easier to read than Mark's version, and it doesn't require the extra memory of the splitting version or importing regular expression module. It also adheres to a few of the rules in the Zen of python, unlike the various re approaches:

  1. Simple is better than complex.
  2. Flat is better than nested.
  3. Readability counts.

What does the ">" (greater-than sign) CSS selector mean?

html
<div>
    <p class="some_class">lohrem text (it will be of red color )</p>    
    <div>
        <p class="some_class">lohrem text (it will  NOT be of red color)</p> 
    </div>
    <p class="some_class">lohrem text (it will be  of red color )</p>
</div>
css
div > p.some_class{
    color:red;
}

All the direct children that are <p> with .some_class would get the style applied to them.

Remove rows not .isin('X')

You can use the DataFrame.select method:

In [1]: df = pd.DataFrame([[1,2],[3,4]], index=['A','B'])

In [2]: df
Out[2]: 
   0  1
A  1  2
B  3  4

In [3]: L = ['A']

In [4]: df.select(lambda x: x in L)
Out[4]: 
   0  1
A  1  2

How to Right-align flex item?

'justify-content: flex-end' worked within price box container.

.price-box {
    justify-content: flex-end;
}

Where is database .bak file saved from SQL Server Management Studio?

have you tried:

C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\Backup

Script to get all backups in the last week can be found at:

http://wraithnath.blogspot.com/2010/12/how-to-find-all-database-backups-in.html

I have plenty more backup SQL scripts there also at

http://wraithnath.blogspot.com/search/label/SQL

What is a Question Mark "?" and Colon ":" Operator Used for?

They are called the ternary operator since they are the only one in Java.

The difference to the if...else construct is, that they return something, and this something can be anything:

  int k = a > b ? 7 : 8; 
  String s = (foobar.isEmpty ()) ? "empty" : foobar.toString (); 

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

How do I escape a reserved word in Oracle?

Oracle normally requires double-quotes to delimit the name of identifiers in SQL statements, e.g.

SELECT "MyColumn" AS "MyColAlias"
FROM "MyTable" "Alias"
WHERE "ThisCol" = 'That Value';

However, it graciously allows omitting the double-quotes, in which case it quietly converts the identifier to uppercase:

SELECT MyColumn AS MyColAlias
FROM MyTable Alias
WHERE ThisCol = 'That Value';

gets internally converted to something like:

SELECT "ALIAS" . "MYCOLUMN" AS "MYCOLALIAS"
FROM "THEUSER" . "MYTABLE" "ALIAS"
WHERE "ALIAS" . "THISCOL" = 'That Value';

How to query a CLOB column in Oracle

If you are using SQL*Plus try the following...

set long 8000

select ...

Convert Date format into DD/MMM/YYYY format in SQL Server

Try using the below query.

SELECT REPLACE(CONVERT(VARCHAR(11),GETDATE(),6), ' ','/');  

Result: 20/Jun/13

SELECT REPLACE(CONVERT(VARCHAR(11),GETDATE(),106), ' ','/');  

Result: 20/Jun/2013

Why is a primary-foreign key relation required when we can join without it?

You don't need a FK, you can join arbitrary columns.

But having a foreign key ensures that the join will actually succeed in finding something.

Foreign key give you certain guarantees that would be extremely difficult and error prone to implement otherwise.

For example, if you don't have a foreign key, you might insert a detail record in the system and just after you checked that the matching master record is present somebody else deletes it. So in order to prevent this you need to lock the master table, when ever you modify the detail table (and vice versa). If you don't need/want that guarantee, screw the FKs.

Depending on your RDBMS a foreign key also might improve performance of select (but also degrades performance of updates, inserts and deletes)

Custom domain for GitHub project pages

As of Aug 29, 2013, Github's documentation claim that:

Warning: Project pages subpaths like http://username.github.io/projectname will not be redirected to a project's custom domain.

ExpressJS How to structure an application?

I don't think it's a good approach to add routes to config. A better structure could be something like this:

application/
| - app.js
| - config.js
| - public/ (assets - js, css, images)
| - views/ (all your views files)
| - libraries/ (you can also call it modules/ or routes/)
    | - users.js
    | - products.js
    | - etc...

So products.js and users.js will contain all your routes will all logic within.

List of all index & index columns in SQL Server DB

sELECT 
     TableName = t.name,
     IndexName = ind.name,
     --IndexId = ind.index_id,
     ColumnId = ic.index_column_id,
     ColumnName = col.name,
     key_ordinal,
     ind.type_desc
     --ind.*,
     --ic.*,
     --col.* 
FROM 
     sys.indexes ind 
INNER JOIN 
     sys.index_columns ic ON  ind.object_id = ic.object_id and ind.index_id = ic.index_id 
INNER JOIN 
     sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id 
INNER JOIN 
     sys.tables t ON ind.object_id = t.object_id 
WHERE 
     ind.is_primary_key = 0 
     AND ind.is_unique = 0 
     AND ind.is_unique_constraint = 0 
     AND t.is_ms_shipped = 0 
     and t.name='CompanyReconciliation' --table name
     and key_ordinal>0
ORDER BY 
     t.name, ind.name, ind.index_id, ic.index_column_id 

List distinct values in a vector in R

Try using the duplicated function in combination with the negation operator "!".

Example:

wdups <- rep(1:5,5)
wodups <- wdups[which(!duplicated(wdups))]

Hope that helps.

Deep copy of a dict in python

Python 3.x

from copy import deepcopy

my_dict = {'one': 1, 'two': 2}
new_dict_deepcopy = deepcopy(my_dict)

Without deepcopy, I am unable to remove the hostname dictionary from within my domain dictionary.

Without deepcopy I get the following error:

"RuntimeError: dictionary changed size during iteration"

...when I try to remove the desired element from my dictionary inside of another dictionary.

import socket
import xml.etree.ElementTree as ET
from copy import deepcopy

domain is a dictionary object

def remove_hostname(domain, hostname):
    domain_copy = deepcopy(domain)
    for domains, hosts in domain_copy.items():
        for host, port in hosts.items():
           if host == hostname:
                del domain[domains][host]
    return domain

Example output: [orginal]domains = {'localdomain': {'localhost': {'all': '4000'}}}

[new]domains = {'localdomain': {} }}

So what's going on here is I am iterating over a copy of a dictionary rather than iterating over the dictionary itself. With this method, you are able to remove elements as needed.

set font size in jquery

You can try another way like that:

<div class="content">
        Australia
    </div>

jQuery code:

$(".content").css({
    background: "#d1d1d1",
    fontSize: "30px"
})

Now you can add more css property as you want.

Are there any free Xml Diff/Merge tools available?

A7Soft provide XML comparison tools freeware and shareware:

http://www.a7soft.com

lvalue required as left operand of assignment error when using C++

It is just a typo(I guess)-

p+=1;

instead of p +1=p; is required .

As name suggest lvalue expression should be left-hand operand of the assignment operator.

TestNG ERROR Cannot find class in classpath

I was facing the same issue and what I tried is as below.

  1. Clean the project (Right click on pom.xml and clean)
  2. And update the maven project (Project > Maven > Update Maven Project)

This solved the issue.

Check if a value is in an array (C#)

Something like this?

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
PrinterSetup(printer);

// redefine PrinterSetup this way:
public void PrinterSetup(string[] printer)
{
    foreach (p in printer.Where(c => c == "jupiter"))
    {
        Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
    }
}

How to delete stuff printed to console by System.out.println()?

There are two different ways to clear the terminal in BlueJ. You can get BlueJ to automatically clear the terminal before every interactive method call. To do this, activate the 'Clear screen at method call' option in the 'Options' menu of the terminal. You can also clear the terminal programmatically from within your program. Printing a formfeed character (Unicode 000C) clears the BlueJ terminal, for example:

System.out.print('\u000C');

Remove a character at a certain position in a string - javascript

var str = 'Hello World',
    i = 3,
    result = str.substr(0, i-1)+str.substring(i);

alert(result);

Value of i should not be less then 1.

Compute a confidence interval from sample data

Start with looking up the z-value for your desired confidence interval from a look-up table. The confidence interval is then mean +/- z*sigma, where sigma is the estimated standard deviation of your sample mean, given by sigma = s / sqrt(n), where s is the standard deviation computed from your sample data and n is your sample size.

Difference between left join and right join in SQL Server

I feel we may require AND condition in where clause of last figure of Outer Excluding JOIN so that we get the desired result of A Union B Minus A Interaction B. I feel query needs to be updated to

SELECT <select_list>
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL AND B.Key IS NULL

If we use OR , then we will get all the results of A Union B

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

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

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

How can I replace non-printable Unicode characters in Java?

I propose it remove the non printable characters like below instead of replacing it

private String removeNonBMPCharacters(final String input) {
    StringBuilder strBuilder = new StringBuilder();
    input.codePoints().forEach((i) -> {
        if (Character.isSupplementaryCodePoint(i)) {
            strBuilder.append("?");
        } else {
            strBuilder.append(Character.toChars(i));
        }
    });
    return strBuilder.toString();
}

How to convert a structure to a byte array in C#?

This is fairly easy, using marshalling.

Top of file

using System.Runtime.InteropServices

Function

byte[] getBytes(CIFSPacket str) {
    int size = Marshal.SizeOf(str);
    byte[] arr = new byte[size];

    IntPtr ptr = Marshal.AllocHGlobal(size);
    Marshal.StructureToPtr(str, ptr, true);
    Marshal.Copy(ptr, arr, 0, size);
    Marshal.FreeHGlobal(ptr);
    return arr;
}

And to convert it back:

CIFSPacket fromBytes(byte[] arr) {
    CIFSPacket str = new CIFSPacket();

    int size = Marshal.SizeOf(str);
    IntPtr ptr = Marshal.AllocHGlobal(size);

    Marshal.Copy(arr, 0, ptr, size);

    str = (CIFSPacket)Marshal.PtrToStructure(ptr, str.GetType());
    Marshal.FreeHGlobal(ptr);

    return str;
}

In your structure, you will need to put this before a string

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public string Buffer;

And make sure SizeConst is as big as your biggest possible string.

And you should probably read this: http://msdn.microsoft.com/en-us/library/4ca6d5z7.aspx

Android Device not recognized by adb

Try use PdaNet. you can download it from here

It installs missing drivers when you plugin your device.

Obviously make sure you "debug usb" option in "developers options" is on.

Another thing, it's important to uninstall any device's installed driver before using it.

Importing lodash into angular2 + typescript application

Please note that npm install --save will foster whatever dependency your app requires in production code.
As for "typings", it is only required by TypeScript, which is eventually transpiled in JavaScript. Therefore, you probably do not want to have them in production code. I suggest to put it in your project's devDependencies instead, by using

npm install --save-dev @types/lodash

or

npm install -D @types/lodash

(see Akash post for example). By the way, it's the way it is done in ng2 tuto.

Alternatively, here is how your package.json could look like:

{
    "name": "my-project-name",
    "version": "my-project-version",
    "scripts": {whatever scripts you need: start, lite, ...},
    // here comes the interesting part
    "dependencies": {
       "lodash": "^4.17.2"
    }
    "devDependencies": {
        "@types/lodash": "^4.14.40"
    }
}

just a tip

The nice thing about npm is that you can start by simply do an npm install --save or --save-dev if you are not sure about the latest available version of the dependency you are looking for, and it will automatically set it for you in your package.json for further use.

cleanup php session files

Debian/Ubuntu handles this with a cronjob defined in /etc/cron.d/php5

# /etc/cron.d/php5: crontab fragment for php5
#  This purges session files older than X, where X is defined in seconds
#  as the largest value of session.gc_maxlifetime from all your php.ini
#  files, or 24 minutes if not defined.  See /usr/lib/php5/maxlifetime

# Look for and purge old sessions every 30 minutes
09,39 *     * * *     root   [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm

The maxlifetime script simply returns the number of minutes a session should be kept alive by checking php.ini, it looks like this

#!/bin/sh -e

max=1440

for ini in /etc/php5/*/php.ini; do
        cur=$(sed -n -e 's/^[[:space:]]*session.gc_maxlifetime[[:space:]]*=[[:space:]]*\([0-9]\+\).*$/\1/p' $ini 2>/dev/null || true);
        [ -z "$cur" ] && cur=0
        [ "$cur" -gt "$max" ] && max=$cur
done

echo $(($max/60))

exit 0

How to generate a random string of 20 characters

You may use the class java.util.Random with method

char c = (char)(rnd.nextInt(128-32))+32 

20x to get Bytes, which you interpret as ASCII. If you're fine with ASCII.

32 is the offset, from where the characters are printable in general.

What SOAP client libraries exist for Python, and where is the documentation for them?

As I suggested here I recommend you roll your own. It's actually not that difficult and I suspect that's the reason there aren't better Python SOAP libraries out there.

Relative paths based on file location instead of current working directory

@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.

This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:


Linux / GNU readlink solution:

If your script needs to run on Linux only or you know that GNU readlink is in the $PATH, use readlink -f, which conveniently resolves a symlink to its ultimate target:

 scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")

Note that GNU readlink has 3 related options for resolving a symlink to its ultimate target's full path: -f (--canonicalize), -e (--canonicalize-existing), and -m (--canonicalize-missing) - see man readlink.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f here, because it is the most well-known one.


Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):

If your script must run on any platform that:

  • has a readlink utility, but lacks the -f option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.

    • macOS uses an older version of the BSD implementation of readlink; note that recent versions of FreeBSD/PC-BSD do support -f.
  • does not even have readlink, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).

The following solution, inspired by https://stackoverflow.com/a/1116890/45375, defines helper shell function, rreadlink(), which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink's -e option, which is similar to the -f option, except that the ultimate target must exist.

Note: The function is a bash function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh), see here.

  • If readlink is available, it is used (without options) - true on most modern platforms.

  • Otherwise, the output from ls -l is parsed, which is the only POSIX-compliant way to determine a symlink's target.
    Caveat: this will break if a filename or path contains the literal substring -> - which is unlikely, however.
    (Note that platforms that lack readlink may still provide other, non-POSIX methods for resolving a symlink; e.g., @Charles Duffy mentions HP-UX's find utility supporting the %l format char. with its -printf primary; in the interest of brevity the function does NOT try to detect such cases.)

  • An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink; on other platforms (assuming they have bash), follow the manual installation instructions.

If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.

#!/usr/bin/env bash

# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...

  local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH= 

  # Since we'll be using `command` below for a predictable execution
  # environment, we make sure that it has its original meaning.
  { \unalias command; \unset -f command; } &>/dev/null

  while :; do # Resolve potential symlinks until the ultimate target is found.
      [[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
      command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
      fname=$(command basename -- "$target") # Extract filename.
      [[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
      if [[ -L $fname ]]; then
        # Extract [next] target path, which is defined
        # relative to the symlink's own directory.
        if [[ -n $readlinkexe ]]; then # Use `readlink`.
          target=$("$readlinkexe" -- "$fname")
        else # `readlink` utility not available.
          # Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant 
          # way to determine a symlink's target. Hypothetically, this can break with
          # filenames containig literal ' -> ' and embedded newlines.
          target=$(command ls -l -- "$fname")
          target=${target#* -> }
        fi
        continue # Resolve [next] symlink target.
      fi
      break # Ultimate target reached.
  done
  targetDir=$(command pwd -P) # Get canonical dir. path
  # Output the ultimate target's canonical path.
  # Note that we manually resolve paths ending in /. and /.. to make sure we
  # have a normalized path.
  if [[ $fname == '.' ]]; then
    command printf '%s\n' "${targetDir%/}"
  elif  [[ $fname == '..' ]]; then
    # Caveat: something like /var/.. will resolve to /private (assuming
    # /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
    command printf '%s\n' "$(command dirname -- "${targetDir}")"
  else
    command printf '%s\n' "${targetDir%/}/$fname"
  fi
)

# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")

Detect if range is empty

This single line works better imho:

Application.Evaluate("SUMPRODUCT(--(E10:E14<>""""))=0")

in this case, it evaluates if range E10:E14 is empty.

Node.js request CERT_HAS_EXPIRED

Try to temporarily modify request.js and harcode everywhere rejectUnauthorized = true, but it would be better to get the certificate extended as a long-term solution.

Search all of Git history for a string?

Try the following commands to search the string inside all previous tracked files:

git log --patch  | less +/searching_string

or

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

which needs to be run from the parent directory where you'd like to do the searching.

gradle build fails on lint task

As for me, it's a bad and quick solution for your problem :

android { 
  lintOptions { 
    abortOnError false 
  }
}

Better solution is solving problem in your code, because lint tool checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization.

This problem most frequently occurring when:

  • Layout include unresolved symbols or missing some attribute
  • Other structural issues, such as use of deprecated elements or API calls that are not supported by the target API versions, might lead to code failing to run correctly.

Find your bugs by Inspect Code in Android Studio: Improve Your Code with Lint

Max retries exceeded with URL in requests

What happened here is that itunes server refuses your connection (you're sending too many requests from same ip address in short period of time)

Max retries exceeded with url: /in/app/adobe-reader/id469337564?mt=8

error trace is misleading it should be something like "No connection could be made because the target machine actively refused it".

There is an issue at about python.requests lib at Github, check it out here

To overcome this issue (not so much an issue as it is misleading debug trace) you should catch connection related exceptions like so:

try:
    page1 = requests.get(ap)
except requests.exceptions.ConnectionError:
    r.status_code = "Connection refused"

Another way to overcome this problem is if you use enough time gap to send requests to server this can be achieved by sleep(timeinsec) function in python (don't forget to import sleep)

from time import sleep

All in all requests is awesome python lib, hope that solves your problem.

How to do a Jquery Callback after form submit?

You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.

But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:

  • override the default submit action (thanks to the passed in event object, that has a preventDefault method)
  • grab all necessary values from the form
  • fire off an HTTP request
  • handle the response to the request

First, you'll have to cancel the form submit action like so:

$("#myform").submit(function(event) {
    // Cancels the form's submit action.
    event.preventDefault();
});

And then, grab the value of the data. Let's just assume you have one text box.

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();
});

And then fire off a request. Let's just assume it's a POST request.

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();

    // I like to use defers :)
    deferred = $.post("http://somewhere.com", { val: val });

    deferred.success(function () {
        // Do your stuff.
    });

    deferred.error(function () {
        // Handle any errors here.
    });
});

And this should about do it.

Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.

Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.

$.post("http://somewhere.com", { val: val }, function () {
    // Start partying here.
}, function () {
    // Handle the bad news here.
});

Check status of one port on remote host

In Command Prompt, you can use the command telnet.. For Example, to connect to IP 192.168.10.1 with port 80,

telnet 192.168.10.1 80

To enable telnet in Windows 7 and above click. From the linked article, enable telnet through control panel -> programs and features -> windows features -> telnet client, or just run this in an admin prompt:

dism /online /Enable-Feature /FeatureName:TelnetClient

How do I make the text box bigger in HTML/CSS?

.textbox {
    height: 40px;
}

<div id=signin>  
    <input type="text" class="textbox" size="25%" height="50"/></br>
<input type="text" class="textbox" size="25%" height="50"/>

Make the font size larger and add height (or line height to the input boxes) I would not recommend adding those size and height attributes in the HTML as that can be handled by CSS. I have made a class text-box that can be used for multiple input boxes

How do I define global variables in CoffeeScript?

If you're a bad person (I'm a bad person.), you can get as simple as this: (->@)()

As in,

(->@)().im_a_terrible_programmer = yes
console.log im_a_terrible_programmer

This works, because when invoking a Reference to a Function ‘bare’ (that is, func(), instead of new func() or obj.func()), something commonly referred to as the ‘function-call invocation pattern’, always binds this to the global object for that execution context.

The CoffeeScript above simply compiles to (function(){ return this })(); so we're exercising that behavior to reliably access the global object.

Save PHP array to MySQL?

Instead of saving it to the database, save it to a file and then call it later.

What many php apps do (like sugarcrm) is to just use var_export to echo all the data of the array to a file. This is what I use to save my configurations data:

private function saveConfig() {
    file_put_contents($this->_data['pathtocompileddata'],'<?php' . PHP_EOL . '$acs_confdata = ' . var_export($this->_data,true) . ';');        
}

I think this is a better way to save your data!

Convert pandas dataframe to NumPy array

Try this:

a = numpy.asarray(df)

Live search through table rows

Here is the pure Javascript version of it with LIVE search for ALL COLUMNS :

function search_table(){
  // Declare variables 
  var input, filter, table, tr, td, i;
  input = document.getElementById("search_field_input");
  filter = input.value.toUpperCase();
  table = document.getElementById("table_id");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td") ; 
    for(j=0 ; j<td.length ; j++)
    {
      let tdata = td[j] ;
      if (tdata) {
        if (tdata.innerHTML.toUpperCase().indexOf(filter) > -1) {
          tr[i].style.display = "";
          break ; 
        } else {
          tr[i].style.display = "none";
        }
      } 
    }
  }
}

What is the common header format of Python files?

I strongly favour minimal file headers, by which I mean just:

  • The hashbang (#! line) if this is an executable script
  • Module docstring
  • Imports, grouped in the standard way, eg:
  import os    # standard library
  import sys

  import requests  # 3rd party packages

  from mypackage import (  # local source
      mymodule,
      myothermodule,
  )

ie. three groups of imports, with a single blank line between them. Within each group, imports are sorted. The final group, imports from local source, can either be absolute imports as shown, or explicit relative imports.

Everything else is a waste of time, visual space, and is actively misleading.

If you have legal disclaimers or licencing info, it goes into a separate file. It does not need to infect every source code file. Your copyright should be part of this. People should be able to find it in your LICENSE file, not random source code.

Metadata such as authorship and dates is already maintained by your source control. There is no need to add a less-detailed, erroneous, and out-of-date version of the same info in the file itself.

I don't believe there is any other data that everyone needs to put into all their source files. You may have some particular requirement to do so, but such things apply, by definition, only to you. They have no place in “general headers recommended for everyone”.

How to use OR condition in a JavaScript IF statement?

here is my example:

if(userAnswer==="Yes"||"yes"||"YeS"){
 console.log("Too Bad!");   
}

This says that if the answer is Yes yes or YeS than the same thing will happen

How to Position a table HTML?

You would want to use CSS to achieve that.

say you have a table with the attribute id="my_table"

You would want to write the following in your css file

#my_table{
    margin-top:10px //moves your table 10pixels down
    margin-left:10px //moves your table 10pixels right
}

if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px to the style attribute in your table element like so

<table style="margin-top:10px; margin-left:10px;">
    ....
</table>

There are a lot of resources on the net describing CSS and HTML in detail

How to use JavaScript variables in jQuery selectors?

$("input").click(function(){
        var name = $(this).attr("name");
        $('input[name="' + name + '"]').hide();    
    });   

Also works with ID:

var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();

when, (sometimes)

$('input#' + id).hide();

does not work, as it should.

You can even do both:

$('input[name="' + name + '"][id="' + id + '"]').hide();

How to make a Bootstrap accordion collapse when clicking the header div?

All you need to do is to to use...

  • data-toggle="collapse"
  • data-target="#ElementToExpandOnClick"

...on the element you want to click to trigger the collapse/expand effect.

The element with data-toggle="collapse" will be the element to trigger the effect. The data-target attribute indicates the element that will expand when the effect is triggered.

Optionally you can set the data-parent if you want to create an accordion effect instead of independent collapsible, e.g.:

  • data-parent="#accordion"

I would also add the following CSS to the elements with data-toggle="collapse" if they aren't <a> tags, e.g.:

.panel-heading {
    cursor: pointer;
}

Here's a jsfiddle with the modified html from the Bootstrap 3 documentation.

how to open a url in python

On window

import os
os.system("start \"\" https://example.com")

On macOS

import os
os.system("open \"\" https://example.com")

On Linux

import os
os.system("xdg-open \"\" https://example.com")

Cross-Platform

import webbrowser

webbrowser.open('https://example.com')

Aborting a stash pop in Git

My use case: just tried popping onto the wrong branch and got conflicts. All I need is to undo the pop but keep it in the stash list so I can pop it out on the correct branch. I did this:

git reset HEAD --hard
git checkout my_correct_branch
git stash pop

Easy.

PHP replacing special characters like à->a, è->e

There's a much easier way to do this, using iconv - from the user notes, this seems to be what you want to do: characters transliteration

// PHP.net User notes
<?php
    $string = "?ABBASABAD";

    echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $string);
    // output: [nothing, and you get a notice]

    echo iconv('UTF-8', 'ISO-8859-1//IGNORE', $string);
    // output: ABBSBD

    echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $string);
    // output: ABBASABAD
    // Yay! That's what I wanted!
?>

Be very conscientious with your character encodings, so you are keeping the same encoding at all stages in the process - front end, form submission, encoding of the source files. Default encoding in PHP and in forms is ISO-8859-1, before PHP 5.4 where it changed to be UTF8 (finally!).

There's a couple of functions you can play around with for ideas. First is from CakePHP's inflector class, called slug:

public static function slug($string, $replacement = '_') {
    $quotedReplacement = preg_quote($replacement, '/');

    $merge = array(
        '/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
        '/\\s+/' => $replacement,
        sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
    );

    $map = self::$_transliteration + $merge;
    return preg_replace(array_keys($map), array_values($map), $string);
}

It depends on a self::$_transliteration array which is similar to what you were doing in your question - you can see the source for inflector on github.

Another is a function I use personally, which comes from here.

function slugify($text,$strict = false) {
    $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
    // replace non letter or digits by -
    $text = preg_replace('~[^\\pL\d.]+~u', '-', $text);

    // trim
    $text = trim($text, '-');
    setlocale(LC_CTYPE, 'en_GB.utf8');
    // transliterate
    if (function_exists('iconv')) {
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    }

    // lowercase
    $text = strtolower($text);
    // remove unwanted characters
    $text = preg_replace('~[^-\w.]+~', '', $text);
    if (empty($text)) {
        return 'empty_$';
    }
    if ($strict) {
        $text = str_replace(".", "_", $text);
    }
    return $text;
}

What those functions do is transliterate and create 'slugs' from arbitrary text input, which is a very very useful thing to have in your toolchest when making web apps. Hope this helps!

How can I parse JSON with C#?

Another native solution to this, which doesn't require any 3rd party libraries but a reference to System.Web.Extensions is the JavaScriptSerializer. This is not a new but a very unknown built-in features there since 3.5.

using System.Web.Script.Serialization;

..

JavaScriptSerializer serializer = new JavaScriptSerializer();
objectString = serializer.Serialize(new MyObject());

and back

MyObject o = serializer.Deserialize<MyObject>(objectString)

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

The problem was related to CORS. I noticed that there was another error in Chrome console:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 422.`

This means the response from backend server was missing Access-Control-Allow-Origin header even though backend nginx was configured to add those headers to the responses with add_header directive.

However, this directive only adds headers when response code is 20X or 30X. On error responses the headers were missing. I needed to use always parameter to make sure header is added regardless of the response code:

add_header 'Access-Control-Allow-Origin' 'http://localhost:4200' always;

Once the backend was correctly configured I could access actual error message in Angular code.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

How to select date from datetime column?

simple and best way to use date function

example

SELECT * FROM 
data 
WHERE date(datetime) = '2009-10-20' 

OR

SELECT * FROM 
data 
WHERE date(datetime ) >=   '2009-10-20'  && date(datetime )  <= '2009-10-20'

c++ integer->std::string conversion. Simple function?

Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).

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

<manifest xmlns:tools="http://schemas.android.com/tools" ... >
  <uses-sdk tools:overrideLibrary="nl.innovalor.ocr, nl.innovalor.corelib" />

I was facing the issue of conflict between different min sdk versions. So this solution worked for me.

Sql Server trigger insert values from new row into another table

try this for sql server

CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS

INSERT INTO yourDestinationTable
        (col1, col2    , col3, user_id, user_name)
    SELECT
        'a'  , default , null, user_id, user_name
        FROM inserted

go

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

The simplest general function to find the positive modulo would be this- It would work on both positive and negative values of x.

int modulo(int x,int N){
    return (x % N + N) %N;
}

How to choose the id generation strategy when using JPA and Hibernate

Basically, you have two major choices:

  • You can generate the identifier yourself, in which case you can use an assigned identifier.
  • You can use the @GeneratedValue annotation and Hibernate will assign the identifier for you.

For the generated identifiers you have two options:

  • UUID identifiers.
  • Numerical identifiers.

For numerical identifiers you have three options:

  • IDENTITY
  • SEQUENCE
  • TABLE

IDENTITY is only a good choice when you cannot use SEQUENCE (e.g. MySQL) because it disables JDBC batch updates.

SEQUENCE is the preferred option, especially when used with an identifier optimizer like pooled or pooled-lo.

TABLE is to be avoided since it uses a separate transaction to fetch the identifier and row-level locks which scales poorly.

How to save a Python interactive session?

After installing Ipython, and opening an Ipython session by running the command:

ipython

from your command line, just run the following Ipython 'magic' command to automatically log your entire Ipython session:

%logstart

This will create a uniquely named .py file and store your session for later use as an interactive Ipython session or for use in the script(s) of your choosing.

Select current element in jQuery

When the jQuery click event calls your event handler, it sets "this" to the object that was clicked on. To turn it into a jQuery object, just pass it to the "$" function: $(this). So, to get, for example, the next sibling element, you would do this inside the click handler:

var nextSibling = $(this).next();

Edit: After reading Kevin's comment, I realized I might be mistaken about what you want. If you want to do what he asked, i.e. select the corresponding link in the other div, you could use $(this).index() to get the clicked link's position. Then you would select the link in the other div by its position, for example with the "eq" method.

var $clicked = $(this);
var linkIndex = $clicked.index();
$clicked.parent().next().children().eq(linkIndex);

If you want to be able to go both ways, you will need some way of determining which div you are in so you know if you need "next()" or "prev()" after "parent()"

How to get a table cell value using jQuery?

If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:

$('#mytable tr').each(function() {
    var customerId = $(this).find(".customerIDCell").html();    
 });

Essentially this is the same as the other solutions (possibly because I copy-pasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a <span>, provided you keep the class attribute with it.

By the way, I think you could do it in one selector:

$('#mytable .customerIDCell').each(function() {
  alert($(this).html());
});

If that makes things easier.

How can I declare dynamic String array in Java

What your looking for is the DefaultListModel - Dynamic String List Variable.

Here is a whole class that uses the DefaultListModel as though it were the TStringList of Delphi. The difference is that you can add Strings to the list without limitation and you have the same ability at getting a single entry by specifying the entry int.

FileName: StringList.java

package YOUR_PACKAGE_GOES_HERE;

//This is the StringList Class by i2programmer
//You may delete these comments
//This code is offered freely at no requirements
//You may alter the code as you wish
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

public class StringList {

    public static String OutputAsString(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static Object OutputAsObject(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static int OutputAsInteger(DefaultListModel list, int entry) {
        return Integer.parseInt(list.getElementAt(entry).toString());
    }

    public static double OutputAsDouble(DefaultListModel list, int entry) {
        return Double.parseDouble(list.getElementAt(entry).toString());
    }

    public static byte OutputAsByte(DefaultListModel list, int entry) {
        return Byte.parseByte(list.getElementAt(entry).toString());
    }

    public static char OutputAsCharacter(DefaultListModel list, int entry) {
        return list.getElementAt(entry).toString().charAt(0);
    }

    public static String GetEntry(DefaultListModel list, int entry) {
        String result = "";
        result = list.getElementAt(entry).toString();
        return result;
    }

    public static void AddEntry(DefaultListModel list, String entry) {
        list.addElement(entry);
    }

    public static void RemoveEntry(DefaultListModel list, int entry) {
        list.removeElementAt(entry);
    }

    public static DefaultListModel StrToList(String input, String delimiter) {
        DefaultListModel dlmtemp = new DefaultListModel();
        input = input.trim();
        delimiter = delimiter.trim();
        while (input.toLowerCase().contains(delimiter.toLowerCase())) {
            int index = input.toLowerCase().indexOf(delimiter.toLowerCase());
            dlmtemp.addElement(input.substring(0, index).trim());
            input = input.substring(index + delimiter.length(), input.length()).trim();
        }
        return dlmtemp;
    }

    public static String ListToStr(DefaultListModel list, String delimiter) {
        String result = "";
        for (int i = 0; i < list.size(); i++) {
            result = list.getElementAt(i).toString() + delimiter;
        }
        result = result.trim();
        return result;
    }

    public static String LoadFile(String inputfile) throws IOException {
        int len;
        char[] chr = new char[4096];
        final StringBuffer buffer = new StringBuffer();
        final FileReader reader = new FileReader(new File(inputfile));
        try {
            while ((len = reader.read(chr)) > 0) {
                buffer.append(chr, 0, len);
            }
        } finally {
            reader.close();
        }
        return buffer.toString();
    }

    public static void SaveFile(String outputfile, String outputstring) {
        try {
            FileWriter f0 = new FileWriter(new File(outputfile));
            f0.write(outputstring);
            f0.flush();
            f0.close();
        } catch (IOException ex) {
            Logger.getLogger(StringList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

OutputAs methods are for outputting an entry as int, double, etc... so that you don't have to convert from string on the other side.

SaveFile & LoadFile are to save and load strings to and from files.

StrToList & ListToStr are to place delimiters between each entry.

ex. 1<>2<>3<>4<> if "<>" is the delimiter and 1 2 3 & 4 are the entries.

AddEntry & GetEntry are to add and get strings to and from the DefaultListModel.

RemoveEntry is to delete a string from the DefaultListModel.

You use the DefaultListModel instead of an array here like this:

DefaultListModel list = new DefaultListModel();
//now that you have a list, you can run it through the above class methods.