Programs & Examples On #Keep alive

A feature of HTTP where the same connection is used for multiple requests, speeding up downloading of web pages with multiple resources.

How to keep an iPhone app running on background fully operational

For running on stock iOS devices, make your app an audio player/recorder or a VOIP app, a legitimate one for submitting to the App store, or a fake one if only for your own use.

Even this won't make an app "fully operational" whatever that is, but restricted to limited APIs.

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

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

For Windows according to Microsoft docs

  • KeepAliveTime (REG_DWORD, milliseconds, by default is not set which means 7,200,000,000 = 2 hours) - analogue to tcp_keepalive_time
  • KeepAliveInterval (REG_DWORD, milliseconds, by default is not set which means 1,000 = 1 second) - analogue to tcp_keepalive_intvl
  • Since Windows Vista there is no analogue to tcp_keepalive_probes, value is fixed to 10 and cannot be changed

find all unchecked checkbox in jquery

You can use like this :

$(":checkbox:not(:checked)")

How to remove the default link color of the html hyperlink 'a' tag?

I had this challenge when I was working on a Rails 6 application using Bootstrap 4.

My challenge was that I didn't want this styling to override the default link styling in the application.

So I created a CSS file called custom.css or custom.scss.

And then defined a new CSS rule with the following properties:

.remove_link_colour {
  a, a:hover, a:focus, a:active {
      color: inherit;
      text-decoration: none;
  }
}

Then I called this rule wherever I needed to override the default link styling.

<div class="product-card__buttons">
  <button class="btn btn-success remove_link_colour" type="button"><%= link_to 'Edit', edit_product_path(product) %></button>
  <button class="btn btn-danger remove_link_colour" type="button"><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></button>
</div>

This solves the issue of overriding the default link styling and removes the default colour, hover, focus, and active styling in the buttons only in places where I call the CSS rule.

That's all.

I hope this helps

How do I find out what type each object is in a ArrayList<Object>?

If you expect the data to be numeric in some form, and all you are interested in doing is converting the result to a numeric value, I would suggest:

for (Object o:list) {
  Double.parseDouble(o.toString);
}

Reading a string with spaces with sscanf

I guess this is what you want, it does exactly what you specified.

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char** argv) {
    int age;
    char* buffer;
    buffer = malloc(200 * sizeof(char));
    sscanf("19 cool kid", "%d cool %s", &age, buffer);
    printf("cool %s is %d years old\n", buffer, age);
    return 0;
}

The format expects: first a number (and puts it at where &age points to), then whitespace (zero or more), then the literal string "cool", then whitespace (zero or more) again, and then finally a string (and put that at whatever buffer points to). You forgot the "cool" part in your format string, so the format then just assumes that is the string you were wanting to assign to buffer. But you don't want to assign that string, only skip it.

Alternative, you could also have a format string like: "%d %s %s", but then you must assign another buffer for it (with a different name), and print it as: "%s %s is %d years old\n".

Android java.exe finished with non-zero exit value 1

Cleaning and rebuilding the project works for me. In Android studio:

Build -> Clean Project 
Build -> Rebuild Project

Refer link

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

I have Visual Studio Team System 2008 Development Edition, and had to remove all updates and Hotfixes:

  • Update KB972221
  • Hotfix KB973674
  • Hotfix KB971091

Reboot, then the following Hotfix appeared, which I then removed as per @riaraos' answer:

  • Hotfix KB952241

Before the Change/Remove would work!

Hope that helps someone else.

Disable browser's back button

Do not disable expected browser behaviour.

Make your pages handle the possibility of users going back a page or two; don't try to cripple their software.

Is there a destructor for Java?

Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.

There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error).

There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required...

How to load external webpage in WebView

I used this code that was cool. but have an error. " neterr_cleartext_not_permitted" show when you use this code then you will face this problem..

I got a solution of this.you have to add this in your AndroidManifest.xml near about Application

android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET" /> // ignore if you already added. outside of Application.

Is it possible to indent JavaScript code in Notepad++?

Try the notepad++ plugin JSMinNpp(Changed name to JSTool since 1.15)

http://www.sunjw.us/jsminnpp/

jQuery event handlers always execute in order they were bound - any way around this?

Here's a solution for jQuery 1.4.x (unfortunately, the accepted answer didn't work for jquery 1.4.1)

$.fn.bindFirst = function(name, fn) {
    // bind as you normally would
    // don't want to miss out on any jQuery magic
    this.bind(name, fn);

    // Thanks to a comment by @Martin, adding support for
    // namespaced events too.
    var handlers = this.data('events')[name.split('.')[0]];
    // take out the handler we just inserted from the end
    var copy = {1: null};

    var last = 0, lastValue = null;
    $.each(handlers, function(name, value) {
        //console.log(name + ": " + value);
        var isNumber = !isNaN(name);
        if(isNumber) {last = name; lastValue = value;};

        var key = isNumber ? (parseInt(name) + 1) : name;
        copy[key] = value;
    });
    copy[1] = lastValue;
    this.data('events')[name.split('.')[0]] = copy;
};

Where to install Android SDK on Mac OS X?

By default the android sdk installer path is ~/Library/Android/sdk/

How to enable scrolling on website that disabled scrolling?

Try ur code to add 'script' is last line or make test ur console (F12) enable scrolling

<script>
(function() {
  for (div=0; div < document.querySelectorAll('div').length; div++) {
    document.querySelectorAll('div')[div].style.overflow = "auto";
  };
})();
</script>

Extend contigency table with proportions (percentages)

If it's conciseness you're after, you might like:

prop.table(table(tips$smoker))

and then scale by 100 and round if you like. Or more like your exact output:

tbl <- table(tips$smoker)
cbind(tbl,prop.table(tbl))

If you wanted to do this for multiple columns, there are lots of different directions you could go depending on what your tastes tell you is clean looking output, but here's one option:

tblFun <- function(x){
    tbl <- table(x)
    res <- cbind(tbl,round(prop.table(tbl)*100,2))
    colnames(res) <- c('Count','Percentage')
    res
}

do.call(rbind,lapply(tips[3:6],tblFun))
       Count Percentage
Female    87      35.66
Male     157      64.34
No       151      61.89
Yes       93      38.11
Fri       19       7.79
Sat       87      35.66
Sun       76      31.15
Thur      62      25.41
Dinner   176      72.13
Lunch     68      27.87

If you don't like stack the different tables on top of each other, you can ditch the do.call and leave them in a list.

How to call function of one php file from another php file and pass parameters to it?

Yes include the first file into the second. That's all.

See an example below,

File1.php :

<?php
  function first($int, $string){ //function parameters, two variables.
    return $string;  //returns the second argument passed into the function
  }
?>

Now Using include (http://php.net/include) to include the File1.php to make its content available for use in the second file:

File2.php :

<?php
  include 'File1.php';
  echo first(1,"omg lol"); //returns omg lol;
?>

CSS: create white glow around image

Works like a charm!

.imageClass {
  -webkit-filter: drop-shadow(12px 12px 7px rgba(0,0,0,0.5));
}

Voila! That's it! Obviously this won't work in ie, but who cares...

How to specify line breaks in a multi-line flexbox layout?

For future questions, It's also possible to do it by using float property and clearing it in each 3 elements.

Here's an example I've made.

_x000D_
_x000D_
.grid {_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  margin: 8px;_x000D_
  width: 48px;_x000D_
  height: 48px;_x000D_
  background-color: #bdbdbd;_x000D_
  font-family: 'Helvetica', 'Arial', sans-serif;_x000D_
  font-size: 14px;_x000D_
  font-weight: 400;_x000D_
  line-height: 20px;_x000D_
  text-indent: 4px;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.cell:nth-child(3n) + .cell {_x000D_
  clear: both;_x000D_
}
_x000D_
<div class="grid">_x000D_
  <div class="cell">1</div>_x000D_
  <div class="cell">2</div>_x000D_
  <div class="cell">3</div>_x000D_
  <div class="cell">4</div>_x000D_
  <div class="cell">5</div>_x000D_
  <div class="cell">6</div>_x000D_
  <div class="cell">7</div>_x000D_
  <div class="cell">8</div>_x000D_
  <div class="cell">9</div>_x000D_
  <div class="cell">10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Where are Magento's log files located?

You can find them in /var/log within your root Magento installation

There will usually be two files by default, exception.log and system.log.

If the directories or files don't exist, create them and give them the correct permissions, then enable logging within Magento by going to System > Configuration > Developer > Log Settings > Enabled = Yes

Joining 2 SQL SELECT result sets into one

Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:

SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a

If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.

Allowing Untrusted SSL Certificates with HttpClient

If this is for a Windows Runtime application, then you have to add the self-signed certificate to the project and reference it in the appxmanifest.

The docs are here: http://msdn.microsoft.com/en-us/library/windows/apps/hh465031.aspx

Same thing if it's from a CA that's not trusted (like a private CA that the machine itself doesn't trust) -- you need to get the CA's public cert, add it as content to the app then add it to the manifest.

Once that's done, the app will see it as a correctly signed cert.

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

I personally like the following solution the most:

using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

... then before you do request getting the error, do the following

System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

Found this after consulting Luke's Solution

Binary numbers in Python

Below is a re-write of a previously posted function:

def addBinary(a, b): # Example: a = '11' + b =' 100' returns as '111'.    
    for ch in a: assert ch in {'0','1'}, 'bad digit: ' + ch    
    for ch in b: assert ch in {'0','1'}, 'bad digit: ' + ch    
    sumx = int(a, 2) + int(b, 2)    
    return bin(sumx)[2:]

finding and replacing elements in a list

Try using a list comprehension and the ternary operator.

>>> a=[1,2,3,1,3,2,1,1]
>>> [4 if x==1 else x for x in a]
[4, 2, 3, 4, 3, 2, 4, 4]

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

Same to me. The name of the mapping class was Mbean but the tag root name was mbean so I had to add the annotation:

@XmlRootElement(name="mbean")
public class MBean { ... }

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)

Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.

Using OR operator in a jquery if statement

Update: using .indexOf() to detect if stat value is one of arr elements

Pure JavaScript

_x000D_
_x000D_
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
    var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
_x000D_
_x000D_

Force table column widths to always be fixed regardless of contents

Try looking into the following CSS:

word-wrap:break-word;

Web browsers should not break-up "words" by default so what you are experiencing is normal behaviour of a browser. However you can override this with the word-wrap CSS directive.

You would need to set a width on the overall table then a width on the columns. "width:100%;" should also be OK depending on your requirements.

Using word-wrap may not be what you want however it is useful for showing all of the data without deforming the layout.

How to fix .pch file missing on build?

I know this topic is very old, but I was dealing with this in VS2015 recently and what helped was to deleted the build folders and re-build it. This may have happen due to trying to close the program or a program halting/freezing VS while building.

How can one use multi threading in PHP applications

While you can't thread, you do have some degree of process control in php. The two function sets that are useful here are:

Process control functions http://www.php.net/manual/en/ref.pcntl.php

POSIX functions http://www.php.net/manual/en/ref.posix.php

You could fork your process with pcntl_fork - returning the PID of the child. Then you can use posix_kill to despose of that PID.

That said, if you kill a parent process a signal should be sent to the child process telling it to die. If php itself isn't recognising this you could register a function to manage it and do a clean exit using pcntl_signal.

Accidentally committed .idea directory files into git

Its better to perform this over Master branch

Edit .gitignore file. Add the below line in it.

.idea

Remove .idea folder from remote repo. using below command.

git rm -r --cached .idea

For more info. reference: Removing Files from a Git Repository Without Actually Deleting Them

Stage .gitignore file. Using below command

git add .gitignore

Commit

git commit -m 'Removed .idea folder'

Push to remote

git push origin master

How to turn off INFO logging in Spark?

Edit your conf/log4j.properties file and Change the following line:

   log4j.rootCategory=INFO, console

to

    log4j.rootCategory=ERROR, console

Another approach would be to :

Fireup spark-shell and type in the following:

import org.apache.log4j.Logger
import org.apache.log4j.Level

Logger.getLogger("org").setLevel(Level.OFF)
Logger.getLogger("akka").setLevel(Level.OFF)

You won't see any logs after that.

What is an efficient way to implement a singleton pattern in Java?

Thread safe in Java 5+:

class Foo {
    private static volatile Bar bar = null;
    public static Bar getBar() {
        if (bar == null) {
            synchronized(Foo.class) {
                if (bar == null)
                    bar = new Bar();
            }
        }
        return bar;
    }
}

Pay attention to the volatile modifier here. :) It is important because without it, other threads are not guaranteed by the JMM (Java Memory Model) to see changes to its value. The synchronization does not take care of that--it only serializes access to that block of code.

@Bno's answer details the approach recommended by Bill Pugh (FindBugs) and is arguable better. Go read and vote up his answer too.

uppercase first character in a variable with bash

Using awk only

foo="uNcapItalizedstrIng"
echo $foo | awk '{print toupper(substr($0,0,1))tolower(substr($0,2))}'

How to push both key and value into an Array in Jquery

This code

var title = news.title;
var link = news.link;
arr.push({title : link});

is not doing what you think it does. What gets pushed is a new object with a single member named "title" and with link as the value ... the actual title value is not used. To save an object with two fields you have to do something like

arr.push({title:title, link:link});

or with recent Javascript advances you can use the shortcut

arr.push({title, link}); // Note: comma "," and not colon ":"

If instead you want the key of the object to be the content of the variable title you can use

arr.push({[title]: link}); // Note that title has been wrapped in brackets

MySQL how to join tables on two fields

SELECT * 
FROM t1
JOIN t2 USING (id, date)

perhaps you'll need to use INNEER JOIN or where t2.id is not null if you want results only matching both conditions

How to add text inside the doughnut chart using Chart.js?

You can also paste mayankcpdixit's code in onAnimationComplete option :

// ...
var myDoughnutChart = new Chart(ctx).Doughnut(data, {
    onAnimationComplete: function() {
        ctx.fillText(data[0].value + "%", 100 - 20, 100, 200);
    }
});

Text will be shown after animation

Pass table as parameter into sql server UDF

PASSING TABLE AS PARAMETER IN STORED PROCEDURE

Step 1:

CREATE TABLE [DBO].T_EMPLOYEES_DETAILS ( Id int, Name nvarchar(50), Gender nvarchar(10), Salary int )

Step 2:

CREATE TYPE EmpInsertType AS TABLE ( Id int, Name nvarchar(50), Gender nvarchar(10), Salary int )

Step 3:

/* Must add READONLY keyword at end of the variable */

CREATE PROC PRC_EmpInsertType @EmployeeInsertType EmpInsertType READONLY AS BEGIN INSERT INTO [DBO].T_EMPLOYEES_DETAILS SELECT * FROM @EmployeeInsertType END

Step 4:

DECLARE @EmployeeInsertType EmpInsertType

INSERT INTO @EmployeeInsertType VALUES(1,'John','Male',50000) INSERT INTO @EmployeeInsertType VALUES(2,'Praveen','Male',60000) INSERT INTO @EmployeeInsertType VALUES(3,'Chitra','Female',45000) INSERT INTO @EmployeeInsertType VALUES(4,'Mathy','Female',6600) INSERT INTO @EmployeeInsertType VALUES(5,'Sam','Male',50000)

EXEC PRC_EmpInsertType @EmployeeInsertType

=======================================

SELECT * FROM T_EMPLOYEES_DETAILS

OUTPUT

1 John Male 50000

2 Praveen Male 60000

3 Chitra Female 45000

4 Mathy Female 6600

5 Sam Male 50000

Check if a String contains numbers Java

public String hasNums(String str) {
        char[] nums = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        char[] toChar = new char[str.length()];
        for (int i = 0; i < str.length(); i++) {
            toChar[i] = str.charAt(i);
            for (int j = 0; j < nums.length; j++) {
                if (toChar[i] == nums[j]) { return str; }
            }
        }
        return "None";
    }

Setting a backgroundImage With React Inline Styles

try this it worked in my case

backgroundImage: `url("${Background}")`

Rounding integer division (instead of truncating)

The standard idiom for integer rounding up is:

int a = (59 + (4 - 1)) / 4;

You add the divisor minus one to the dividend.

Set HTML element's style property in javascript

Don't set the style object itself, set the background color property of the style object that is a property of the element.

And yes, even though you said no, jquery and tablesorter with its zebra stripe plugin can do this all for you in 3 lines of code.

And just setting the class attribute would be better since then you have non-hard-coded control over the styling which is more organized

How to split string using delimiter char using T-SQL?

You need a split function:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Function [dbo].[udf_Split]
(   
    @DelimitedList nvarchar(max)
    , @Delimiter nvarchar(2) = ','
)
RETURNS TABLE 
AS
RETURN 
    (
    With CorrectedList As
        (
        Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            + @DelimitedList
            + Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            As List
            , Len(@Delimiter) As DelimiterLen
        )
        , Numbers As 
        (
        Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
        From sys.columns As c1
            Cross Join sys.columns As c2
        )
    Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
        , Substring (
                    CL.List
                    , CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen     
                    , CharIndex(@Delimiter, CL.list, N.Value + 1)                           
                        - ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen ) 
                    ) As Value
    From CorrectedList As CL
        Cross Join Numbers As N
    Where N.Value <= DataLength(CL.List) / 2
        And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
    )

With your split function, you would then use Cross Apply to get the data:

Select T.Col1, T.Col2
    , Substring( Z.Value, 1, Charindex(' = ', Z.Value) - 1 ) As AttributeName
    , Substring( Z.Value, Charindex(' = ', Z.Value) + 1, Len(Z.Value) ) As Value
From Table01 As T
    Cross Apply dbo.udf_Split( T.Col3, '|' ) As Z

Where do I put image files, css, js, etc. in Codeigniter?

I just wanted to add that the problem may be even simpler -

I've been scratching my head for hours with this problem - I have read all the solutions, nothing worked. Then I managed to check the actual file name.

I had "image.jpg.jpg" rather than "image.jpg".

If you use $ ls public/..path to image assets../ you can quickly check the file names.

Sounds stupid but I never thought to look at something so simple as file name given the all the technical advice here.

PHPMailer AddAddress()

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddAddress($email, $name);
}

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

Get current domain

Try using this:

$_SERVER['SERVER_NAME']

Or parse :

$_SERVER['REQUEST_URI']

apache_request_headers()

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

You can use below code for your solution:-

public void Linq94() 
{ 
    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
    int[] numbersB = { 1, 3, 5, 7, 8 }; 

    var allNumbers = numbersA.Concat(numbersB); 

    Console.WriteLine("All numbers from both arrays:"); 
    foreach (var n in allNumbers) 
    { 
        Console.WriteLine(n); 
    } 
}

How to create a JavaScript callback for knowing when an image is loaded?

If you are using React.js, you could do this:

render() {

// ...

<img 
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}

src={item.src} key={item.key}
ref={item.key} />

// ... }

Where:

  • - onLoad (...) now will called with something like this: { src: "https://......png", key:"1" } you can use this as "key" to know which images is loaded correctly and which not.
  • - onError(...) it is the same but for errors.
  • - the object "item" is something like this { key:"..", src:".."} you can use to store the images' URL and key in order to use in a list of images.

  • Differences between "java -cp" and "java -jar"?

    I prefer the first version to start a java application just because it has less pitfalls ("welcome to classpath hell"). The second one requires an executable jar file and the classpath for that application has to be defined inside the jar's manifest (all other classpath declaration will be silently ignored...). So with the second version you'd have to look into the jar, read the manifest and try to find out if the classpath entries are valid from where the jar is stored... That's avoidable.

    I don't expect any performance advantages or disadvantages for either version. It's just telling the jvm which class to use for the main thread and where it can find the libraries.

    How does Task<int> become an int?

    Does an implicit conversion occur between Task<> and int?

    Nope. This is just part of how async/await works.

    Any method declared as async has to have a return type of:

    • void (avoid if possible)
    • Task (no result beyond notification of completion/failure)
    • Task<T> (for a logical result of type T in an async manner)

    The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length - you can't make the method just return int, as the actual method will return when it hits the first await expression which hasn't already completed. So instead, it returns a Task<int> which will complete when the async method itself completes.

    Note that await does the opposite - it unwraps a Task<T> to a T value, which is how this line works:

    string urlContents = await getStringTask;
    

    ... but of course it unwraps it asynchronously, whereas just using Result would block until the task had completed. (await can unwrap other types which implement the awaitable pattern, but Task<T> is the one you're likely to use most often.)

    This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:

    public async Task<int> AccessTheWebAndDoubleAsync()
    {
        var task = AccessTheWebAsync();
        int result = await task;
        return result * 2;
    }
    

    (Or simply return await AccessTheWebAsync() * 2; of course.)

    trace a particular IP and port

    Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.

    You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).

    How to move up a directory with Terminal in OS X

    To move up a directory, the quickest way would be to add an alias to ~/.bash_profile

    alias ..='cd ..'
    

    and then one would need only to type '..[return]'.

    Python 3 string.join() equivalent?

    Visit https://www.tutorialspoint.com/python/string_join.htm

    s=" "
    seq=["ab", "cd", "ef"]
    print(s.join(seq))
    

    ab cd ef

    s="."
    print(s.join(seq))
    

    ab.cd.ef

    How to select an element by classname using jqLite?

    Essentially, and as-noted by @kevin-b:

    // find('#id')
    angular.element(document.querySelector('#id'))
    
    //find('.classname'), assumes you already have the starting elem to search from
    angular.element(elem.querySelector('.classname'))
    

    Note: If you're looking to do this from your controllers you may want to have a look at the "Using Controllers Correctly" section in the developers guide and refactor your presentation logic into appropriate directives (such as <a2b ...>).

    How can I get the client's IP address in ASP.NET MVC?

    A lot of the code here was very helpful, but I cleaned it up for my purposes and added some tests. Here's what I ended up with:

    using System;
    using System.Linq;
    using System.Net;
    using System.Web;
    
    public class RequestHelpers
    {
        public static string GetClientIpAddress(HttpRequestBase request)
        {
            try
            {
                var userHostAddress = request.UserHostAddress;
    
                // Attempt to parse.  If it fails, we catch below and return "0.0.0.0"
                // Could use TryParse instead, but I wanted to catch all exceptions
                IPAddress.Parse(userHostAddress);
    
                var xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
    
                if (string.IsNullOrEmpty(xForwardedFor))
                    return userHostAddress;
    
                // Get a list of public ip addresses in the X_FORWARDED_FOR variable
                var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();
    
                // If we found any, return the last one, otherwise return the user host address
                return publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
            }
            catch (Exception)
            {
                // Always return all zeroes for any failure (my calling code expects it)
                return "0.0.0.0";
            }
        }
    
        private static bool IsPrivateIpAddress(string ipAddress)
        {
            // http://en.wikipedia.org/wiki/Private_network
            // Private IP Addresses are: 
            //  24-bit block: 10.0.0.0 through 10.255.255.255
            //  20-bit block: 172.16.0.0 through 172.31.255.255
            //  16-bit block: 192.168.0.0 through 192.168.255.255
            //  Link-local addresses: 169.254.0.0 through 169.254.255.255 (http://en.wikipedia.org/wiki/Link-local_address)
    
            var ip = IPAddress.Parse(ipAddress);
            var octets = ip.GetAddressBytes();
    
            var is24BitBlock = octets[0] == 10;
            if (is24BitBlock) return true; // Return to prevent further processing
    
            var is20BitBlock = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
            if (is20BitBlock) return true; // Return to prevent further processing
    
            var is16BitBlock = octets[0] == 192 && octets[1] == 168;
            if (is16BitBlock) return true; // Return to prevent further processing
    
            var isLinkLocalAddress = octets[0] == 169 && octets[1] == 254;
            return isLinkLocalAddress;
        }
    }
    

    And here are some NUnit tests against that code (I'm using Rhino Mocks to mock the HttpRequestBase, which is the M<HttpRequestBase> call below):

    using System.Web;
    using NUnit.Framework;
    using Rhino.Mocks;
    using Should;
    
    [TestFixture]
    public class HelpersTests : TestBase
    {
        HttpRequestBase _httpRequest;
    
        private const string XForwardedFor = "X_FORWARDED_FOR";
        private const string MalformedIpAddress = "MALFORMED";
        private const string DefaultIpAddress = "0.0.0.0";
        private const string GoogleIpAddress = "74.125.224.224";
        private const string MicrosoftIpAddress = "65.55.58.201";
        private const string Private24Bit = "10.0.0.0";
        private const string Private20Bit = "172.16.0.0";
        private const string Private16Bit = "192.168.0.0";
        private const string PrivateLinkLocal = "169.254.0.0";
    
        [SetUp]
        public void Setup()
        {
            _httpRequest = M<HttpRequestBase>();
        }
    
        [TearDown]
        public void Teardown()
        {
            _httpRequest = null;
        }
    
        [Test]
        public void PublicIpAndNullXForwardedFor_Returns_CorrectIp()
        {
            // Arrange
            _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
            _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);
    
            // Act
            var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
    
            // Assert
            ip.ShouldEqual(GoogleIpAddress);
        }
    
        [Test]
        public void PublicIpAndEmptyXForwardedFor_Returns_CorrectIp()
        {
            // Arrange
            _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
            _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(string.Empty);
    
            // Act
            var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
    
            // Assert
            ip.ShouldEqual(GoogleIpAddress);
        }
    
        [Test]
        public void MalformedUserHostAddress_Returns_DefaultIpAddress()
        {
            // Arrange
            _httpRequest.Stub(x => x.UserHostAddress).Return(MalformedIpAddress);
            _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);
    
            // Act
            var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
    
            // Assert
            ip.ShouldEqual(DefaultIpAddress);
        }
    
        [Test]
        public void MalformedXForwardedFor_Returns_DefaultIpAddress()
        {
            // Arrange
            _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
            _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MalformedIpAddress);
    
            // Act
            var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
    
            // Assert
            ip.ShouldEqual(DefaultIpAddress);
        }
    
        [Test]
        public void SingleValidPublicXForwardedFor_Returns_XForwardedFor()
        {
            // Arrange
            _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
            _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MicrosoftIpAddress);
    
            // Act
            var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
    
            // Assert
            ip.ShouldEqual(MicrosoftIpAddress);
        }
    
        [Test]
        public void MultipleValidPublicXForwardedFor_Returns_LastXForwardedFor()
        {
            // Arrange
            _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
            _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(GoogleIpAddress + "," + MicrosoftIpAddress);
    
            // Act
            var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
    
            // Assert
            ip.ShouldEqual(MicrosoftIpAddress);
        }
    
        [Test]
        public void SinglePrivateXForwardedFor_Returns_UserHostAddress()
        {
            // Arrange
            _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
            _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(Private24Bit);
    
            // Act
            var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
    
            // Assert
            ip.ShouldEqual(GoogleIpAddress);
        }
    
        [Test]
        public void MultiplePrivateXForwardedFor_Returns_UserHostAddress()
        {
            // Arrange
            _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
            const string privateIpList = Private24Bit + "," + Private20Bit + "," + Private16Bit + "," + PrivateLinkLocal;
            _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);
    
            // Act
            var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
    
            // Assert
            ip.ShouldEqual(GoogleIpAddress);
        }
    
        [Test]
        public void MultiplePublicXForwardedForWithPrivateLast_Returns_LastPublic()
        {
            // Arrange
            _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
            const string privateIpList = Private24Bit + "," + Private20Bit + "," + MicrosoftIpAddress + "," + PrivateLinkLocal;
            _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);
    
            // Act
            var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
    
            // Assert
            ip.ShouldEqual(MicrosoftIpAddress);
        }
    }
    

    How to iterate std::set?

    One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth element normal way will not work. example:

    std::vector<int > vec{1,2,3,4,5};
    int k=3;
    for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";
    
    
    std::unordered_set<int > s{1,2,3,4,5};
    int k=3;
    int index=0;
    auto itr=s.begin();
    while(true){
       if(index==k) break;
       cout<<*itr++<<" ";
       index++;
    }
    

    Server http:/localhost:8080 requires a user name and a password. The server says: XDB

    Just change your default port 8080 to something else like below example

    SQL> begin
     2   dbms_xdb.sethttpport('9090');
     3   end;
     4  /
    

    Why is "throws Exception" necessary when calling a function?

    Exception is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception must handle or declare it.

    Error:Unable to locate adb within SDK in Android Studio

    I know this is silly, but in my case while I was getting the same error message, just changing the USB cable used to connect the device fixed the problem :O

    Perhaps this might benefit someone else as well?!

    Why are static variables considered evil?

    Static variables most importantly creates problem with security of data (any time changed,anyone can change,direct access without object, etc.)

    For further info read this Thanks.

    How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

    To remove the frame of the chart

    for spine in plt.gca().spines.values():
      spine.set_visible(False)
    

    I hope this could work

    Python error: AttributeError: 'module' object has no attribute

    More accurately, your mod1 and lib directories are not modules, they are packages. The file mod11.py is a module.

    Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.

    >>> import lib
    >>> dir(lib)
    ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
    >>> import lib.pkg1
    >>> import lib.pkg1.mod11
    >>> lib.pkg1.mod11.mod12()
    mod12
    

    An alternative is to use the from syntax to "pull" a module from a package into you scripts namespace.

    >>> from lib.pkg1 import mod11
    

    Then reference the function as simply mod11.mod12().

    Unit Testing C Code

    There is CUnit

    And Embedded Unit is unit testing framework for Embedded C System. Its design was copied from JUnit and CUnit and more, and then adapted somewhat for Embedded C System. Embedded Unit does not require std C libs. All objects are allocated to const area.

    And Tessy automates the unit testing of embedded software.

    Undo git pull, how to bring repos to old state

    A more modern way to undo a merge is:

    git merge --abort
    

    And the slightly older way:

    git reset --merge
    

    The old-school way described in previous answers (warning: will discard all your local changes):

    git reset --hard
    

    But actually, it is worth noticing that git merge --abort is only equivalent to git reset --merge given that MERGE_HEAD is present. This can be read in the git help for merge command.

    git merge --abort is equivalent to git reset --merge when MERGE_HEAD is present.
    

    After a failed merge, when there is no MERGE_HEAD, the failed merge can be undone with git reset --merge but not necessarily with git merge --abort, so they are not only old and new syntax for the same thing. This is why i find git reset --merge to be much more useful in everyday work.

    CSS align one item right with flexbox

    To align one flex child to the right set it withmargin-left: auto;

    From the flex spec:

    One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

    .wrap div:last-child {
      margin-left: auto;
    }
    

    Updated fiddle

    _x000D_
    _x000D_
    .wrap {_x000D_
      display: flex;_x000D_
      background: #ccc;_x000D_
      width: 100%;_x000D_
      justify-content: space-between;_x000D_
    }_x000D_
    .wrap div:last-child {_x000D_
      margin-left: auto;_x000D_
    }_x000D_
    .result {_x000D_
      background: #ccc;_x000D_
      margin-top: 20px;_x000D_
    }_x000D_
    .result:after {_x000D_
      content: '';_x000D_
      display: table;_x000D_
      clear: both;_x000D_
    }_x000D_
    .result div {_x000D_
      float: left;_x000D_
    }_x000D_
    .result div:last-child {_x000D_
      float: right;_x000D_
    }
    _x000D_
    <div class="wrap">_x000D_
      <div>One</div>_x000D_
      <div>Two</div>_x000D_
      <div>Three</div>_x000D_
    </div>_x000D_
    _x000D_
    <!-- DESIRED RESULT -->_x000D_
    <div class="result">_x000D_
      <div>One</div>_x000D_
      <div>Two</div>_x000D_
      <div>Three</div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Note:

    You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1) which would push the last item all the way to the right. (Demo)

    The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.

    Demo

    _x000D_
    _x000D_
    .wrap {_x000D_
      display: flex;_x000D_
      background: #ccc;_x000D_
      width: 100%;_x000D_
      justify-content: space-between;_x000D_
    }_x000D_
    .wrap div {_x000D_
      border: 3px solid tomato;_x000D_
    }_x000D_
    .margin div:last-child {_x000D_
      margin-left: auto;_x000D_
    }_x000D_
    .grow div:nth-child(2) {_x000D_
      flex: 1;_x000D_
    }_x000D_
    .result {_x000D_
      background: #ccc;_x000D_
      margin-top: 20px;_x000D_
    }_x000D_
    .result:after {_x000D_
      content: '';_x000D_
      display: table;_x000D_
      clear: both;_x000D_
    }_x000D_
    .result div {_x000D_
      float: left;_x000D_
    }_x000D_
    .result div:last-child {_x000D_
      float: right;_x000D_
    }
    _x000D_
    <div class="wrap margin">_x000D_
      <div>One</div>_x000D_
      <div>Two</div>_x000D_
      <div>Three</div>_x000D_
    </div>_x000D_
    _x000D_
    <div class="wrap grow">_x000D_
      <div>One</div>_x000D_
      <div>Two</div>_x000D_
      <div>Three</div>_x000D_
    </div>_x000D_
    _x000D_
    <!-- DESIRED RESULT -->_x000D_
    <div class="result">_x000D_
      <div>One</div>_x000D_
      <div>Two</div>_x000D_
      <div>Three</div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    $watch'ing for data changes in an Angular directive

    Because if you want to trigger your data with deep of it,you have to pass 3th argument true of your listener.By default it's false and it meens that you function will trigger,only when your variable will change not it's field.

    how to import csv data into django models

    define class in models.py and a function in it.

    class all_products(models.Model):
        def get_all_products():
            items = []
            with open('EXACT FILE PATH OF YOUR CSV FILE','r') as fp:
                # You can also put the relative path of csv file
                # with respect to the manage.py file
                reader1 = csv.reader(fp, delimiter=';')
                for value in reader1:
                    items.append(value)
            return items
    

    You can access ith element in the list as items[i]

    Web.Config Debug/Release

    The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.

    In your .Debug/.Release files, you need to add the following parameter in your connection string fields:

    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"
    

    This will cause each connection string line to find the matching name and update the attributes accordingly.

    Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.

    Here's an example from one of my apps. Here's the web.config file section:

    <connectionStrings>
          <add name="EAF" connectionString="[Test Connection String]" />
    </connectionString>
    

    And here's the web.config.release section doing the proper transform:

    <connectionStrings>
          <add name="EAF" connectionString="[Prod Connection String]"
               xdt:Transform="SetAttributes"
               xdt:Locator="Match(name)" />
    </connectionStrings>
    

    One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.

    For more details you can see the MSDN documentation

    https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx

    Add MIME mapping in web.config for IIS Express

    I was having a problem getting my ASP.NET 5.0/MVC 6 app to serve static binary file types or browse virtual directories. It looks like this is now done in Configure() at startup. See http://docs.asp.net/en/latest/fundamentals/static-files.html for a quick primer.

    Show percent % instead of counts in charts of categorical variables

    Here is a workaround for faceted data. (The accepted answer by @Andrew does not work in this case.) The idea is to calculate the percentage value using dplyr and then to use geom_col to create the plot.

    library(ggplot2)
    library(scales)
    library(magrittr)
    library(dplyr)
    
    binwidth <- 30
    
    mtcars.stats <- mtcars %>%
      group_by(cyl) %>%
      mutate(bin = cut(hp, breaks=seq(0,400, binwidth), 
                   labels= seq(0+binwidth,400, binwidth)-(binwidth/2)),
             n = n()) %>%
      group_by(cyl, bin) %>%
      summarise(p = n()/n[1]) %>%
      ungroup() %>%
      mutate(bin = as.numeric(as.character(bin)))
    
    ggplot(mtcars.stats, aes(x = bin, y= p)) +  
      geom_col() + 
      scale_y_continuous(labels = percent) +
      facet_grid(cyl~.)
    

    This is the plot:

    enter image description here

    Java URLConnection Timeout

    Are you on Windows? The underlying socket implementation on Windows seems not to support the SO_TIMEOUT option very well. See also this answer: setSoTimeout on a client socket doesn't affect the socket

    Import and insert sql.gz file into database with putty

    Login into your server using a shell program like putty.

    Type in the following command on the command line

    zcat DB_File_Name.sql.gz | mysql -u username -p Target_DB_Name
    

    where

    DB_File_Name.sql.gz = full path of the sql.gz file to be imported

    username = your mysql username

    Target_DB_Name = database name where you want to import the database

    When you hit enter in the command line, it will prompt for password. Enter your MySQL password.

    You are done!

    HTML meta tag for content language

    Html5 also recommend to use <html lang="es-ES"> The small letter lang tag only specifies: language code The large letter specifies: country code

    This is really useful for ie.Chrome, when the browser is proposing to translate web content(ie google translate)

    How to convert unsigned long to string

    For a long value you need to add the length info 'l' and 'u' for unsigned decimal integer,

    as a reference of available options see sprintf

    #include <stdio.h>
    
        int main ()
        {
          unsigned long lval = 123;
          char buffer [50];
          sprintf (buffer, "%lu" , lval );
         }
    

    Cross-Origin Read Blocking (CORB)

    I encountered this problem because the format of the jsonp response from the server is wrong. The incorrect response is as follows.

    callback(["apple", "peach"])
    

    The problem is, the object inside callback should be a correct json object, instead of a json array. So I modified some server code and changed its format:

    callback({"fruit": ["apple", "peach"]})
    

    The browser happily accepted the response after the modification.

    Protecting cells in Excel but allow these to be modified by VBA script

    I selected the cells I wanted locked out in sheet1 and place the suggested code in the open_workbook() function and worked like a charm.

    ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _
    UserInterfaceOnly:=True
    

    Convert NSDate to String in iOS Swift

    DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:

    extension Date {  
      func asString(style: DateFormatter.Style) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = style
        return dateFormatter.string(from: self)
      }
    }
    

    This gives you the following styles:

    short, medium, long, full
    

    Example usage:

    let myDate = Date()
    myDate.asString(style: .full)   // Wednesday, January 10, 2018
    myDate.asString(style: .long)   // January 10, 2018
    myDate.asString(style: .medium) // Jan 10, 2018
    myDate.asString(style: .short)  // 1/10/18
    

    Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

    This is a more common error now as many projects are moving their master branch to another name like main, primary, default, root, reference, latest, etc, as discussed at Github plans to replace racially insensitive terms like ‘master’ and ‘whitelist’.

    To fix it, first find out what the project is now using, which you can find via their github, gitlab or other git server.

    Then do this to capture the current configuration:

    $ git branch -vv
    ...
    * master  968695b [origin/master] Track which contest a ballot was sampled for (#629)
    ...
    

    Find the line describing the master branch, and note whether the remote repo is called origin, upstream or whatever.

    Then using that information, change the branch name to the new one, e.g. if it says you're currently tracking origin/master, substitute main:

    git branch master --set-upstream-to origin/main
    

    You can also rename your own branch to avoid future confusion:

    git branch -m main
    

    How do I animate constraint changes?

    I appreciate the answer provided, but I think it would be nice to take it a bit further.

    The basic block animation from the documentation

    [containerView layoutIfNeeded]; // Ensures that all pending layout operations have been completed
    [UIView animateWithDuration:1.0 animations:^{
         // Make all constraint changes here
         [containerView layoutIfNeeded]; // Forces the layout of the subtree animation block and then captures all of the frame changes
    }];
    

    but really this is a very simplistic scenario. What if I want to animate subview constraints via the updateConstraints method?

    An animation block that calls the subviews updateConstraints method

    [self.view layoutIfNeeded];
    [self.subView setNeedsUpdateConstraints];
    [self.subView updateConstraintsIfNeeded];
    [UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionLayoutSubviews animations:^{
        [self.view layoutIfNeeded];
    } completion:nil];
    

    The updateConstraints method is overridden in the UIView subclass and must call super at the end of the method.

    - (void)updateConstraints
    {
        // Update some constraints
    
        [super updateConstraints];
    }
    

    The AutoLayout Guide leaves much to be desired but it is worth reading. I myself am using this as part of a UISwitch that toggles a subview with a pair of UITextFields with a simple and subtle collapse animation (0.2 seconds long). The constraints for the subview are being handled in the UIView subclasses updateConstraints methods as described above.

    Why can't I have "public static const string S = "stuff"; in my Class?

    A const member is considered static by the compiler, as well as implying constant value semantics, which means references to the constant might be compiled into the using code as the value of the constant member, instead of a reference to the member.

    In other words, a const member containing the value 10, might get compiled into code that uses it as the number 10, instead of a reference to the const member.

    This is different from a static readonly field, which will always be compiled as a reference to the field.

    Note, this is pre-JIT. When the JIT'ter comes into play, it might compile both these into the target code as values.

    Best way to style a TextBox in CSS

    your approach is pretty good...

    _x000D_
    _x000D_
    .myclass {_x000D_
        height: 20px;_x000D_
        position: relative;_x000D_
        border: 2px solid #cdcdcd;_x000D_
        border-color: rgba(0, 0, 0, .14);_x000D_
        background-color: AliceBlue;_x000D_
        font-size: 14px;_x000D_
    }
    _x000D_
    <input type="text" class="myclass" />
    _x000D_
    _x000D_
    _x000D_

    How to run mvim (MacVim) from Terminal?

    I'm adding Bard Park's comment here for that was the real answer for me:

    Since mvim is simply a shell script, you can download it directly from the MacVim source at GitHub here: http://raw.github.com/b4winckler/macvim/master/src/MacVim/mvim

    How to iterate through XML in Powershell?

    PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

    [xml]$xml = Get-Content $serviceStatePath
    $nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
    $nodes | ForEach-Object {$_.Node.'#text'}
    

    Or shorter

    [xml]$xml = Get-Content $serviceStatePath
    Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
      % {$_.Node.'#text'}
    

    How do I determine whether an array contains a particular value in Java?

    Arrays.asList(yourArray).contains(yourValue)
    

    Warning: this doesn't work for arrays of primitives (see the comments).


    Since you can now use Streams.

    String[] values = {"AB","BC","CD","AE"};
    boolean contains = Arrays.stream(values).anyMatch("s"::equals);
    

    To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.

    Example

    int[] a = {1,2,3,4};
    boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
    

    Passing by reference in C

    Short answer: Yes, C does implement parameter passing by reference using pointers.

    While implementing parameter passing, designers of programming languages use three different strategies (or semantic models): transfer data to the subprogram, receive data from the subprogram, or do both. These models are commonly known as in mode, out mode, and inout mode, correspondingly.

    Several models have been devised by language designers to implement these three elementary parameter passing strategies:

    Pass-by-Value (in mode semantics) Pass-by-Result (out mode semantics) Pass-by-Value-Result (inout mode semantics) Pass-by-Reference (inout mode semantics) Pass-by-Name (inout mode semantics)

    Pass-by-reference is the second technique for inout-mode parameter passing. Instead of copying data back and forth between the main routine and the subprogram, the runtime system sends a direct access path to the data for the subprogram. In this strategy the subprogram has direct access to the data effectively sharing the data with the main routine. The main advantage with this technique is that its absolutely efficient in time and space because there is no need to duplicate space and there is no data copying operations.

    Parameter passing implementation in C: C implements pass-by-value and also pass-by-reference (inout mode) semantics using pointers as parameters. The pointer is send to the subprogram and no actual data is copied at all. However, because a pointer is an access path to the data of the main routine, the subprogram may change the data in the main routine. C adopted this method from ALGOL68.

    Parameter passing implementation in C++: C++ also implements pass-by-reference (inout mode) semantics using pointers and also using a special kind of pointer, called reference type. Reference type pointers are implicitly dereferenced inside the subprogram but their semantics are also pass-by-reference.

    So the key concept here is that pass-by-reference implements an access path to the data instead of copying the data into the subprogram. Data access paths can be explicitly dereferenced pointers or auto dereferenced pointers (reference type).

    For more info please refer to the book Concepts of Programming Languages by Robert Sebesta, 10th Ed., Chapter 9.

    Send value of submit button when form gets posted

    The initial post mentioned buttons. You can also replace the input tags with buttons.

    <button type="submit" name="product" value="Tea">Tea</button>
    <button type="submit" name="product" value="Coffee">Coffee</button>
    

    The name and value attributes are required to submit the value when the form is submitted (the id attribute is not necessary in this case). The attribute type=submit specifies that clicking on this button causes the form to be submitted.

    When the server is handling the submitted form, $_POST['product'] will contain the value "Tea" or "Coffee" depending on which button was clicked.

    If you want you can also require the user to confirm before submitting the form (useful when you are implementing a delete button for example).

    <button type="submit" name="product" value="Tea" onclick="return confirm('Are you sure you want tea?');">Tea</button>
    <button type="submit" name="product" value="Coffee" onclick="return confirm('Are you sure you want coffee?');">Coffee</button>
    

    How to get a table creation script in MySQL Workbench?

    1. Open MySQL Workbench (6.3 CE)
    2. In "Navigator" select "Management"
    3. Then select "Data Export" (Here select the table whose create script you wish to export)
    4. In Drop down select "Dump Structure and Data"
    5. Select checkbox "Include Create Schema"
    6. Click the button "Start Export" Once export is complete it will display the location in which exported file is dumped in your system. Go to the location and open the exported file to find table creation script.

    Or Check https://dev.mysql.com/doc/workbench/en/wb-admin-export-import-management.html

    How to press/click the button using Selenium if the button does not have the Id?

    Use xpath selector (here's quick tutorial) instead of id:

    #python:
    from selenium.webdriver import Firefox
    
    YOUR_PAGE_URL = 'http://mypage.com/'
    NEXT_BUTTON_XPATH = '//input[@type="submit" and @title="next"]'
    
    browser = Firefox()
    browser.get(YOUR_PAGE_URL)
    
    button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
    button.click()
    

    Or, if you use "vanilla" Selenium, just use same xpath selector instead of button id:

    NEXT_BUTTON_XPATH = '//input[@type="submit" and @title="next"]'
    selenium.click(NEXT_BUTTON_XPATH)
    

    What and When to use Tuple?

    This is the most important thing to know about the Tuple type. Tuple is a class, not a struct. It thus will be allocated upon the managed heap. Each class instance that is allocated adds to the burden of garbage collection.

    Note: The properties Item1, Item2, and further do not have setters. You cannot assign them. The Tuple is immutable once created in memory.

    NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

    i had the same error while working with hibernate, i had added below dependency in my pom.xml that solved the problem

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.10</version>
        </dependency>
    

    reference https://mvnrepository.com/artifact/org.slf4j/slf4j-api

    Javascript to sort contents of select element

    This is a a recompilation of my 3 favorite answers on this board:

    • jOk's best and simplest answer.
    • Terry Porter's easy jQuery method.
    • SmokeyPHP's configurable function.

    The results are an easy to use, and easily configurable function.

    First argument can be a select object, the ID of a select object, or an array with at least 2 dimensions.

    Second argument is optional. Defaults to sorting by option text, index 0. Can be passed any other index so sort on that. Can be passed 1, or the text "value", to sort by value.

    Sort by text examples (all would sort by text):

     sortSelect('select_object_id');
     sortSelect('select_object_id', 0);
     sortSelect(selectObject);
     sortSelect(selectObject, 0);
    

    Sort by value (all would sort by value):

     sortSelect('select_object_id', 'value');
     sortSelect('select_object_id', 1);
     sortSelect(selectObject, 1);
    

    Sort any array by another index:

    var myArray = [
      ['ignored0', 'ignored1', 'Z-sortme2'],
      ['ignored0', 'ignored1', 'A-sortme2'],
      ['ignored0', 'ignored1', 'C-sortme2'],
    ];
    
    sortSelect(myArray,2);
    

    This last one will sort the array by index-2, the sortme's.

    Main sort function

    function sortSelect(selElem, sortVal) {
    
        // Checks for an object or string. Uses string as ID. 
        switch(typeof selElem) {
            case "string":
                selElem = document.getElementById(selElem);
                break;
            case "object":
                if(selElem==null) return false;
                break;
            default:
                return false;
        }
    
        // Builds the options list.
        var tmpAry = new Array();
        for (var i=0;i<selElem.options.length;i++) {
            tmpAry[i] = new Array();
            tmpAry[i][0] = selElem.options[i].text;
            tmpAry[i][1] = selElem.options[i].value;
        }
    
        // allows sortVal to be optional, defaults to text.
        switch(sortVal) {
            case "value": // sort by value
                sortVal = 1;
                break;
            default: // sort by text
                sortVal = 0;
        }
        tmpAry.sort(function(a, b) {
            return a[sortVal] == b[sortVal] ? 0 : a[sortVal] < b[sortVal] ? -1 : 1;
        });
    
        // removes all options from the select.
        while (selElem.options.length > 0) {
            selElem.options[0] = null;
        }
    
        // recreates all options with the new order.
        for (var i=0;i<tmpAry.length;i++) {
            var op = new Option(tmpAry[i][0], tmpAry[i][1]);
            selElem.options[i] = op;
        }
    
        return true;
    }
    

    Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

    Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
    See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds):

    Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.

    The documentation now reads:

    --depth <depth>::
    

    Create a 'shallow' clone with a history truncated to the specified number of revisions.

    That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
    smart-http now supports shallow fetch/clone too.

    All the details are in "shallow.c: the 8 steps to select new commits for .git/shallow".

    Update June 2015: Git 2.5 will even allow for fetching a single commit!
    (Ultimate shallow case)


    Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
    See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
    (Merged by Junio C Hamano -- gitster -- in commit 7e3e80a, 20 Jan 2016)

    This is "Documentation/user-manual.txt"

    A <<def_shallow_clone,shallow clone>> is created by specifying the git-clone --depth switch.
    The depth can later be changed with the git-fetch --depth switch, or full history restored with --unshallow.

    Merging inside a <<def_shallow_clone,shallow clone>> will work as long as a merge base is in the recent history.
    Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
    This limitation may make such a repository unsuitable to be used in merge based workflows.

    Update 2020:

    • git 2.11.1 introduced option git fetch --shallow-exclude= to prevent fetching all history
    • git 2.11.1 introduced option git fetch --shallow-since= to prevent fetching old commits.

    For more on the shallow clone update process, see "How to update a git shallow clone?".


    As commented by Richard Michael:

    to backfill history: git pull --unshallow

    And Olle Härstedt adds in the comments:

    To backfill part of the history: git fetch --depth=100.

    How to test for $null array in PowerShell

    if($foo -eq $null) { "yes" } else { "no" }
    
    help about_comparison_operators 
    

    displays help and includes this text:

    All comparison operators except the containment operators (-contains, -notcontains) and type operators (-is, -isnot) return a Boolean value when the input to the operator (the value on the left side of the operator) is a single value (a scalar). When the input is a collection of values, the containment operators and the type operators return any matching values. If there are no matches in a collection, these operators do not return anything. The containment operators and type operators always return a Boolean value.

    JPA and Hibernate - Criteria vs. JPQL or HQL

    HQL is much easier to read, easier to debug using tools like the Eclipse Hibernate plugin, and easier to log. Criteria queries are better for building dynamic queries where a lot of the behavior is determined at runtime. If you don't know SQL, I could understand using Criteria queries, but overall I prefer HQL if I know what I want upfront.

    How can I make a menubar fixed on the top while scrolling

    This should get you started

     <div class="menuBar">
            <img class="logo" src="logo.jpg"/>
            <div class="nav"> 
                <ul>
                    <li>Menu1</li>
                    <li>Menu 2</li>
                    <li>Menu 3</li>
                </ul> 
            </div>
        </div>
    
    
    
    body{
        margin-top:50px;}
    .menuBar{
        width:100%;
        height:50px;
        display:block;
        position:absolute;
        top:0;
        left:0;
        }
    .logo{
        float:left;
        }
    .nav{
        float:right;
        margin-right:10px;}
    .nav ul li{
        list-style:none;
        float:left;
        }
    

    What is the best workaround for the WCF client `using` block issue?

    Below is an enhanced version of the source from the question and extended to cache multiple channel factories and attempt to look up the endpoint in the configuration file by contract name.

    It uses .NET 4 (specifically: contravariance, LINQ, var):

    /// <summary>
    /// Delegate type of the service method to perform.
    /// </summary>
    /// <param name="proxy">The service proxy.</param>
    /// <typeparam name="T">The type of service to use.</typeparam>
    internal delegate void UseServiceDelegate<in T>(T proxy);
    
    /// <summary>
    /// Wraps using a WCF service.
    /// </summary>
    /// <typeparam name="T">The type of service to use.</typeparam>
    internal static class Service<T>
    {
        /// <summary>
        /// A dictionary to hold looked-up endpoint names.
        /// </summary>
        private static readonly IDictionary<Type, string> cachedEndpointNames = new Dictionary<Type, string>();
    
        /// <summary>
        /// A dictionary to hold created channel factories.
        /// </summary>
        private static readonly IDictionary<string, ChannelFactory<T>> cachedFactories =
            new Dictionary<string, ChannelFactory<T>>();
    
        /// <summary>
        /// Uses the specified code block.
        /// </summary>
        /// <param name="codeBlock">The code block.</param>
        internal static void Use(UseServiceDelegate<T> codeBlock)
        {
            var factory = GetChannelFactory();
            var proxy = (IClientChannel)factory.CreateChannel();
            var success = false;
    
            try
            {
                using (proxy)
                {
                    codeBlock((T)proxy);
                }
    
                success = true;
            }
            finally
            {
                if (!success)
                {
                    proxy.Abort();
                }
            }
        }
    
        /// <summary>
        /// Gets the channel factory.
        /// </summary>
        /// <returns>The channel factory.</returns>
        private static ChannelFactory<T> GetChannelFactory()
        {
            lock (cachedFactories)
            {
                var endpointName = GetEndpointName();
    
                if (cachedFactories.ContainsKey(endpointName))
                {
                    return cachedFactories[endpointName];
                }
    
                var factory = new ChannelFactory<T>(endpointName);
    
                cachedFactories.Add(endpointName, factory);
                return factory;
            }
        }
    
        /// <summary>
        /// Gets the name of the endpoint.
        /// </summary>
        /// <returns>The name of the endpoint.</returns>
        private static string GetEndpointName()
        {
            var type = typeof(T);
            var fullName = type.FullName;
    
            lock (cachedFactories)
            {
                if (cachedEndpointNames.ContainsKey(type))
                {
                    return cachedEndpointNames[type];
                }
    
                var serviceModel = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).SectionGroups["system.serviceModel"] as ServiceModelSectionGroup;
    
                if ((serviceModel != null) && !string.IsNullOrEmpty(fullName))
                {
                    foreach (var endpointName in serviceModel.Client.Endpoints.Cast<ChannelEndpointElement>().Where(endpoint => fullName.EndsWith(endpoint.Contract)).Select(endpoint => endpoint.Name))
                    {
                        cachedEndpointNames.Add(type, endpointName);
                        return endpointName;
                    }
                }
            }
    
            throw new InvalidOperationException("Could not find endpoint element for type '" + fullName + "' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.");
        }
    }
    

    Add timer to a Windows Forms application

    Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html

    Then add a button or something on the form and inside its event, just open this app ie:

    {

    Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");

    }

    Create parameterized VIEW in SQL Server 2008

    no. You can use UDF in which you can pass parameters.

    How to access a RowDataPacket object

    Solution

    Just do: JSON.stringify(results)

    How to set a class attribute to a Symfony2 form input

    You can do this from the twig template:

    {{ form_widget(form.birthdate, { 'attr': {'class': 'calendar'} }) }}
    

    From http://symfony.com/doc/current/book/forms.html#rendering-each-field-by-hand

    How to avoid pressing Enter with getchar() for reading a single character only?

    You could include the 'ncurses' library, and use getch() instead of getchar().

    Cannot read property length of undefined

    The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

    Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

    PHP, display image with Header()

    Though weirdly named, you can use the getimagesize() function. This will also give you mime information:

    Array
    (
        [0] => 295 // width
        [1] => 295 // height
        [2] => 3 // http://php.net/manual/en/image.constants.php
        [3] => width="295" height="295" // width and height as attr's
        [bits] => 8
        [mime] => image/png
    )
    

    How can I inspect the file system of a failed `docker build`?

    Debugging build step failures is indeed very annoying.

    The best solution I have found is to make sure that each step that does real work succeeds, and adding a check after those that fails. That way you get a committed layer that contains the outputs of the failed step that you can inspect.

    A Dockerfile, with an example after the # Run DB2 silent installer line:

    #
    # DB2 10.5 Client Dockerfile (Part 1)
    #
    # Requires
    #   - DB2 10.5 Client for 64bit Linux ibm_data_server_runtime_client_linuxx64_v10.5.tar.gz
    #   - Response file for DB2 10.5 Client for 64bit Linux db2rtcl_nr.rsp 
    #
    #
    # Using Ubuntu 14.04 base image as the starting point.
    FROM ubuntu:14.04
    
    MAINTAINER David Carew <[email protected]>
    
    # DB2 prereqs (also installing sharutils package as we use the utility uuencode to generate password - all others are required for the DB2 Client) 
    RUN dpkg --add-architecture i386 && apt-get update && apt-get install -y sharutils binutils libstdc++6:i386 libpam0g:i386 && ln -s /lib/i386-linux-gnu/libpam.so.0 /lib/libpam.so.0
    RUN apt-get install -y libxml2
    
    
    # Create user db2clnt
    # Generate strong random password and allow sudo to root w/o password
    #
    RUN  \
       adduser --quiet --disabled-password -shell /bin/bash -home /home/db2clnt --gecos "DB2 Client" db2clnt && \
       echo db2clnt:`dd if=/dev/urandom bs=16 count=1 2>/dev/null | uuencode -| head -n 2 | grep -v begin | cut -b 2-10` | chgpasswd && \
       adduser db2clnt sudo && \
       echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
    
    # Install DB2
    RUN mkdir /install
    # Copy DB2 tarball - ADD command will expand it automatically
    ADD v10.5fp9_linuxx64_rtcl.tar.gz /install/
    # Copy response file
    COPY  db2rtcl_nr.rsp /install/
    # Run  DB2 silent installer
    RUN mkdir /logs
    RUN (/install/rtcl/db2setup -t /logs/trace -l /logs/log -u /install/db2rtcl_nr.rsp && touch /install/done) || /bin/true
    RUN test -f /install/done || (echo ERROR-------; echo install failed, see files in container /logs directory of the last container layer; echo run docker run '<last image id>' /bin/cat /logs/trace; echo ----------)
    RUN test -f /install/done
    
    # Clean up unwanted files
    RUN rm -fr /install/rtcl
    
    # Login as db2clnt user
    CMD su - db2clnt
    

    What are functional interfaces used for in Java 8?

    Functional Interfaces: An interface is called a functional interface if it has a single abstract method irrespective of the number of default or static methods. Functional Interface are use for lamda expression. Runnable, Callable, Comparable, Comparator are few examples of Functional Interface.

    KeyNotes:

    • Annotation @FunctionalInterface is used(Optional).
    • It should have only 1 abstract method(irrespective of number of default and static methods).
    • Two abstract method gives compilation error(Provider @FunctionalInterface annotation is used).

    This thread talks more in detail about what benefit functional Interface gives over anonymous class and how to use them.

    Find value in an array

    I'm guessing that you're trying to find if a certain value exists inside the array, and if that's the case, you can use Array#include?(value):

    a = [1,2,3,4,5]
    a.include?(3)   # => true
    a.include?(9)   # => false
    

    If you mean something else, check the Ruby Array API

    Searching for file in directories recursively

    For file and directory search purpose I would want to offer use specialized multithreading .NET library that possess a wide search opportunities and works very fast.

    All information about library you can find on GitHub: https://github.com/VladPVS/FastSearchLibrary

    If you want to download it you can do it here: https://github.com/VladPVS/FastSearchLibrary/releases

    If you have any questions please ask them.

    It is one demonstrative example how you can use it:

    class Searcher
    {
        private static object locker = new object(); 
    
        private FileSearcher searcher;
    
        List<FileInfo> files;
    
        public Searcher()
        {
            files = new List<FileInfo>(); // create list that will contain search result
        }
    
        public void Startsearch()
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            // create tokenSource to get stop search process possibility
    
            searcher = new FileSearcher(@"C:\", (f) =>
            {
                return Regex.IsMatch(f.Name, @".*[Dd]ragon.*.jpg$");
            }, tokenSource);  // give tokenSource in constructor
    
    
            searcher.FilesFound += (sender, arg) => // subscribe on FilesFound event
            {
                lock (locker) // using a lock is obligatorily
                {
                    arg.Files.ForEach((f) =>
                    {
                        files.Add(f); // add the next received file to the search results list
                        Console.WriteLine($"File location: {f.FullName}, \nCreation.Time: {f.CreationTime}");
                    });
    
                    if (files.Count >= 10) // one can choose any stopping condition
                        searcher.StopSearch();
                }
            };
    
            searcher.SearchCompleted += (sender, arg) => // subscribe on SearchCompleted event
            {
                if (arg.IsCanceled) // check whether StopSearch() called
                    Console.WriteLine("Search stopped.");
                else
                    Console.WriteLine("Search completed.");
    
                Console.WriteLine($"Quantity of files: {files.Count}"); // show amount of finding files
            };
    
            searcher.StartSearchAsync();
            // start search process as an asynchronous operation that doesn't block the called thread
        }
    }
    

    input checkbox true or checked or yes

    Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.

    disabled, readonly and ismap input's attributes go on the same way.

    EDITED

    empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin

    Why is semicolon allowed in this python snippet?

    A quote from "When Pythons Attack"

    Don't terminate all of your statements with a semicolon. It's technically legal to do this in Python, but is totally useless unless you're placing more than one statement on a single line (e.g., x=1; y=2; z=3).

    How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

    Pehaps...ok, very likely, I'm missing something, but why not just create an object type, say NSNumber, as a container to your non-object type variable, such as CGFloat?

    CGFloat myFloat = 2.0; 
    NSNumber *myNumber = [NSNumber numberWithFloat:myFloat];
    
    [self performSelector:@selector(MyCalculatorMethod:) withObject:myNumber afterDelay:5.0];
    

    How to redirect verbose garbage collection output to a file?

    To add to the above answers, there's a good article: Useful JVM Flags – Part 8 (GC Logging) by Patrick Peschlow.

    A brief excerpt:

    The flag -XX:+PrintGC (or the alias -verbose:gc) activates the “simple” GC logging mode

    By default the GC log is written to stdout. With -Xloggc:<file> we may instead specify an output file. Note that this flag implicitly sets -XX:+PrintGC and -XX:+PrintGCTimeStamps as well.

    If we use -XX:+PrintGCDetails instead of -XX:+PrintGC, we activate the “detailed” GC logging mode which differs depending on the GC algorithm used.

    With -XX:+PrintGCTimeStamps a timestamp reflecting the real time passed in seconds since JVM start is added to every line.

    If we specify -XX:+PrintGCDateStamps each line starts with the absolute date and time.

    Keep CMD open after BAT file executes

    javac -d C:\xxx\lib\ -classpath C:\xxx\lib\ *.java
    
    cmd cd C:\xxx\yourbat.bat
    

    the second command make your cmd window not be closed. The important thing is you still able to input new command

    c++ array - expression must have a constant value

    When you declare a variable as here

    int a[10][10];
    

    you are telling the C++ compiler that you want 100 consecutive integers allocated in the program's memory at runtime. The compiler will then provide for your program to have that much memory available and all is well with the world.

    If however you tell the compiler

    int x = 9001;
    int y = 5;
    int a[x][y];
    

    the compiler has no way of knowing how much memory you are actually going to need at run time without doing a lot of very complex analysis to track down every last place where the values of x and y changed [if any]. Rather than support such variable size arrays, C++ and C strongly suggest if not outright demand that you use malloc() to manually allocate the space you want.

    TL;DR

    int x = 5;
    int y = 5;
    int **a = malloc(x*sizeof(int*));
    for(int i = 0; i < y; i++) {
        a[i] = malloc(sizeof(int*)*y);
    }
    

    a is now a 2D array of size 5x5 and will behave the same as int a[5][5]. Because you have manually allocated memory, C++ and C demand that you delete it by hand too...

    for(int i = 0; i < x; i++) {
        free(a[i]); // delete the 2nd dimension array
    }
    free(a); // delete a itself
    

    Submitting HTML form using Jquery AJAX

    var postData = "text";
          $.ajax({
                type: "post",
                url: "url",
                data: postData,
                contentType: "application/x-www-form-urlencoded",
                success: function(responseData, textStatus, jqXHR) {
                    alert("data saved")
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log(errorThrown);
                }
            })
    

    Joining pairs of elements of a list

    Use an iterator.

    List comprehension:

    >>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
    >>> [c+next(si, '') for c in si]
    ['abcde', 'fghijklmn', 'opqr']
    
    • Very efficient for memory usage.
    • Exactly one traversal of s

    Generator expression:

    >>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
    >>> pair_iter = (c+next(si, '') for c in si)
    >>> pair_iter # can be used in a for loop
    <generator object at 0x4ccaa8>
    >>> list(pair_iter) 
    ['abcde', 'fghijklmn', 'opqr']
    
    • use as an iterator

    Using map, str.__add__, iter

    >>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
    >>> map(str.__add__, si, si)
    ['abcde', 'fghijklmn', 'opqr']
    

    next(iterator[, default]) is available starting in Python 2.6

    Change primary key column in SQL Server

    Assuming that your current primary key constraint is called pk_history, you can replace the following lines:

    ALTER TABLE history ADD PRIMARY KEY (id)
    
    ALTER TABLE history
    DROP CONSTRAINT userId
    DROP CONSTRAINT name
    

    with these:

    ALTER TABLE history DROP CONSTRAINT pk_history
    
    ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)
    

    If you don't know what the name of the PK is, you can find it with the following query:

    SELECT * 
      FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
     WHERE TABLE_NAME = 'history'
    

    How to get screen dimensions as pixels in Android

    I think it's simplest

    private fun checkDisplayResolution() {
        val displayMetrics = DisplayMetrics().also {
            windowManager.defaultDisplay.getMetrics(it)
        }
    
        Log.i(TAG, "display width: ${displayMetrics.widthPixels}")
        Log.i(TAG, "display height: ${displayMetrics.heightPixels}")
        Log.i(TAG, "display width dpi: ${displayMetrics.xdpi}")
        Log.i(TAG, "display height dpi: ${displayMetrics.ydpi}")
        Log.i(TAG, "display density: ${displayMetrics.density}")
        Log.i(TAG, "display scaled density: ${displayMetrics.scaledDensity}")
    }
    

    What does on_delete do on Django models?

    The on_delete method is used to tell Django what to do with model instances that depend on the model instance you delete. (e.g. a ForeignKey relationship). The on_delete=models.CASCADE tells Django to cascade the deleting effect i.e. continue deleting the dependent models as well.

    Here's a more concrete example. Assume you have an Author model that is a ForeignKey in a Book model. Now, if you delete an instance of the Author model, Django would not know what to do with instances of the Book model that depend on that instance of Author model. The on_delete method tells Django what to do in that case. Setting on_delete=models.CASCADE will instruct Django to cascade the deleting effect i.e. delete all the Book model instances that depend on the Author model instance you deleted.

    Note: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.

    Here's the entire official documentation.

    What does "export default" do in JSX?

    Export like export default HelloWorld; and import, such as import React from 'react' are part of the ES6 modules system.

    A module is a self contained unit that can expose assets to other modules using export, and acquire assets from other modules using import.

    In your code:

    import React from 'react'; // get the React object from the react module
    
    class HelloWorld extends React.Component {
      render() {
        return <p>Hello, world!</p>;
      }
    }
    
    export default HelloWorld; // expose the HelloWorld component to other modules
    

    In ES6 there are two kinds of exports:

    Named exports - for example export function func() {} is a named export with the name of func. Named modules can be imported using import { exportName } from 'module';. In this case, the name of the import should be the same as the name of the export. To import the func in the example, you'll have to use import { func } from 'module';. There can be multiple named exports in one module.

    Default export - is the value that will be imported from the module, if you use the simple import statement import X from 'module'. X is the name that will be given locally to the variable assigned to contain the value, and it doesn't have to be named like the origin export. There can be only one default export.

    A module can contain both named exports and a default export, and they can be imported together using import defaultExport, { namedExport1, namedExport3, etc... } from 'module';.

    Display a message in Visual Studio's output window when not debug mode?

    To write in the Visual Studio output window I used IVsOutputWindow and IVsOutputWindowPane. I included as members in my OutputWindow class which look like this :

    public class OutputWindow : TextWriter
    {
      #region Members
    
      private static readonly Guid mPaneGuid = new Guid("AB9F45E4-2001-4197-BAF5-4B165222AF29");
      private static IVsOutputWindow mOutputWindow = null;
      private static IVsOutputWindowPane mOutputPane = null;
    
      #endregion
    
      #region Constructor
    
      public OutputWindow(DTE2 aDte)
      {
        if( null == mOutputWindow )
        {
          IServiceProvider serviceProvider = 
          new ServiceProvider(aDte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
          mOutputWindow = serviceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;
        }
    
        if (null == mOutputPane)
        {
          Guid generalPaneGuid = mPaneGuid;
          mOutputWindow.GetPane(ref generalPaneGuid, out IVsOutputWindowPane pane);
    
          if ( null == pane)
          {
            mOutputWindow.CreatePane(ref generalPaneGuid, "Your output window name", 0, 1);
            mOutputWindow.GetPane(ref generalPaneGuid, out pane);
          }
          mOutputPane = pane;
        }
      }
    
      #endregion
    
      #region Properties
    
      public override Encoding Encoding => System.Text.Encoding.Default;
    
      #endregion
    
      #region Public Methods
    
      public override void Write(string aMessage) => mOutputPane.OutputString($"{aMessage}\n");
    
      public override void Write(char aCharacter) => mOutputPane.OutputString(aCharacter.ToString());
    
      public void Show(DTE2 aDte)
      {
        mOutputPane.Activate();
        aDte.ExecuteCommand("View.Output", string.Empty);
      }
    
      public void Clear() => mOutputPane.Clear();
    
      #endregion
    }
    

    If you have a big text to write in output window you usually don't want to freeze the UI. In this purpose you can use a Dispatcher. To write something in output window using this implementation now you can simple do this:

    Dispatcher mDispatcher = HwndSource.FromHwnd((IntPtr)mDte.MainWindow.HWnd).RootVisual.Dispatcher;
    
    using (OutputWindow outputWindow = new OutputWindow(mDte))
    {
      mDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
      {
        outputWindow.Write("Write what you want here");
      }));
    }
    

    How to print matched regex pattern using awk?

    If you know what column the text/pattern you're looking for (e.g. "yyy") is in, you can just check that specific column to see if it matches, and print it.

    For example, given a file with the following contents, (called asdf.txt)

    xxx yyy zzz
    

    to only print the second column if it matches the pattern "yyy", you could do something like this:

    awk '$2 ~ /yyy/ {print $2}' asdf.txt
    

    Note that this will also match basically any line where the second column has a "yyy" in it, like these:

    xxx yyyz zzz
    xxx zyyyz
    

    MySQL: Fastest way to count number of rows

    I've always understood that the below will give me the fastest response times.

    SELECT COUNT(1) FROM ... WHERE ...
    

    Testing HTML email rendering

    You could also use PutsMail to test your emails before sending them.

    PutsMail is a tool to test HTML emails that will be sent as campaigns, newsletters and others (please, don't use it to spam, help us to make a better world).

    Main features:

    • Check HTML & CSS compatibility with email clients
    • Easily send HTML emails for approval or to check how it looks like in email clients

    CSV parsing in Java - working example..?

    i had to use a csv parser about 5 years ago. seems there are at least two csv standards: http://en.wikipedia.org/wiki/Comma-separated_values and what microsoft does in excel.

    i found this libaray which eats both: http://ostermiller.org/utils/CSV.html, but afaik, it has no way of inferring what data type the columns were.

    Go To Definition: "Cannot navigate to the symbol under the caret."

    Most of the paths submitted by others either don't work or are a little backwards.

    Empty this folder:

    %localappdata%\Temp\TFSTemp
    

    This worked for me.

    How to use KeyListener

    The class which implements KeyListener interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame. So

    1. Make one Key listener class as

      class MyListener implements KeyListener{
      
         // override all the methods of KeyListener interface.
      }
      
    2. Now our class MyKeyListener is ready to listen the key events. But it can not directly do so.

    3. Create any object like JFrame object through which MyListener can listen the key events. for that you need to add MyListener object to the JFrame object.

      JFrame f=new JFrame();
      f.addKeyListener(new MyKeyListener);
      

    SQL Client for Mac OS X that works with MS SQL Server

    Let's work together on a canonical answer.

    Native Apps

    Java-Based

    Electron-Based

    (TODO: Add others mentioned below)

    forEach is not a function error with JavaScript array

    A more naive version, at least you're sure that it'll work on all devices, without conversion and ES6 :

    const children = parent.children;
    for (var i = 0; i < children.length; i++){
        console.log(children[i]);
    }
    

    https://jsfiddle.net/swb12kqn/5/

    How to set cornerRadius for only top-left and top-right corner of a UIView?

    Simple extension

    extension UIView {
        func roundCorners(corners: UIRectCorner, radius: CGFloat) {
            if #available(iOS 11, *) {
                self.clipsToBounds = true
                self.layer.cornerRadius = radius
                var masked = CACornerMask()
                if corners.contains(.topLeft) { masked.insert(.layerMinXMinYCorner) }
                if corners.contains(.topRight) { masked.insert(.layerMaxXMinYCorner) }
                if corners.contains(.bottomLeft) { masked.insert(.layerMinXMaxYCorner) }
                if corners.contains(.bottomRight) { masked.insert(.layerMaxXMaxYCorner) }
                self.layer.maskedCorners = masked
            }
            else {
                let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
                let mask = CAShapeLayer()
                mask.path = path.cgPath
                layer.mask = mask
            }
        }
    }
    

    Usage:

    view.roundCorners(corners: [.bottomLeft, .bottomRight], radius: 12)
    

    Difference between break and continue in PHP?

    break will stop the current loop (or pass an integer to tell it how many loops to break from).

    continue will stop the current iteration and start the next one.

    How do I combine 2 javascript variables into a string

    Use the concatenation operator +, and the fact that numeric types will convert automatically into strings:

    var a = 1;
    var b = "bob";
    var c = b + a;
    

    How to update primary key

    First, we choose stable (not static) data columns to form a Primary Key, precisely because updating Keys in a Relational database (in which the references are by Key) is something we wish to avoid.

    1. For this issue, it doesn't matter if the Key is a Relational Key ("made up from the data"), and thus has Relational Integrity, Power, and Speed, or if the "key" is a Record ID, with none of that Relational Integrity, Power, and Speed. The effect is the same.

    2. I state this because there are many posts by the clueless ones, who suggest that this is the exact reason that Record IDs are somehow better than Relational Keys.

    3. The point is, the Key or Record ID is migrated to wherever a reference is required.

    Second, if you have to change the value of the Key or Record ID, well, you have to change it. Here is the OLTP Standard-compliant method. Note that the high-end vendors do not allow "cascade update".

    • Write a proc. Foo_UpdateCascade_tr @ID, where Foo is the table name

    • Begin a Transaction

    • First INSERT-SELECT a new row in the parent table, from the old row, with the new Key or RID value

    • Second, for all child tables, working top to bottom, INSERT-SELECT the new rows, from the old rows, with the new Key or RID value

    • Third, DELETE the rows in the child tables that have the old Key or RID value, working bottom to top

    • Last, DELETE the row in the parent table that has the old Key or RID value

    • Commit the Transaction

    Re the Other Answers

    The other answers are incorrect.

    • Disabling constraints and then enabling them, after UPDATing the required rows (parent plus all children) is not something that a person would do in an online production environment, if they wish to remain employed. That advice is good for single-user databases.

    • The need to change the value of a Key or RID is not indicative of a design flaw. It is an ordinary need. That is mitigated by choosing stable (not static) Keys. It can be mitigated, but it cannot be eliminated.

    • A surrogate substituting a natural Key, will not make any difference. In the example you have given, the "key" is a surrogate. And it needs to be updated.

      • Please, just surrogate, there is no such thing as a "surrogate key", because each word contradicts the other. Either it is a Key (made up from the data) xor it isn't. A surrogate is not made up from the data, it is explicitly non-data. It has none of the properties of a Key.
    • There is nothing "tricky" about cascading all the required changes. Refer to the steps given above.

    • There is nothing that can be prevented re the universe changing. It changes. Deal with it. And since the database is a collection of facts about the universe, when the universe changes, the database will have to change. That is life in the big city, it is not for new players.

    • People getting married and hedgehogs getting buried are not a problem (despite such examples being used to suggest that it is a problem). Because we do not use Names as Keys. We use small, stable Identifiers, such as are used to Identify the data in the universe.

      • Names, descriptions, etc, exist once, in one row. Keys exist wherever they have been migrated. And if the "key" is a RID, then the RID too, exists wherever it has been migrated.
    • Don't update the PK! is the second-most hilarious thing I have read in a while. Add a new column is the most.

    How to fix SSL certificate error when running Npm on Windows?

    I am having the same issue, I overcome using

    npm config set proxy http://my-proxy.com:1080
    npm config set https-proxy http://my-proxy.com:1080
    

    Additionally info at node-doc

    How to overcome "datetime.datetime not JSON serializable"?

    My solution (with less verbosity, I think):

    def default(o):
        if type(o) is datetime.date or type(o) is datetime.datetime:
            return o.isoformat()
    
    def jsondumps(o):
        return json.dumps(o, default=default)
    

    Then use jsondumps instead of json.dumps. It will print:

    >>> jsondumps({'today': datetime.date.today()})
    '{"today": "2013-07-30"}'
    

    I you want, later you can add other special cases to this with a simple twist of the default method. Example:

    def default(o):
        if type(o) is datetime.date or type(o) is datetime.datetime:
            return o.isoformat()
        if type(o) is decimal.Decimal:
            return float(o)
    

    Should I use window.navigate or document.location in JavaScript?

    Late joining this conversation to shed light on a mildly interesting factoid for web-facing, analytics-aware websites. Passing the mic over to Michael Papworth:

    https://github.com/michaelpapworth/jQuery.navigate

    "When using website analytics, window.location is not sufficient due to the referer not being passed on the request. The plugin resolves this and allows for both aliased and parametrised URLs."

    If one examines the code what it does is this:

       var methods = {
                'goTo': function (url) {
                    // instead of using window.location to navigate away
                    // we use an ephimeral link to click on and thus ensure
                    // the referer (current url) is always passed on to the request
                    $('<a></a>').attr("href", url)[0].click();
                },
                ...
       };
    

    Neato!

    How to print a dictionary line by line in Python?

    You have a nested structure, so you need to format the nested dictionary too:

    for key, car in cars.items():
        print(key)
        for attribute, value in car.items():
            print('{} : {}'.format(attribute, value))
    

    This prints:

    A
    color : 2
    speed : 70
    B
    color : 3
    speed : 60
    

    Git merge master into feature branch

    git merge

    you can follow below steps

    1. merge origin/master branch to feature branch

    # step1: change branch to master, and pull to update all commits
    $ git checkout master
    $ git pull
    
    # step2: change branch to target, and pull to update commits
    $ git checkout feature
    $ git pull
    
    # step3: merge master to feature(?? current is feature branch)
    $ git merge master
    
    

    2. merge feature branch to origin/master branch

    origin/master is the remote master branch, while master is the local master branch

    $ git checkout master
    $ git pull origin/master
    
    $ git merge feature
    $ git push origin/master
    
    

    How do you use MySQL's source command to import large files in windows

    For importing a large SQL file using the command line in MySQL.

    First go to file path at the command line. Then,

    Option 1:

    mysql -u {user_name} -p{password} {database_name}  < your_file.sql
    

    It's give a warning mesaage : Using a password on the command line interface can be insecure.

    Done.Your file will be imported.

    Option 2:

    mysql -u {user_name} -p {database_name}  < your_file.sql
    

    in this you are not provide sql password then they asked for password just enter password and your file will be imported.

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

    Warning you get is done by compiler, not by library (or utility method).

    Simplest way using Jackson directly would be:

    HashMap<String,Object> props;
    
    // src is a File, InputStream, String or such
    props = new ObjectMapper().readValue(src, new TypeReference<HashMap<String,Object>>() {});
    // or:
    props = (HashMap<String,Object>) new ObjectMapper().readValue(src, HashMap.class);
    // or even just:
    @SuppressWarnings("unchecked") // suppresses typed/untype mismatch warnings, which is harmless
    props = new ObjectMapper().readValue(src, HashMap.class);
    

    Utility method you call probably just does something similar to this.

    Set default format of datetimepicker as dd-MM-yyyy

    Ensure that control Format property is properly set to use a custom format:

    DateTimePicker1.Format = DateTimePickerFormat.Custom
    

    Then this is how you can set your desired format:

    DateTimePicker1.CustomFormat = "dd-MM-yyyy"
    

    pandas dataframe groupby datetime month

    Slightly alternative solution to @jpp's but outputting a YearMonth string:

    df['YearMonth'] = pd.to_datetime(df['Date']).apply(lambda x: '{year}-{month}'.format(year=x.year, month=x.month))
    
    res = df.groupby('YearMonth')['Values'].sum()
    

    How do I iterate over the words of a string?

    Using std::string_view and Eric Niebler's range-v3 library:

    https://wandbox.org/permlink/kW5lwRCL1pxjp2pW

    #include <iostream>
    #include <string>
    #include <string_view>
    #include "range/v3/view.hpp"
    #include "range/v3/algorithm.hpp"
    
    int main() {
        std::string s = "Somewhere down the range v3 library";
        ranges::for_each(s  
            |   ranges::view::split(' ')
            |   ranges::view::transform([](auto &&sub) {
                    return std::string_view(&*sub.begin(), ranges::distance(sub));
                }),
            [](auto s) {std::cout << "Substring: " << s << "\n";}
        );
    }
    

    By using a range for loop instead of ranges::for_each algorithm:

    #include <iostream>
    #include <string>
    #include <string_view>
    #include "range/v3/view.hpp"
    
    int main()
    {
        std::string str = "Somewhere down the range v3 library";
        for (auto s : str | ranges::view::split(' ')
                          | ranges::view::transform([](auto&& sub) { return std::string_view(&*sub.begin(), ranges::distance(sub)); }
                          ))
        {
            std::cout << "Substring: " << s << "\n";
        }
    }
    

    Sending mail attachment using Java

    If you allow me, it works fine also for multi-attachments, the 1st above answer of NINCOMPOOP, with just a little modification like follows:

    DataSource source,source2,source3,source4, ...;  
    source = new FileDataSource(myfile);  
    messageBodyPart.setDataHandler(new DataHandler(source));  
    messageBodyPart.setFileName(myfile);  
    multipart.addBodyPart(messageBodyPart);  
    
    source2 = new FileDataSource(myfile2);  
    messageBodyPart.setDataHandler(new DataHandler(source2));  
    messageBodyPart.setFileName(myfile2);  
    multipart.addBodyPart(messageBodyPart);  
    
    source3 = new FileDataSource(myfile3);  
    messageBodyPart.setDataHandler(new DataHandler(source3));  
    messageBodyPart.setFileName(myfile3);  
    multipart.addBodyPart(messageBodyPart);  
    
    source4 = new FileDataSource(myfile4);  
    messageBodyPart.setDataHandler(new DataHandler(source4));  
    messageBodyPart.setFileName(myfile4);  
    multipart.addBodyPart(messageBodyPart);  
    
    ...
    
    message.setContent(multipart);
    

    Document Root PHP

    <a href="<?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?>">go with php</a>
        <br />
    <a href="/hello.html">go to with html</a>
    

    Try this yourself and find that they are not exactly the same.

    $_SERVER['DOCUMENT_ROOT'] renders an actual file path (on my computer running as it's own server, C:/wamp/www/

    HTML's / renders the root of the server url, in my case, localhost/

    But C:/wamp/www/hello.html and localhost/hello.html are in fact the same file

    How to embed PDF file with responsive width

    <html>
    <head>
    <style type="text/css">
    #wrapper{ width:100%; float:left; height:auto; border:1px solid #5694cf;}
    </style>
    </head>
    <div id="wrapper">
    <object data="http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf" width="100%" height="100%">
    <p>Your web browser doesn't have a PDF Plugin. Instead you can <a href="http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf"> Click
    here to download the PDF</a></p>
    </object>
    </div>
    </html>
    

    Why do I get a "permission denied" error while installing a gem?

    Install rbenv or rvm as your Ruby version manager (I prefer rbenv) via homebrew (ie. brew update & brew install rbenv) but then for example in rbenv's case make sure to add rbenv to your $PATH as instructed here and here.

    For a deeper explanation on how rbenv works I recommend this.

    Convert one date format into another in PHP

    Just using strings, for me is a good solution, less problems with mysql. Detects the current format and changes it if necessary, this solution is only for spanish/french format and english format, without use php datetime function.

    class dateTranslator {
    
     public static function translate($date, $lang) {
          $divider = '';
    
          if (empty($date)){
               return null;   
          }
          if (strpos($date, '-') !== false) {
               $divider = '-';
          } else if (strpos($date, '/') !== false) {
               $divider = '/';
          }
          //spanish format DD/MM/YYYY hh:mm
          if (strcmp($lang, 'es') == 0) {
    
               $type = explode($divider, $date)[0];
               if (strlen($type) == 4) {
                    $date = self::reverseDate($date,$divider);
               } 
               if (strcmp($divider, '-') == 0) {
                    $date = str_replace("-", "/", $date);
               }
          //english format YYYY-MM-DD hh:mm
          } else {
    
               $type = explode($divider, $date)[0];
               if (strlen($type) == 2) {
    
                    $date = self::reverseDate($date,$divider);
               } 
               if (strcmp($divider, '/') == 0) {
                    $date = str_replace("/", "-", $date);
    
               }   
          }
          return $date;
     }
    
     public static function reverseDate($date) {
          $date2 = explode(' ', $date);
          if (count($date2) == 2) {
               $date = implode("-", array_reverse(preg_split("/\D/", $date2[0]))) . ' ' . $date2[1];
          } else {
               $date = implode("-", array_reverse(preg_split("/\D/", $date)));
          }
    
          return $date;
     }
    

    USE

    dateTranslator::translate($date, 'en')
    

    jQuery DataTable overflow and text-wrapping issues

    You can try setting the word-wrap however it doesn't work in all browsers yet.

    Another method would be to add an element around your cell data like this:

    <td><span>...</span></td>
    

    Then add some css like this:

    .datatable td span{
        max-width: 400px;
        display: block;
        overflow: hidden;
    }
    

    else & elif statements not working in Python

     if guess == number:
         print ("Good")
     elif guess == 2:
         print ("Bad")
     else:
         print ("Also bad")
    

    Make sure you have your identation right. The syntax is ok.

    Reference - What does this regex mean?

    The Stack Overflow Regular Expressions FAQ

    See also a lot of general hints and useful links at the tag details page.


    Online tutorials

    Quantifiers

    Character Classes

    Escape Sequences

    Anchors

    (Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

    Groups

    Lookarounds

    Modifiers

    Other:

    Common Tasks

    Advanced Regex-Fu

    Flavor-Specific Information

    (Except for those marked with *, this section contains non-Stack Overflow links.)

    General information

    (Links marked with * are non-Stack Overflow links.)

    Examples of regex that can cause regex engine to fail

    Tools: Testers and Explainers

    (This section contains non-Stack Overflow links.)

    how to read all files inside particular folder

        using System.IO;
        string[] arr=Directory.GetFiles("folderpath","*.Fileextension");
          foreach(string file in arr)
           {
    
           }
    

    How to get param from url in angular 4?

    constructor(private activatedRoute: ActivatedRoute) {
    }
    
    ngOnInit() {
        this.activatedRoute.params.subscribe(paramsId => {
            this.id = paramsId.id;
            console.log(this.id);
        });
      
     }
    

    TypeError: can't pickle _thread.lock objects

    I had the same problem with Pool() in Python 3.6.3.

    Error received: TypeError: can't pickle _thread.RLock objects

    Let's say we want to add some number num_to_add to each element of some list num_list in parallel. The code is schematically like this:

    class DataGenerator:
        def __init__(self, num_list, num_to_add)
            self.num_list = num_list # e.g. [4,2,5,7]
            self.num_to_add = num_to_add # e.g. 1 
    
            self.run()
    
        def run(self):
            new_num_list = Manager().list()
    
            pool = Pool(processes=50)
            results = [pool.apply_async(run_parallel, (num, new_num_list)) 
                          for num in num_list]
            roots = [r.get() for r in results]
            pool.close()
            pool.terminate()
            pool.join()
    
        def run_parallel(self, num, shared_new_num_list):
            new_num = num + self.num_to_add # uses class parameter
            shared_new_num_list.append(new_num)
    

    The problem here is that self in function run_parallel() can't be pickled as it is a class instance. Moving this parallelized function run_parallel() out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add and then you have to pass it as an argument.

    Solution:

    def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
        new_num = num + to_add
        shared_new_num_list.append(new_num)
    
    class DataGenerator:
        def __init__(self, num_list, num_to_add)
            self.num_list = num_list # e.g. [4,2,5,7]
            self.num_to_add = num_to_add # e.g. 1
    
            self.run()
    
        def run(self):
            new_num_list = Manager().list()
    
            pool = Pool(processes=50)
            results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
                          for num in num_list]
            roots = [r.get() for r in results]
            pool.close()
            pool.terminate()
            pool.join()
    

    Other suggestions above didn't help me.

    AngularJS How to dynamically add HTML and bind to controller

    See if this example provides any clarification. Basically you configure a set of routes and include partial templates based on the route. Setting ng-view in your main index.html allows you to inject those partial views.

    The config portion looks like this:

      .config(['$routeProvider', function($routeProvider) {
        $routeProvider
          .when('/', {controller:'ListCtrl', templateUrl:'list.html'})
          .otherwise({redirectTo:'/'});
      }])
    

    The point of entry for injecting the partial view into your main template is:

    <div class="container" ng-view=""></div>
    

    How to replace (null) values with 0 output in PIVOT

    You have to account for all values in the pivot set. you can accomplish this using a cartesian product.

    select pivoted.*
    from (
        select cartesian.key1, cartesian.key2, isnull(relationship.[value],'nullvalue') as [value]
        from (
          select k1.key1, k2.key2
          from ( select distinct key1 from relationship) k1
              ,( select distinct key2 from relationship) k2
        ) cartesian
          left outer join relationship on relationship.key1 = cartesian.key1 and  relationship.key2 = carterisan.key2
    ) data
      pivot (
        max(data.value) for ([key2_v1], [key2_v2], [key2_v3], ...)
      ) pivoted
    

    Change the On/Off text of a toggle button Android

    You can do this by 2 options:

    Option 1: By setting its xml attributes

     `android:textOff="TEXT OFF"
      android:textOn="TEXT ON"`
    

    Option 2: Programmatically

    Set the attribute onClick: methodNameHere (mine is toggleState) Then write this code:

    public void toggleState(View view) {
       boolean toggle = ((ToogleButton)view).isChecked();
       if (toggle){
           ((ToogleButton)view).setTextOn("TEXT ON");
       } else {
          ((ToogleButton)view).setTextOff("TEXT OFF");
       }
    }
    

    PS: it works for me, hope it works for you too

    Recursively look for files with a specific extension

    Though using find command can be useful here, the shell itself provides options to achieve this requirement without any third party tools. The bash shell provides an extended glob support option using which you can get the file names under recursive paths that match with the extensions you want.

    The extended option is extglob which needs to be set using the shopt option as below. The options are enabled with the -s support and disabled with he -u flag. Additionally you could use couple of options more i.e. nullglob in which an unmatched glob is swept away entirely, replaced with a set of zero words. And globstar that allows to recurse through all the directories

    shopt -s extglob nullglob globstar
    

    Now all you need to do is form the glob expression to include the files of a certain extension which you can do as below. We use an array to populate the glob results because when quoted properly and expanded, the filenames with special characters would remain intact and not get broken due to word-splitting by the shell.

    For example to list all the *.csv files in the recursive paths

    fileList=(**/*.csv)
    

    The option ** is to recurse through the sub-folders and *.csv is glob expansion to include any file of the extensions mentioned. Now for printing the actual files, just do

    printf '%s\n' "${fileList[@]}"
    

    Using an array and doing a proper quoted expansion is the right way when used in shell scripts, but for interactive use, you could simply use ls with the glob expression as

    ls -1 -- **/*.csv
    

    This could very well be expanded to match multiple files i.e. file ending with multiple extension (i.e. similar to adding multiple flags in find command). For example consider a case of needing to get all recursive image files i.e. of extensions *.gif, *.png and *.jpg, all you need to is

    ls -1 -- **/+(*.jpg|*.gif|*.png)
    

    This could very well be expanded to have negate results also. With the same syntax, one could use the results of the glob to exclude files of certain type. Assume you want to exclude file names with the extensions above, you could do

    excludeResults=()
    excludeResults=(**/!(*.jpg|*.gif|*.png))
    printf '%s\n' "${excludeResults[@]}"
    

    The construct !() is a negate operation to not include any of the file extensions listed inside and | is an alternation operator just as used in the Extended Regular Expressions library to do an OR match of the globs.

    Note that these extended glob support is not available in the POSIX bourne shell and its purely specific to recent versions of bash. So if your are considering portability of the scripts running across POSIX and bash shells, this option wouldn't be right.

    Is it possible to change javascript variable values while debugging in Google Chrome?

    Actually there is a workaround. Copy the entire method, modify it's name, e.g. originalName() to originalName2() but modify the variable inside to take on whatever value you want, or pass it in as a parameter.

    Then if you call this method directly from the console, it will have the same functionality but you will be able to modify the variable values.

    If the method is called automatically then instead type into the console

    originalName = null;
    function originalName(original params..)
    {
        alert("modified internals");
        add whatever original code you want
    }
    

    Quickest way to convert a base 10 number to any base in .NET?

    I had a similar need, except I needed to do math on the "numbers" as well. I took some of the suggestions here and created a class that will do all this fun stuff. It allows for any unicode character to be used to represent a number and it works with decimals too.

    This class is pretty easy to use. Just create a number as a type of New BaseNumber, set a few properties, and your off. The routines take care of switching between base 10 and base x automatically and the value you set is preserved in the base you set it in, so no accuracy is lost (until conversion that is, but even then precision loss should be very minimal since this routine uses Double and Long where ever possible).

    I can't command on the speed of this routine. It is probably quite slow, so I'm not sure if it will suit the needs of the one who asked the question, but it certain is flexible, so hopefully someone else can use this.

    For anyone else that may need this code for calculating the next column in Excel, I will include the looping code I used that leverages this class.

    Public Class BaseNumber
    
        Private _CharacterArray As List(Of Char)
    
        Private _BaseXNumber As String
        Private _Base10Number As Double?
    
        Private NumberBaseLow As Integer
        Private NumberBaseHigh As Integer
    
        Private DecimalSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
        Private GroupSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator
    
        Public Sub UseCapsLetters()
            'http://unicodelookup.com
            TrySetBaseSet(65, 90)
        End Sub
    
        Public Function GetCharacterArray() As List(Of Char)
            Return _CharacterArray
        End Function
    
        Public Sub SetCharacterArray(CharacterArray As String)
            _CharacterArray = New List(Of Char)
            _CharacterArray.AddRange(CharacterArray.ToList)
    
            TrySetBaseSet(_CharacterArray)
        End Sub
    
        Public Sub SetCharacterArray(CharacterArray As List(Of Char))
            _CharacterArray = CharacterArray
            TrySetBaseSet(_CharacterArray)
        End Sub
    
        Public Sub SetNumber(Value As String)
            _BaseXNumber = Value
            _Base10Number = Nothing
        End Sub
    
        Public Sub SetNumber(Value As Double)
            _Base10Number = Value
            _BaseXNumber = Nothing
        End Sub
    
        Public Function GetBaseXNumber() As String
            If _BaseXNumber IsNot Nothing Then
                Return _BaseXNumber
            Else
                Return ToBaseString()
            End If
        End Function
    
        Public Function GetBase10Number() As Double
            If _Base10Number IsNot Nothing Then
                Return _Base10Number
            Else
                Return ToBase10()
            End If
        End Function
    
        Private Sub TrySetBaseSet(Values As List(Of Char))
            For Each value As Char In _BaseXNumber
                If Not Values.Contains(value) Then
                    Throw New ArgumentOutOfRangeException("The string has a value, " & value & ", not contained in the selected 'base' set.")
                    _CharacterArray.Clear()
                    DetermineNumberBase()
                End If
            Next
    
            _CharacterArray = Values
    
        End Sub
    
        Private Sub TrySetBaseSet(LowValue As Integer, HighValue As Integer)
    
            Dim HighLow As KeyValuePair(Of Integer, Integer) = GetHighLow()
    
            If HighLow.Key < LowValue OrElse HighLow.Value > HighValue Then
                Throw New ArgumentOutOfRangeException("The string has a value not contained in the selected 'base' set.")
                _CharacterArray.Clear()
                DetermineNumberBase()
            End If
    
            NumberBaseLow = LowValue
            NumberBaseHigh = HighValue
    
        End Sub
    
        Private Function GetHighLow(Optional Values As List(Of Char) = Nothing) As KeyValuePair(Of Integer, Integer)
            If Values Is Nothing Then
                Values = _BaseXNumber.ToList
            End If
    
            Dim lowestValue As Integer = Convert.ToInt32(Values(0))
            Dim highestValue As Integer = Convert.ToInt32(Values(0))
    
            Dim currentValue As Integer
    
            For Each value As Char In Values
    
                If value <> DecimalSeparator AndAlso value <> GroupSeparator Then
                    currentValue = Convert.ToInt32(value)
                    If currentValue > highestValue Then
                        highestValue = currentValue
                    End If
                    If currentValue < lowestValue Then
                        currentValue = lowestValue
                    End If
                End If
            Next
    
            Return New KeyValuePair(Of Integer, Integer)(lowestValue, highestValue)
    
        End Function
    
        Public Sub New(BaseXNumber As String)
            _BaseXNumber = BaseXNumber
            DetermineNumberBase()
        End Sub
    
        Public Sub New(BaseXNumber As String, NumberBase As Integer)
            Me.New(BaseXNumber, Convert.ToInt32("0"c), NumberBase)
        End Sub
    
        Public Sub New(BaseXNumber As String, NumberBaseLow As Integer, NumberBaseHigh As Integer)
            _BaseXNumber = BaseXNumber
            Me.NumberBaseLow = NumberBaseLow
            Me.NumberBaseHigh = NumberBaseHigh
        End Sub
    
        Public Sub New(Base10Number As Double)
            _Base10Number = Base10Number
        End Sub
    
        Private Sub DetermineNumberBase()
            Dim highestValue As Integer
    
            Dim currentValue As Integer
    
            For Each value As Char In _BaseXNumber
    
                currentValue = Convert.ToInt32(value)
                If currentValue > highestValue Then
                    highestValue = currentValue
                End If
            Next
    
            NumberBaseHigh = highestValue
            NumberBaseLow = Convert.ToInt32("0"c) 'assume 0 is the lowest
    
        End Sub
    
        Private Function ToBaseString() As String
            Dim Base10Number As Double = _Base10Number
    
            Dim intPart As Long = Math.Truncate(Base10Number)
            Dim fracPart As Long = (Base10Number - intPart).ToString.Replace(DecimalSeparator, "")
    
            Dim intPartString As String = ConvertIntToString(intPart)
            Dim fracPartString As String = If(fracPart <> 0, DecimalSeparator & ConvertIntToString(fracPart), "")
    
            Return intPartString & fracPartString
    
        End Function
    
        Private Function ToBase10() As Double
            Dim intPartString As String = _BaseXNumber.Split(DecimalSeparator)(0).Replace(GroupSeparator, "")
            Dim fracPartString As String = If(_BaseXNumber.Contains(DecimalSeparator), _BaseXNumber.Split(DecimalSeparator)(1), "")
    
            Dim intPart As Long = ConvertStringToInt(intPartString)
            Dim fracPartNumerator As Long = ConvertStringToInt(fracPartString)
            Dim fracPartDenominator As Long = ConvertStringToInt(GetEncodedChar(1) & String.Join("", Enumerable.Repeat(GetEncodedChar(0), fracPartString.ToString.Length)))
    
            Return Convert.ToDouble(intPart + fracPartNumerator / fracPartDenominator)
    
        End Function
    
        Private Function ConvertIntToString(ValueToConvert As Long) As String
            Dim result As String = String.Empty
            Dim targetBase As Long = GetEncodingCharsLength()
    
            Do
                result = GetEncodedChar(ValueToConvert Mod targetBase) & result
                ValueToConvert = ValueToConvert \ targetBase
            Loop While ValueToConvert > 0
    
            Return result
        End Function
    
        Private Function ConvertStringToInt(ValueToConvert As String) As Long
            Dim result As Long
            Dim targetBase As Integer = GetEncodingCharsLength()
            Dim startBase As Integer = GetEncodingCharsStartBase()
    
            Dim value As Char
            For x As Integer = 0 To ValueToConvert.Length - 1
                value = ValueToConvert(x)
                result += GetDecodedChar(value) * Convert.ToInt32(Math.Pow(GetEncodingCharsLength, ValueToConvert.Length - (x + 1)))
            Next
    
            Return result
    
        End Function
    
        Private Function GetEncodedChar(index As Integer) As Char
            If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
                Return _CharacterArray(index)
            Else
                Return Convert.ToChar(index + NumberBaseLow)
            End If
        End Function
    
        Private Function GetDecodedChar(character As Char) As Integer
            If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
                Return _CharacterArray.IndexOf(character)
            Else
                Return Convert.ToInt32(character) - NumberBaseLow
            End If
        End Function
    
        Private Function GetEncodingCharsLength() As Integer
            If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
                Return _CharacterArray.Count
            Else
                Return NumberBaseHigh - NumberBaseLow + 1
            End If
        End Function
    
        Private Function GetEncodingCharsStartBase() As Integer
            If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
                Return GetHighLow.Key
            Else
                Return NumberBaseLow
            End If
        End Function
    End Class
    

    And now for the code to loop through Excel columns:

        Public Function GetColumnList(DataSheetID As String) As List(Of String)
            Dim workingColumn As New BaseNumber("A")
            workingColumn.SetCharacterArray("@ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    
            Dim listOfPopulatedColumns As New List(Of String)
            Dim countOfEmptyColumns As Integer
    
            Dim colHasData As Boolean
            Dim cellHasData As Boolean
    
            Do
                colHasData = True
                cellHasData = False
                For r As Integer = 1 To GetMaxRow(DataSheetID)
                    cellHasData = cellHasData Or XLGetCellValue(DataSheetID, workingColumn.GetBaseXNumber & r) <> ""
                Next
                colHasData = colHasData And cellHasData
    
                'keep trying until we get 4 empty columns in a row
                If colHasData Then
                    listOfPopulatedColumns.Add(workingColumn.GetBaseXNumber)
                    countOfEmptyColumns = 0
                Else
                    countOfEmptyColumns += 1
                End If
    
                'we are already starting with column A, so increment after we check column A
                Do
                    workingColumn.SetNumber(workingColumn.GetBase10Number + 1)
                Loop Until Not workingColumn.GetBaseXNumber.Contains("@")
    
            Loop Until countOfEmptyColumns > 3
    
            Return listOfPopulatedColumns
    
        End Function
    

    You'll note the important part of the Excel part is that 0 is identified by a @ in the re-based number. So I just filter out all the numbers that have an @ in them and I get the proper sequence (A, B, C, ..., Z, AA, AB, AC, ...).

    Printing all properties in a Javascript Object

    What about this:

    var txt="";
    var nyc = {
        fullName: "New York City",
        mayor: "Michael Bloomberg",
        population: 8000000,
        boroughs: 5
    };
    
    for (var x in nyc){
        txt += nyc[x];
    }
    

    where is create-react-app webpack config and files?

    If you want to find webpack files and configurations go to your package.json file and look for scripts

    img

    You will find that scripts object is using a library react-scripts

    Now go to node_modules and look for react-scripts folder react-script-in-node-modules

    This react-scripts/scripts and react-scripts/config folder contains all the webpack configurations.

    how get yesterday and tomorrow datetime in c#

    To get "local" yesterday in UTC.

      var now = DateTime.Now;
      var yesterday = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0, DateTimeKind.Utc).AddDays(-1);
    

    "Stack overflow in line 0" on Internet Explorer

    Aha!

    I had an OnError() event in some code that was setting the image source to a default image path if it wasn't found. Of course, if the default image path wasn't found it would trigger the error handler...

    For people who have a similar problem but not the same, I guess the cause of this is most likely to be either an unterminated loop, an event handler that triggers itself or something similar that throws the JavaScript engine into a spin.

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name

    According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

    java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
    

    I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

    Java Round up Any Number

    Math.ceil() is the correct function to call. I'm guessing a is an int, which would make a / 100 perform integer arithmetic. Try Math.ceil(a / 100.0) instead.

    int a = 142;
    System.out.println(a / 100);
    System.out.println(Math.ceil(a / 100));
    System.out.println(a / 100.0);
    System.out.println(Math.ceil(a / 100.0));
    System.out.println((int) Math.ceil(a / 100.0));
    

    Outputs:

    1
    1.0
    1.42
    2.0
    2
    

    See http://ideone.com/yhT0l

    Adding items to end of linked list

    loop to the last element of the linked list which have next pointer to null then modify the next pointer to point to a new node which has the data=object and next pointer = null

    How to split an integer into an array of digits?

    >>> [int(i) for i in str(12345)]
    
    [1, 2, 3, 4, 5]
    

    alternative to "!is.null()" in R

    If it's just a matter of easy reading, you could always define your own function :

    is.not.null <- function(x) !is.null(x)
    

    So you can use it all along your program.

    is.not.null(3)
    is.not.null(NULL)
    

    Visual Studio Code pylint: Unable to import 'protorpc'

    Spent hours trying to fix the error for importing local modules. Code execution was fine but pylint showed:

        Unable to import '<module>'
    

    Finally figured:

    1. First of all, select the correct python path. (In the case of a virtual environment, it will be venv/bin/python). You can do this by hitting

    2. Make sure that your pylint path is the same as the python path you chose in step 1. (You can open VS Code from within the activated venv from terminal so it automatically performs these two steps)

    3. The most important step: Add an empty __init__.py file in the folder that contains your module file. Although python3 does not require this file for importing modules, I think pylint still requires it for linting.

    Restart VS Code, the errors should be gone!

    How to create checkbox inside dropdown?

    Simply use bootstrap-multiselect where you can populate dropdown with multiselect option and many more feaatures.

    For doc and tutorials you may visit below link

    https://www.npmjs.com/package/bootstrap-multiselect

    http://davidstutz.de/bootstrap-multiselect/

    How to apply CSS to iframe?

    If the content of the iframe is not completely under your control or you want to access the content from different pages with different styles you could try manipulating it using JavaScript.

    var frm = frames['frame'].document;
    var otherhead = frm.getElementsByTagName("head")[0];
    var link = frm.createElement("link");
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("type", "text/css");
    link.setAttribute("href", "style.css");
    otherhead.appendChild(link);
    

    Note that depending on what browser you use this might only work on pages served from the same domain.

    sql like operator to get the numbers only

    With SQL 2012 and later, you could use TRY_CAST/TRY_CONVERT to try converting to a numeric type, e.g. TRY_CAST(answer AS float) IS NOT NULL -- note though that this will match scientific notation too (1+E34). (If you use decimal, then scientific notation won't match)

    typedef fixed length array

    To use the array type properly as a function argument or template parameter, make a struct instead of a typedef, then add an operator[] to the struct so you can keep the array like functionality like so:

    typedef struct type24 {
      char& operator[](int i) { return byte[i]; }
      char byte[3];
    } type24;
    
    type24 x;
    x[2] = 'r';
    char c = x[2];
    

    jQuery posting JSON

    In case you are sending this post request to a cross domain, you should check out this link.

    https://stackoverflow.com/a/1320708/969984

    Your server is not accepting the cross site post request. So the server configuration needs to be changed to allow cross site requests.

    What does "export" do in shell programming?

    Well, it generally depends on the shell. For bash, it marks the variable as "exportable" meaning that it will show up in the environment for any child processes you run.

    Non-exported variables are only visible from the current process (the shell).

    From the bash man page:

    export [-fn] [name[=word]] ...
    export -p

    The supplied names are marked for automatic export to the environment of subsequently executed commands.

    If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed.

    The -n option causes the export property to be removed from each name.

    If a variable name is followed by =word, the value of the variable is set to word.

    export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function.

    You can also set variables as exportable with the typeset command and automatically mark all future variable creations or modifications as such, with set -a.

    Kotlin's List missing "add", "remove", Map missing "put", etc?

    Defining a List collection in Kotlin in different ways:

    • Immutable variable with immutable (read only) list:

      val users: List<User> = listOf( User("Tom", 32), User("John", 64) )
      


    • Immutable variable with mutable list:

      val users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
      

      or without initial value - empty list and without explicit variable type:

      val users = mutableListOf<User>()
      //or
      val users = ArrayList<User>()
      
      • you can add items to list:
        • users.add(anohterUser) or
        • users += anotherUser (under the hood it's users.add(anohterUser))


    • Mutable variable with immutable list:

      var users: List<User> = listOf( User("Tom", 32), User("John", 64) )
      

      or without initial value - empty list and without explicit variable type:

      var users = emptyList<User>()
      
      • NOTE: you can add* items to list:
        • users += anotherUser - *it creates new ArrayList and assigns it to users


    • Mutable variable with mutable list:

      var users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
      

      or without initial value - empty list and without explicit variable type:

      var users = emptyList<User>().toMutableList()
      //or
      var users = ArrayList<User>()
      
      • NOTE: you can add items to list:
        • users.add(anohterUser)
        • but not using users += anotherUser

          Error: Kotlin: Assignment operators ambiguity:
          public operator fun Collection.plus(element: String): List defined in kotlin.collections
          @InlineOnly public inline operator fun MutableCollection.plusAssign(element: String): Unit defined in kotlin.collections


    see also: https://kotlinlang.org/docs/reference/collections.html

    Google MAP API v3: Center & Zoom on displayed markers

    Try this function....it works...

    $(function() {
            var myOptions = {
                zoom: 10,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
            var latlng_pos=[];
            var j=0;
             $(".property_item").each(function(){
                latlng_pos[j]=new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val());
                j++;
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val()),
                    // position: new google.maps.LatLng(-35.397, 150.640),
                    map: map
                });
            }
            );
            // map: an instance of google.maps.Map object
            // latlng: an array of google.maps.LatLng objects
            var latlngbounds = new google.maps.LatLngBounds( );
            for ( var i = 0; i < latlng_pos.length; i++ ) {
                latlngbounds.extend( latlng_pos[ i ] );
            }
            map.fitBounds( latlngbounds );
    
    
    
        });
    

    static linking only some libraries

    There is also -l:libstatic1.a (minus l colon) variant of -l option in gcc which can be used to link static library (Thanks to https://stackoverflow.com/a/20728782). Is it documented? Not in the official documentation of gcc (which is not exact for shared libs too): https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html

    -llibrary
    -l library 
    

    Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.) ... The only difference between using an -l option and specifying a file name is that -l surrounds library with ‘lib’ and ‘.a’ and searches several directories.

    The binutils ld doc describes it. The -lname option will do search for libname.so then for libname.a adding lib prefix and .so (if enabled at the moment) or .a suffix. But -l:name option will only search exactly for the name specified: https://sourceware.org/binutils/docs/ld/Options.html

    -l namespec
    --library=namespec
    

    Add the archive or object file specified by namespec to the list of files to link. This option may be used any number of times. If namespec is of the form :filename, ld will search the library path for a file called filename, otherwise it will search the library path for a file called libnamespec.a.

    On systems which support shared libraries, ld may also search for files other than libnamespec.a. Specifically, on ELF and SunOS systems, ld will search a directory for a library called libnamespec.so before searching for one called libnamespec.a. (By convention, a .so extension indicates a shared library.) Note that this behavior does not apply to :filename, which always specifies a file called filename.

    The linker will search an archive only once, at the location where it is specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive. However, an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive again.

    See the -( option for a way to force the linker to search archives multiple times.

    You may list the same archive multiple times on the command line.

    This type of archive searching is standard for Unix linkers. However, if you are using ld on AIX, note that it is different from the behaviour of the AIX linker.

    The variant -l:namespec is documented since 2.18 version of binutils (2007): https://sourceware.org/binutils/docs-2.18/ld/Options.html

    Update OpenSSL on OS X with Homebrew

    I had problems installing some Wordpress plugins on my local server running php56 on OSX10.11. They failed connection on the external API over SSL.

    Installing openSSL didn't solved my problem. But then I figured out that CURL also needed to be reinstalled.

    This solved my problem using Homebrew.

    brew rm curl && brew install curl --with-openssl
    
    brew uninstall php56 && brew install php56 --with-homebrew-curl --with-openssl
    

    simple way to display data in a .txt file on a webpage?

    You cannot style a text file, it must be HTML

    Formatting text in a TextBlock

    You need to use Inlines:

    <TextBlock.Inlines>
        <Run FontWeight="Bold" FontSize="14" Text="This is WPF TextBlock Example. " />
        <Run FontStyle="Italic" Foreground="Red" Text="This is red text. " />
    </TextBlock.Inlines>
    

    With binding:

    <TextBlock.Inlines>
        <Run FontWeight="Bold" FontSize="14" Text="{Binding BoldText}" />
        <Run FontStyle="Italic" Foreground="Red" Text="{Binding ItalicText}" />
    </TextBlock.Inlines>
    

    You can also bind the other properties:

    <TextBlock.Inlines>
        <Run FontWeight="{Binding Weight}"
             FontSize="{Binding Size}"
             Text="{Binding LineOne}" />
        <Run FontStyle="{Binding Style}"
             Foreground="Binding Colour}"
             Text="{Binding LineTwo}" />
    </TextBlock.Inlines>
    

    You can bind through converters if you have bold as a boolean (say).

    How to JSON decode array elements in JavaScript?

    If the object element you get is a function, you can try this:

    var url = myArray[i]();
    

    How to affect other elements when one element is hovered

    If the cube is directly inside the container:

    #container:hover > #cube { background-color: yellow; }
    

    If cube is next to (after containers closing tag) the container:

    #container:hover + #cube { background-color: yellow; }
    

    If the cube is somewhere inside the container:

    #container:hover #cube { background-color: yellow; }
    

    If the cube is a sibling of the container:

    #container:hover ~ #cube { background-color: yellow; }
    

    java - path to trustStore - set property doesn't work?

    You have a typo - it is trustStore.

    Apart from setting the variables with System.setProperty(..), you can also use

    -Djavax.net.ssl.keyStore=path/to/keystore.jks
    

    Replacing objects in array

    Here a transparent approach, instead of an unreadable and undebuggable oneliner:

    export class List {
        static replace = (object, list) => {
            let newList = [];
            list.forEach(function (item) {
                if (item.id === object.id) {
                    newList.push(object);
                } else {
                    newList.push(item);
                }
            });
            return newList;
        }
    }
    

    Why is IoC / DI not common in Python?

    Part of it is the way the module system works in Python. You can get a sort of "singleton" for free, just by importing it from a module. Define an actual instance of an object in a module, and then any client code can import it and actually get a working, fully constructed / populated object.

    This is in contrast to Java, where you don't import actual instances of objects. This means you are always having to instantiate them yourself, (or use some sort of IoC/DI style approach). You can mitigate the hassle of having to instantiate everything yourself by having static factory methods (or actual factory classes), but then you still incur the resource overhead of actually creating new ones each time.

    Change jsp on button click

    You have several options, I'll start from the easiest:

    1- Change the input buttons to links, you can style them with css so they look like buttons:

    <a href="CreateCourse.jsp">Creazione Nuovo Corso</a>
    

    instead of

    <input type="button" value="Creazione Nuovo Corso" name="CreateCourse" />
    

    2- Use javascript to change the action of the form depending on the button you click:

    <input type="button" value="Creazione Nuovo Corso" name="CreateCourse" 
    onclick="document.forms[0].action = 'CreateCourse.jsp'; return true;" />
    

    3- Use a servlet or JSP to handle the request and redirect or forward to the appropriate JSP page.

    get keys of json-object in JavaScript

    The working code

    _x000D_
    _x000D_
    var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];_x000D_
    _x000D_
    for(var obj in jsonData){_x000D_
        if(jsonData.hasOwnProperty(obj)){_x000D_
        for(var prop in jsonData[obj]){_x000D_
            if(jsonData[obj].hasOwnProperty(prop)){_x000D_
               alert(prop + ':' + jsonData[obj][prop]);_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    How do I "select Android SDK" in Android Studio?

    Go to : File > Project Structure > Modules -> app > Properties

    please choose : Compile 'SDK' version = API26 Build Tools Version = 27.0.0 Source Compatibility = 1.8 Target Compatibility = 1.8

    How do you set, clear, and toggle a single bit?

    int set_nth_bit(int num, int n){    
        return (num | 1 << n);
    }
    
    int clear_nth_bit(int num, int n){    
        return (num & ~( 1 << n));
    }
    
    int toggle_nth_bit(int num, int n){    
        return num ^ (1 << n);
    }
    
    int check_nth_bit(int num, int n){    
        return num & (1 << n);
    }
    

    Inserting a string into a list without getting split into characters

    Another option is using the overloaded + operator:

    >>> l = ['hello','world']
    >>> l = ['foo'] + l
    >>> l
    ['foo', 'hello', 'world']
    

    Difference between Fact table and Dimension table?

    From my point of view,

    • Dimension table : Master Data
    • Fact table : Transactional Data

    git remove merge commit from history

    There are two ways to tackle this based on what you want:

    Solution 1: Remove purple commits, preserving history (incase you want to roll back)

    git revert -m 1 <SHA of merge>
    

    -m 1 specifies which parent line to choose

    Purple commits will still be there in history but since you have reverted, you will not see code from those commits.


    Solution 2: Completely remove purple commits (disruptive change if repo is shared)

    git rebase -i <SHA before branching out>
    

    and delete (remove lines) corresponding to purple commits.

    This would be less tricky if commits were not made after merge. Additional commits increase the chance of conflicts during revert/rebase.

    "Could not find Developer Disk Image"

    Older XCode version has no developer disk image for newer iOS version. If you don't want upgrade XCode you can find ready developer disk images for latest versions in this answer: https://stackoverflow.com/a/39865199/286361

    Installing Apache Maven Plugin for Eclipse

    Installed Maven in Juno IDE for Java EE (eclipse-jee-juno-SR2-linux-gtk-x86_64)

    Eclipse -> Available Software Sites -> Maven URL -> http://download.eclipse.org/technology/m2e/releases

    Following Maven URL did not work and was giving "No software found" error: http://eclipse.org/m2e/download/

    What is resource-ref in web.xml used for?

    You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

    <resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

    So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

    <resource-ref>
      <res-ref-name>jdbc/primaryDB</res-ref-name>
      <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
    </resource-ref>
    

    Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

    The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

    Replacing Numpy elements if condition is met

    The quickest (and most flexible) way is to use np.where, which chooses between two arrays according to a mask(array of true and false values):

    import numpy as np
    a = np.random.randint(0, 5, size=(5, 4))
    b = np.where(a<3,0,1)
    print('a:',a)
    print()
    print('b:',b)
    

    which will produce:

    a: [[1 4 0 1]
     [1 3 2 4]
     [1 0 2 1]
     [3 1 0 0]
     [1 4 0 1]]
    
    b: [[0 1 0 0]
     [0 1 0 1]
     [0 0 0 0]
     [1 0 0 0]
     [0 1 0 0]]
    

    CSS: Creating textured backgrounds

    with latest CSS3 technology, it is possible to create textured background. Check this out: http://lea.verou.me/css3patterns/#

    but it still limited on so many aspect. And browser support is also not so ready.

    your best bet is using small texture image and make repeat to that background. you could get some nice ready to use texture image here:

    http://subtlepatterns.com