Programs & Examples On #Mscomct2.ocx

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

While waiting for a reply for ideas here, I had decided to try something. I ran regedit as administrator, navigated to the HKEY_CLASSES_ROOT\TypeLib Key and then did a search for "MSCOMCTL.OCX"... I deleted EVERY key that referenced this .ocx file.

After searching the entire registry, deleting what I found, I ran command prompt as administrator. I then navigated to C:\Windows\SysWOW64 and typed the following commands:

regsvr32 MSCOMCTL.OCX
regtlib msdatsrc.tlb

Upon registering these two files again, everything is WORKING! I scoured the web for HOURS looking for this solution to no avail. It just so happens I fixed it myself after posting a question here :( Even though Visual Studio 6 is outdated, hopefully this may still help others!

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

Add regression line equation and R^2 on graph

Here's the most simplest code for everyone

Note: Showing Pearson's Rho and not R^2.

library(ggplot2)
library(ggpubr)

df <- data.frame(x = c(1:100)
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
        geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
        geom_point()+
        stat_cor(label.y = 35)+ #this means at 35th unit in the y axis, the r squared and p value will be shown
        stat_regline_equation(label.y = 30) #this means at 30th unit regresion line equation will be shown

p

One such example with my own dataset

Regex to accept alphanumeric and some special character in Javascript?

use:

/^[ A-Za-z0-9_@./#&+-]*$/

You can also use the character class \w to replace A-Za-z0-9_

How to mount host volumes into docker containers in Dockerfile during build

First, to answer "why doesn't VOLUME work?" When you define a VOLUME in the Dockerfile, you can only define the target, not the source of the volume. During the build, you will only get an anonymous volume from this. That anonymous volume will be mounted at every RUN command, prepopulated with the contents of the image, and then discarded at the end of the RUN command. Only changes to the container are saved, not changes to the volume.


Since this question has been asked, a few features have been released that may help. First is multistage builds allowing you to build a disk space inefficient first stage, and copy just the needed output to the final stage that you ship. And the second feature is Buildkit which is dramatically changing how images are built and new capabilities are being added to the build.

For a multi-stage build, you would have multiple FROM lines, each one starting the creation of a separate image. Only the last image is tagged by default, but you can copy files from previous stages. The standard use is to have a compiler environment to build a binary or other application artifact, and a runtime environment as the second stage that copies over that artifact. You could have:

FROM debian:sid as builder
COPY export /export
RUN compile command here >/result.bin

FROM debian:sid
COPY --from=builder /result.bin /result.bin
CMD ["/result.bin"]

That would result in a build that only contains the resulting binary, and not the full /export directory.


Buildkit is coming out of experimental in 18.09. It's a complete redesign of the build process, including the ability to change the frontend parser. One of those parser changes has has implemented the RUN --mount option which lets you mount a cache directory for your run commands. E.g. here's one that mounts some of the debian directories (with a reconfigure of the debian image, this could speed up reinstalls of packages):

# syntax = docker/dockerfile:experimental
FROM debian:latest
RUN --mount=target=/var/lib/apt/lists,type=cache \
    --mount=target=/var/cache/apt,type=cache \
    apt-get update \
 && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
      git

You would adjust the cache directory for whatever application cache you have, e.g. $HOME/.m2 for maven, or /root/.cache for golang.


TL;DR: Answer is here: With that RUN --mount syntax, you can also bind mount read-only directories from the build-context. The folder must exist in the build context, and it is not mapped back to the host or the build client:

# syntax = docker/dockerfile:experimental
FROM debian:latest
RUN --mount=target=/export,type=bind,source=export \
    process export directory here...

Note that because the directory is mounted from the context, it's also mounted read-only, and you cannot push changes back to the host or client. When you build, you'll want an 18.09 or newer install and enable buildkit with export DOCKER_BUILDKIT=1.

If you get an error that the mount flag isn't supported, that indicates that you either didn't enable buildkit with the above variable, or that you didn't enable the experimental syntax with the syntax line at the top of the Dockerfile before any other lines, including comments. Note that the variable to toggle buildkit will only work if your docker install has buildkit support built in, which requires version 18.09 or newer from Docker, both on the client and server.

Vue.js - How to properly watch for nested data

I used deep:true, but found the old and new value in the watched function was the same always. As an alternative to previous solutions I tried this, which will check any change in the whole object by transforming it to a string:

created() {
    this.$watch(
        () => JSON.stringify(this.object),
            (newValue, oldValue) => {
                //do your stuff                
            }
    );
},

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:

$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session 

or

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

Clicking HTML 5 Video element to play, pause video, breaks play button

I had countless issues doing this but finally came up with a solution that works.

Basically the code below is adding a click handler to the video but ignoring all the clicks on the lower part (0.82 is arbitrary but seems to work on all sizes).

    $("video").click(function(e){

        // get click position 
        var clickY = (e.pageY - $(this).offset().top);
        var height = parseFloat( $(this).height() );

        // avoids interference with controls
        if(y > 0.82*height) return;

        // toggles play / pause
        this.paused ? this.play() : this.pause();

    });

Fastest Convert from Collection to List<T>

you can convert like below code snippet

Collection<A> obj=new Collection<return ListRetunAPI()>

Chrome says my extension's manifest file is missing or unreadable

Kindly check whether you have installed right version of ChromeDriver or not . In my case , installing correct version helped.

Generate a range of dates using SQL

Ahahaha, here's a funny way I just came up with to do this:

select SYSDATE - ROWNUM
from shipment_weights sw
where ROWNUM < 365;

where shipment_weights is any large table;

How can I change my Cygwin home folder after installation?

I'd like to add a correction/update to the bit about $HOME taking precedence. The home directory in /etc/passwd takes precedence over everything.

I'm a long time Cygwin user and I just did a clean install of Windows 7 x64 and Cygwin V1.126. I was going nuts trying to figure out why every time I ran ssh I kept getting:

e:\>ssh foo.bar.com
Could not create directory '/home/dhaynes/.ssh'.
The authenticity of host 'foo.bar.com (10.66.19.19)' can't be established.
...

I add the HOME=c:\users\dhaynes definition in the Windows environment but still it kept trying to create '/home/dhaynes'. I tried every combo I could including setting HOME to /cygdrive/c/users/dhaynes. Googled for the error message, could not find anything, couldn't find anything on the cygwin site. I use cygwin from cmd.exe, not bash.exe but the problem was present in both.

I finally realized that the home directory in /etc/passwd was taking precedence over the $HOME environment variable. I simple re-ran 'mkpasswd -l >/etc/passwd' and that updated the home directory, now all is well with ssh.

That may be obvious to linux types with sysadmin experience but for those of us who primarily use Windows it's a bit obscure.

Selenium -- How to wait until page is completely loaded

You can do this in many ways before clicking on add items:

WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(By.id("urelementid")));// instead of id u can use cssSelector or xpath of ur element.


or

wait.until(ExpectedConditions.visibilityOfElementLocated("urelement"));

You can also wait like this. If you want to wait until invisible of previous page element:

wait.until(ExpectedConditions.invisibilityOfElementLocated("urelement"));

Here is the link where you can find all the Selenium WebDriver APIs that can be used for wait and its documentation.

https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html

Pandas get the most frequent values of a column

You could use .apply and pd.value_counts to get a count the occurrence of all the names in the name column.

dataframe['name'].apply(pd.value_counts)

How do I force Robocopy to overwrite files?

I did this for a home folder where all the folders are on the desktops of the corresponding users, reachable through a shortcut which did not have the appropriate permissions, so that users couldn't see it even if it was there. So I used Robocopy with the parameter to overwrite the file with the right settings:

FOR /F "tokens=*" %G IN ('dir /b') DO robocopy  "\\server02\Folder with shortcut" "\\server02\home\%G\Desktop" /S /A /V /log+:C:\RobocopyShortcut.txt /XF *.url *.mp3 *.hta *.htm *.mht *.js *.IE5 *.css *.temp *.html *.svg *.ocx *.3gp *.opus *.zzzzz *.avi *.bin *.cab *.mp4 *.mov *.mkv *.flv *.tiff *.tif *.asf *.webm *.exe *.dll *.dl_ *.oc_ *.ex_ *.sy_ *.sys *.msi *.inf *.ini *.bmp *.png *.gif *.jpeg *.jpg *.mpg *.db *.wav *.wma *.wmv *.mpeg *.tmp *.old *.vbs *.log *.bat *.cmd *.zip /SEC /IT /ZB /R:0

As you see there are many file types which I set to ignore (just in case), just set them for your needs or your case scenario.

It was tested on Windows Server 2012, and every switch is documented on Microsoft's sites and others.

What's the difference between SoftReference and WeakReference in Java?

In Java; order from strongest to weakest, there are: Strong, Soft, Weak and Phantom

A Strong reference is a normal reference that protects the referred object from collection by GC. i.e. Never garbage collects.

A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError.

A Weak reference is a reference that does not protect a referenced object from collection by GC. i.e. garbage collects when no Strong or Soft refs.

A Phantom reference is a reference to an object is phantomly referenced after it has been finalized, but before its allocated memory has been reclaimed.

Source

Analogy: Assume a JVM is a kingdom, Object is a king of the kingdom, and GC is an attacker of the kingdom who tries to kill the king(object).

  • When King is Strong, GC can not kill him.
  • When King is Soft, GC attacks him but King rule the kingdom with protection until resource are available.
  • When King is Weak, GC attacks him but rule the kingdom without protection.
  • When king is Phantom, GC already killed him but king is available via his soul.

How do I check if a Socket is currently connected in Java?

Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.

TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.

See Do I need to heartbeat to keep a TCP connection open? for more discussion.

Handling the null value from a resultset in JAVA

To treat validation when a field is null in the database, you could add the following condition.

String name = (oRs.getString ("name_column"))! = Null? oRs.getString ("name_column"): "";

with this you can validate when a field is null and do not mark an exception.

jQuery select box validation

Since you cannot set value="" within your first option, you'll need to create your own rule using the built-in addMethod() method.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            year: {
                selectcheck: true
            }
        }
    });

    jQuery.validator.addMethod('selectcheck', function (value) {
        return (value != '0');
    }, "year required");

});

HTML:

<select name="year">
    <option value="0">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Working Demo: http://jsfiddle.net/tPRNd/


Original Answer: (Only if you can set value="" within the first option)

To properly validate a select element with the jQuery Validate plugin simply requires that the first option contains value="". So remove the 0 from value="0" and it's fixed.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            year: {
                required: true,
            }
        }
    });

});

HTML:

<select name="year">
    <option value="">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Demo: http://jsfiddle.net/XGtEr/

Where can I find my Facebook application id and secret key?

It is under Account -> Application Settings, click on your application's profile, then go to Edit Application.

Android Studio installation on Windows 7 fails, no JDK found

Install the latest JDK in your system from JDK 7 and JRE 7 Installation Guide.

JAVA_HOME -> C:\Program Files\Java\jdk1.7.0_4
path -> C:\Program Files\Java\jdk1.7.0_4\bin

ZIP Code (US Postal Code) validation

Javascript Regex Literal:

US Zip Codes: /(^\d{5}$)|(^\d{5}-\d{4}$)/

var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210");

Some countries use Postal Codes, which would fail this pattern.

to_string is not a member of std, says g++ (mingw)

If we use a template-light-solution (as shown above) like the following:

namespace std {
    template<typename T>
    std::string to_string(const T &n) {
        std::ostringstream s;
        s << n;
        return s.str();
    }
}

Unfortunately, we will have problems in some cases. For example, for static const members:

hpp

class A
{
public:

    static const std::size_t x = 10;

    A();
};

cpp

A::A()
{
    std::cout << std::to_string(x);
}

And linking:

CMakeFiles/untitled2.dir/a.cpp.o:a.cpp:(.rdata$.refptr._ZN1A1xE[.refptr._ZN1A1xE]+0x0): undefined reference to `A::x'
collect2: error: ld returned 1 exit status

Here is one way to solve the problem (add to the type size_t):

namespace std {
    std::string to_string(size_t n) {
        std::ostringstream s;
        s << n;
        return s.str();
    }
}

HTH.

Starting a shell in the Docker Alpine container

Nowadays, Alpine images will boot directly into /bin/sh by default, without having to specify a shell to execute:

$ sudo docker run -it --rm alpine  
/ # echo $0  
/bin/sh  

This is since the alpine image Dockerfiles now contain a CMD command, that specifies the shell to execute when the container starts: CMD ["/bin/sh"].

In older Alpine image versions (pre-2017), the CMD command was not used, since Docker used to create an additional layer for CMD which caused the image size to increase. This is something that the Alpine image developers wanted to avoid. In recent Docker versions (1.10+), CMD no longer occupies a layer, and so it was added to alpine images. Therefore, as long as CMD is not overridden, recent Alpine images will boot into /bin/sh.

For reference, see the following commit to the official Alpine Dockerfiles by Glider Labs:
https://github.com/gliderlabs/docker-alpine/commit/ddc19dd95ceb3584ced58be0b8d7e9169d04c7a3#diff-db3dfdee92c17cf53a96578d4900cb5b

How to send a simple email from a Windows batch file?

I've used Blat ( http://www.blat.net/ ) for many years. It's a simple command line utility that can send email from command line. It's free and opensource.

You can use command like "Blat myfile.txt -to [email protected] -server smtp.domain.com -port 6000"

Here is some other software you can try to send email from command line (I've never used them):
http://caspian.dotconf.net/menu/Software/SendEmail/
http://www.petri.co.il/sendmail.htm
http://www.petri.co.il/software/mailsend105.zip
http://retired.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm

Here ( http://www.petri.co.il/send_mail_from_script.htm ) you can find other various way of sending email from a VBS script, plus link to some of the mentioned software

The following VBScript code is taken from that page

Set objEmail = CreateObject("CDO.Message")
objEmail.From = "[email protected]"
objEmail.To = "[email protected]"
objEmail.Subject = "Server is down!"
objEmail.Textbody = "Server100 is no longer accessible over the network."
objEmail.Send

Save the file as something.vbs

Set Msg = CreateObject("CDO.Message")

With Msg

 .To = "[email protected]"
 .From = "[email protected]"
 .Subject = "Hello"
 .TextBody = "Just wanted to say hi."
 .Send

End With

Save the file as something2.vbs

I think these VBS scripts use the windows default mail server, if present. I've not tested these scripts...

Increase bootstrap dropdown menu width

Usually we have the need to control the width of the dropdown menu; specially that's essential when the dropdown menu holds a form, e.g. login form --- then the dropdown menu and its items should be wide enough for ease of inputing username/email and password.

Besides, when the screen is smaller than 768px or when the window (containing the dropdown menu) is zoomed down to smaller than 768px, Bootstrap 3 responsively scales the dropdown menu to the whole width of the screen/window. We need to keep this reponsive action.

Hence, the following css class could do that:

@media (min-width: 768px) {
    .dropdown-menu {
        width: 300px !important;  /* change the number to whatever that you need */
    }
}

(I had used it in my web app.)

Select datatype of the field in postgres

You can get data types from the information_schema (8.4 docs referenced here, but this is not a new feature):

=# select column_name, data_type from information_schema.columns
-# where table_name = 'config';
    column_name     | data_type 
--------------------+-----------
 id                 | integer
 default_printer_id | integer
 master_host_enable | boolean
(3 rows)

AngularJs ReferenceError: angular is not defined

I think this will happen if you'll use 'async defer' for (the file that contains the filter) while working with angularjs:

<script src="js/filter.js" type="text/javascript" async defer></script>

if you do, just remove 'async defer'.

Does GPS require Internet?

There are two issues:

  1. Getting the current coordinates (longitude, latitude, perhaps altitude) based on some external signals received by your device, and
  2. Deriving a human-readable position (address) from the coordinates.

To get the coordinates you don't need the Internet. GPS is satellite-based. But to derive street/city information from the coordinates, you'd need either to implement the map and the corresponding algorithms yourself on the device (a lot of work!) or to rely on proven services, e.g. by Google, in which case you'd need an Internet connection.

As of recently, Google allows for caching the maps, which would at least allow you to show your current position on the map even without a data connection, provided, you had cached the map in advance, when you could access the Internet.

How to call a method in MainActivity from another class?

Initialize it first

MainActivity mActivity= new MainActivity();

Then you can continue

mActivity.startChronometer();

How do you determine the size of a file in C?

If you're fine with using the std c library:

#include <sys/stat.h>
off_t fsize(char *file) {
    struct stat filestat;
    if (stat(file, &filestat) == 0) {
        return filestat.st_size;
    }
    return 0;
}

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

Converting from signed char to unsigned char and back again?

Yes this is safe.

The c language uses a feature called integer promotion to increase the number of bits in a value before performing calculations. Therefore your CLAMP255 macro will operate at integer (probably 32 bit) precision. The result is assigned to a jbyte, which reduces the integer precision back to 8 bits fit in to the jbyte.

Use 'import module' or 'from module import'?

Since I am also a beginner, I will be trying to explain this in a simple way: In Python, we have three types of import statements which are:

1. Generic imports:

import math

this type of import is my personal favorite, the only downside to this import technique is that if you need use any module's function you must use the following syntax:

math.sqrt(4)

of course, it increases the typing effort but as a beginner, it will help you to keep track of module and function associated with it, (a good text editor will reduce the typing effort significantly and is recommended).

Typing effort can be further reduced by using this import statement:

import math as m

now, instead of using math.sqrt() you can use m.sqrt().

2. Function imports:

from math import sqrt

this type of import is best suited if your code only needs to access single or few functions from the module, but for using any new item from the module you have to update import statement.

3. Universal imports:

from math import * 

Although it reduces typing effort significantly but is not recommended because it will fill your code with various functions from the module and their name could conflict with the name of user-defined functions. example:

If you have a function of your very own named sqrt and you import math, your function is safe: there is your sqrt and there is math.sqrt. If you do from math import *, however, you have a problem: namely, two different functions with the exact same name. Source: Codecademy

Is there a way to create interfaces in ES6 / Node 4?

In comments debiasej wrote the mentioned below article explains more about design patterns (based on interfaces, classes):

http://loredanacirstea.github.io/es6-design-patterns/

Design patterns book in javascript may also be useful for you:

http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Design pattern = classes + interface or multiple inheritance

An example of the factory pattern in ES6 JS (to run: node example.js):

"use strict";

// Types.js - Constructors used behind the scenes

// A constructor for defining new cars
class Car {
  constructor(options){
    console.log("Creating Car...\n");
    // some defaults
    this.doors = options.doors || 4;
    this.state = options.state || "brand new";
    this.color = options.color || "silver";
  }
}

// A constructor for defining new trucks
class Truck {
  constructor(options){
    console.log("Creating Truck...\n");
    this.state = options.state || "used";
    this.wheelSize = options.wheelSize || "large";
    this.color = options.color || "blue";
  }
}


// FactoryExample.js

// Define a skeleton vehicle factory
class VehicleFactory {}

// Define the prototypes and utilities for this factory

// Our default vehicleClass is Car
VehicleFactory.prototype.vehicleClass = Car;

// Our Factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function ( options ) {

  switch(options.vehicleType){
    case "car":
      this.vehicleClass = Car;
      break;
    case "truck":
      this.vehicleClass = Truck;
      break;
    //defaults to VehicleFactory.prototype.vehicleClass (Car)
  }

  return new this.vehicleClass( options );

};

// Create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle( {
            vehicleType: "car",
            color: "yellow",
            doors: 6 } );

// Test to confirm our car was created using the vehicleClass/prototype Car

// Outputs: true
console.log( car instanceof Car );

// Outputs: Car object of color "yellow", doors: 6 in a "brand new" state
console.log( car );

var movingTruck = carFactory.createVehicle( {
                      vehicleType: "truck",
                      state: "like new",
                      color: "red",
                      wheelSize: "small" } );

// Test to confirm our truck was created with the vehicleClass/prototype Truck

// Outputs: true
console.log( movingTruck instanceof Truck );

// Outputs: Truck object of color "red", a "like new" state
// and a "small" wheelSize
console.log( movingTruck );

Verilog generate/genvar in an always block

Within a module, Verilog contains essentially two constructs: items and statements. Statements are always found in procedural contexts, which include anything in between begin..end, functions, tasks, always blocks and initial blocks. Items, such as generate constructs, are listed directly in the module. For loops and most variable/constant declarations can exist in both contexts.

In your code, it appears that you want the for loop to be evaluated as a generate item but the loop is actually part of the procedural context of the always block. For a for loop to be treated as a generate loop it must be in the module context. The generate..endgenerate keywords are entirely optional(some tools require them) and have no effect. See this answer for an example of how generate loops are evaluated.

//Compiler sees this
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
genvar c;

    always @(posedge sysclk) //Procedural context starts here
    begin
        for (c = 0; c < ROWBITS; c = c + 1) begin: test
            temp[c] <= 1'b0; //Still a genvar
        end
    end

How often does python flush to a file?

I don't know if this applies to python as well, but I think it depends on the operating system that you are running.

On Linux for example, output to terminal flushes the buffer on a newline, whereas for output to files it only flushes when the buffer is full (by default). This is because it is more efficient to flush the buffer fewer times, and the user is less likely to notice if the output is not flushed on a newline in a file.

You might be able to auto-flush the output if that is what you need.

EDIT: I think you would auto-flush in python this way (based from here)

#0 means there is no buffer, so all output
#will be auto-flushed
fsock = open('out.log', 'w', 0)
sys.stdout = fsock
#do whatever
fsock.close()

How can I compile and run c# program without using visual studio?

There are different ways for this:

1.Building C# Applications Using csc.exe

While it is true that you might never decide to build a large-scale application using nothing but the C# command-line compiler, it is important to understand the basics of how to compile your code files by hand.

2.Building .NET Applications Using Notepad++

Another simple text editor I’d like to quickly point out is the freely downloadable Notepad++ application. This tool can be obtained from http://notepad-plus.sourceforge.net. Unlike the primitive Windows Notepad application, Notepad++ allows you to author code in a variety of languages and supports

3.Building .NET Applications Using SharpDevelop

As you might agree, authoring C# code with Notepad++ is a step in the right direction, compared to Notepad. However, these tools do not provide rich IntelliSense capabilities for C# code, designers for building graphical user interfaces, project templates, or database manipulation utilities. To address such needs, allow me to introduce the next .NET development option: SharpDevelop (also known as "#Develop").You can download it from http://www.sharpdevelop.com.

How to uninstall jupyter

In pip3

pip3 uninstall jupyterlab

Proxy with urllib2

In Addition to the accepted answer: My scipt gave me an error

File "c:\Python23\lib\urllib2.py", line 580, in proxy_open
    if '@' in host:
TypeError: iterable argument required

Solution was to add http:// in front of the proxy string:

proxy = urllib2.ProxyHandler({'http': 'http://proxy.xy.z:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')

How to validate numeric values which may contain dots or commas?

In order to represent a single digit in the form of a regular expression you can use either:

[0-9] or \d

In order to specify how many times the number appears you would add

[0-9]*: the star means there are zero or more digits

[0-9]{2}: {N} means N digits

[0-9]{0,2}: {N,M} N digits or M digits

[0-9]{0-9}: {N-M} N digits to M digits. Note: M can be left blank for an infinite representation

Lets say I want to represent a number between 1 and 99 I would express it as such:

[0-9]{1-2} or [0-9]{1,2} or \d{1-2} or \d{1,2}

Or lets say we were working with binary display, displaying a byte size, we would want our digits to be between 0 and 1 and length of a byte size, 8, so we would represent it as follows:

[0-1]{8} representation of a binary byte

Then if you want to add a , or a . symbol you would use:

\, or \. or you can use [.] or [,]

You can also state a selection between possible values as such

[.,] means either a dot or a comma symbol

And you just need to concatenate the pieces together, so in the case where you want to represent a 1 or 2 digit number followed by either a comma or a period and followed by two more digits you would express it as follows: >

[0-9]{1,2}[.,]\d{1-2}

Also note that regular expression strings inside C++ strings must be double-back-slashed so every \ becomes \\

UITextField text change event

I resolved the issue changing the behavior of shouldChangeChractersInRange. If you return NO the changes won't be applied by iOS internally, instead you have the opportunity to change it manually and perform any actions after the changes.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    //Replace the string manually in the textbox
    textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    //perform any logic here now that you are sure the textbox text has changed
    [self didChangeTextInTextField:textField];
    return NO; //this make iOS not to perform any action
}

Casting to string in JavaScript

Real world example: I've got a log function that can be called with an arbitrary number of parameters: log("foo is {} and bar is {}", param1, param2). If a DEBUG flag is set to true, the brackets get replaced by the given parameters and the string is passed to console.log(msg). Parameters can and will be Strings, Numbers and whatever may be returned by JSON / AJAX calls, maybe even null.

  • arguments[i].toString() is not an option, because of possible null values (see Connell Watkins answer)
  • JSLint will complain about arguments[i] + "". This may or may not influence a decision on what to use. Some folks strictly adhere to JSLint.
  • In some browsers, concatenating empty strings is a little faster than using string function or string constructor (see JSPerf test in Sammys S. answer). In Opera 12 and Firefox 19, concatenating empty strings is rediculously faster (95% in Firefox 19) - or at least JSPerf says so.

What does "request for member '*******' in something not a structure or union" mean?

It may also happen in the following case:

eg. if we consider the push function of a stack:

typedef struct stack
{
    int a[20];
    int head;
}stack;

void push(stack **s)
{
    int data;
    printf("Enter data:");
    scanf("%d",&(*s->a[++*s->head])); /* this is where the error is*/
}

main()
{
    stack *s;
    s=(stack *)calloc(1,sizeof(stack));
    s->head=-1;
    push(&s);
    return 0;
}

The error is in the push function and in the commented line. The pointer s has to be included within the parentheses. The correct code:

scanf("%d",&( (*s)->a[++(*s)->head]));

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

Compare two columns using pandas

You could use apply() and do something like this

df['que'] = df.apply(lambda x : x['one'] if x['one'] >= x['two'] and x['one'] <= x['three'] else "", axis=1)

or if you prefer not to use a lambda

def que(x):
    if x['one'] >= x['two'] and x['one'] <= x['three']:
        return x['one']
    return ''
df['que'] = df.apply(que, axis=1)

How to loop and render elements in React.js without an array of objects to map?

You can still use map if you can afford to create a makeshift array:

{
    new Array(this.props.level).fill(0).map((_, index) => (
        <span className='indent' key={index}></span>
    ))
}

This works because new Array(n).fill(x) creates an array of size n filled with x, which can then aid map.

array-fill

How to redirect the output of the time command to a file in Linux?

If you want just the time in a shell variable then this works:

var=`{ time <command> ; } 2>&1 1>/dev/null`

C Macro definition to determine big endian or little endian machine?

If you are looking for a compile time test and you are using gcc, you can do:

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__

See gcc documentation for more information.

How to increase an array's length

First things first:

  • In Java, once an array is created, it's length is fixed. Arrays cannot be resized.
  • You can copy the elements of an array to a new array with a different size. The easiest way to do this, is to use one of the Arrays.copyOf() methods.
  • If you need a collection of variable size, you're probably better off using an ArrayList instead of an array.

That being said, there might be situations where you have no other choice than to change the size of an array that is created somewhere outside of your code.1 The only way to do that is to manipulate the generated bytecode of the code that creates the array.

Proof-of-concept

Below is a small proof-of-concept project that uses Java instrumentation to dynamically change the size of an array2. The sample project is a maven project with the following structure:

.
+- pom.xml
+- src
   +- main
      +- java
         +- com
            +- stackoverflow
               +- agent
                  +- Agent.java
                  +- test
                     +- Main.java

Main.java

This file contains the target class of which we're going to manipulate the bytecode:

package com.stackoverflow.agent.test;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] array = {"Zero"};

        fun(array);

        System.out.println(Arrays.toString(array));
    }

    public static void fun(String[] array) {
        array[1] = "One";
        array[2] = "Two";
        array[3] = "Three";
        array[4] = "Four";
    }
}

In the main method, we create a String array of size 1. In the fun method, 4 additional values are assigned outside of the array's bounds. Running this code as-is will obviously result in an error.

Agent.java

This file contains the class that will perform the bytecode manipulation:

package com.stackoverflow.agent;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

public class Agent {
    public static void premain(String args, Instrumentation instrumentation) {
        instrumentation.addTransformer(new ClassFileTransformer() {
            public byte[] transform(ClassLoader l, String name, Class<?> c,
                    ProtectionDomain d, byte[] b) {

                if (name.equals("com/stackoverflow/agent/test/Main")) {
                    byte iconst1 = (byte) 0x04;
                    byte iconst5 = (byte) 0x08;
                    byte anewarray = (byte) 0xbd;

                    for (int i = 0; i <= b.length - 1; i++) {
                        if (b[i] == iconst1 && b[i + 1] == anewarray) {
                            b[i] = iconst5;
                        }
                    }

                    return b;
                }

                return null;
            }
        });
    }
}

On the bytecode level, the creation of the String array in the Main class consists of two commands:

  • iconst_1, which pushes an int constant with value 1 onto the stack (0x04).
  • anewarray, which pops the value of the stack and creates a reference array3 of the same size (0xbd). The above code looks for that combination of commands in the Main class, and if found, replaces the const_1 command with a const_5 command (0x08), effectively changing the dimensions of the array to 5.4

pom.xml

The maven POM file is used to build the application JAR and configure the main class and the Java agent class.5

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.stackoverflow</groupId>
  <artifactId>agent</artifactId>
  <version>1.0-SNAPSHOT</version>

  <build>
    <finalName>${project.artifactId}</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.1.1</version>
        <configuration>
          <archive>
            <manifestEntries>
              <Main-Class>com.stackoverflow.agent.test.Main</Main-Class>
              <Premain-Class>com.stackoverflow.agent.Agent</Premain-Class>
              <Agent-Class>com.stackoverflow.agent.Agent</Agent-Class>
              <Can-Retransform-Classes>true</Can-Retransform-Classes>
            </manifestEntries>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Build and execute

The sample project can be built using the standard mvn clean package command.

Executing without referencing the agent code will yield the expected error:

$> java -jar target/agent.jar 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
        at com.stackoverflow.agent.test.Main.fun(Main.java:15)
        at com.stackoverflow.agent.test.Main.main(Main.java:9)

While executing with the agent code will yield:

$> java -javaagent:target/agent.jar -jar target/agent.jar
[Zero, One, Two, Three, Four]

This demonstrates that the size of the array was successfully changed using bytecode manipulation.


1 Such situations came up in questions here and here, the latter of which prompted me to write this answer.
2 Technically, the sample project doesn't resize the array. It just creates it with a different size than the size specified in code. Actually resizing an existing array while maintaining its reference and copying its elements would be a fair bit more complicated.
3 For a primitive array, the corresponding bytecode operation would be newarray (0xbc) instead.
4 As noted, this is just a proof of concept (and a very hacky one at that). Instead of randomly replacing bytes, a more robust implementation could use a bytecode manipulation library like ASM to insert a pop command followed by an sipush command before any newarray or anewarray command. Some more hints towards that solution can be found in the comments to this answer.
5 In a real-world scenario, the agent code would obviously be in a separate project.

Removing the first 3 characters from a string

Just use substring: "apple".substring(3); will return le

Extracting substrings in Go

To get substring

  1. find position of "sp"

  2. cut string with array-logical

https://play.golang.org/p/0Redd_qiZM

How to send custom headers with requests in Swagger UI?

Golang/go-swagger example: https://github.com/go-swagger/go-swagger/issues/1416

// swagger:parameters opid
type XRequestIdHeader struct {
    // in: header
    // required: true
    XRequestId string `json:"X-Request-Id"`
}

...
    // swagger:operation POST /endpoint/ opid
    // Parameters:
    // - $ref: #/parameters/XRequestIDHeader

How to export all collections in MongoDB?

There are multiple options depending on what you want to do

1) If you want to export your database to another mongo database, you should use mongodump. This creates a folder of BSON files which have metadata that JSON wouldn't have.

mongodump
mongorestore --host mongodb1.example.net --port 37017 dump/

2) If you want to export your database into JSON you can use mongoexport except you have to do it one collection at a time (this is by design). However I think it's easiest to export the entire database with mongodump and then convert to JSON.

# -d is a valid option for both mongorestore and mongodump

mongodump -d <DATABASE_NAME>
for file in dump/*/*.bson; do bsondump $file > $file.json; done

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Solution to the problem

as mentioned by Uberfuzzy [ real cause of problem ]

If you look at the PHP constant [PATH_SEPARATOR][1], you will see it being ":" for you.

If you break apart your string ".:/usr/share/pear:/usr/share/php" using that character, you will get 3 parts

  • . (this means the current directory your code is in)
  • /usr/share/pear
  • /usr/share/ph

Any attempts to include()/require() things, will look in these directories, in this order.

It is showing you that in the error message to let you know where it could NOT find the file you were trying to require()

That was the cause of error.

Now coming to solution

  1. Step 1 : Find you php.ini file using command php --ini ( in my case : /etc/php5/cli/php.ini )
  2. Step 2 : find include_path in vi using esc then press /include_path then enter
  3. Step 3 : uncomment that line if commented and include your server directory, your path should look like this include_path = ".:/usr/share/php:/var/www/<directory>/"
  4. Step 4 : Restart apache sudo service apache2 restart

This is it. Hope it helps.

How to load local file in sc.textFile, instead of HDFS

I tried the following and it worked from my local file system.. Basically spark can read from local, HDFS and AWS S3 path

listrdd=sc.textFile("file:////home/cloudera/Downloads/master-data/retail_db/products")

How can I execute a python script from an html button?

It is discouraged and problematic yet doable. What you need is a custom URI scheme ie. You need to register and configure it on your machine and then hook an url with that scheme to the button.

URI scheme is the part before :// in an URI. Standard URI schemes are for example https or ftp or file. But there are custom like fx. mongodb. What you need is your own e.g. mypythonscript. It can be configured to exec the script or even just python with the script name in the params etc. It is of course a tradeoff between flexibility and security.

You can find more details in the links:

https://support.shotgunsoftware.com/hc/en-us/articles/219031308-Launching-applications-using-custom-browser-protocols

https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx

EDIT: Added more details about what an custom scheme is.

Fastest way to iterate over all the chars in a String

This is just micro-optimisation that you shouldn't worry about.

char[] chars = str.toCharArray();

returns you a copy of str character arrays (in JDK, it returns a copy of characters by calling System.arrayCopy).

Other than that, str.charAt() only checks if the index is indeed in bounds and returns a character within the array index.

The first one doesn't create additional memory in JVM.

Functions that return a function

Create a variable:

var thing1 = undefined;

Declare a Function:

function something1 () {
    return "Hi there, I'm number 1!";
}

Alert the value of thing1 (our first variable):

alert(thing1); // Outputs: "undefined".

Now, if we wanted thing1 to be a reference to the function something1, meaning it would be the same thing as our created function, we would do:

thing1 = something1;

However, if we wanted the return value of the function then we must assign it the return value of the executed function. You execute the function by using parenthesis:

thing1 = something1(); // Value of thing1: "Hi there, I'm number 1!" 

Ruby max integer

There is no maximum since Ruby 2.4, as Bignum and Fixnum got unified into Integer. see Feature #12005

> (2 << 1000).is_a? Fixnum
(irb):322: warning: constant ::Fixnum is deprecated
=> true

> 1.is_a? Bignum
(irb):314: warning: constant ::Bignum is deprecated
=> true

> (2 << 1000).class
=> Integer

There won't be any overflow, what would happen is an out of memory.

Excel SUMIF between dates

this works, and can be adapted for weeks or anyother frequency i.e. weekly, quarterly etc...

=SUMIFS(B12:B11652,A12:A11652,">="&DATE(YEAR(C12),MONTH(C12),1),A12:A11652,"<"&DATE(YEAR(C12),MONTH(C12)+1,1))

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Just add autofocus in first input or textarea.

<input type="text" name="name" id="xax" autofocus="autofocus" />

Responsive timeline UI with Bootstrap3

"Timeline (responsive)" snippet:

This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.

You can fork this and use it as a great starting point for your specific expectations:


Here are two screenshots I took for you... wide and thin:

wide thin

declaring a priority_queue in c++ with a custom comparator

In case this helps anyone :

static bool myFunction(Node& p1, Node& p2) {}
priority_queue <Node, vector<Node>, function<bool(Node&, Node&)>> pq1(myFunction);

Initializing a list to a known number of elements in Python

One obvious and probably not efficient way is

verts = [0 for x in range(1000)]

Note that this can be extended to 2-dimension easily. For example, to get a 10x100 "array" you can do

verts = [[0 for x in range(100)] for y in range(10)]

Regular Expression Match to test for a valid year

Years from 1000 to 2999

^[12][0-9]{3}$

For 1900-2099

^(19|20)\d{2}$

How to declare and add items to an array in Python?

{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].

To initialize an empty list do this:

my_list = []

or

my_list = list()

To add elements to the list, use append

my_list.append(12)

To extend the list to include the elements from another list use extend

my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]

To remove an element from a list use remove

my_list.remove(2)

Dictionaries represent a collection of key/value pairs also known as an associative array or a map.

To initialize an empty dictionary use {} or dict()

Dictionaries have keys and values

my_dict = {'key':'value', 'another_key' : 0}

To extend a dictionary with the contents of another dictionary you may use the update method

my_dict.update({'third_key' : 1})

To remove a value from a dictionary

del my_dict['key']

How to use zIndex in react-native

Use elevation instead of zIndex for android devices

elevatedElement: {
  zIndex: 3, // works on ios
  elevation: 3, // works on android
}

This worked fine for me!

How do I bind a List<CustomObject> to a WPF DataGrid?

Actually, to properly support sorting, filtering, etc. a CollectionViewSource should be used as a link between the DataGrid and the list, like this:

<Window.Resources>
  <CollectionViewSource x:Key="ItemCollectionViewSource" CollectionViewType="ListCollectionView"/>
</Window.Resources>   

The DataGrid line looks like this:

<DataGrid
  DataContext="{StaticResource ItemCollectionViewSource}"
  ItemsSource="{Binding}"
  AutoGenerateColumns="False">  

In the code behind, you link CollectionViewSource with your link.

CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource"));
itemCollectionViewSource.Source = itemList;

For detailed example see my article on CoedProject: http://www.codeproject.com/Articles/683429/Guide-to-WPF-DataGrid-formatting-using-bindings

Multi-dimensional arraylist or list in C#?

You can create a list of lists

   public class MultiDimList: List<List<string>> {  }

or a Dictionary of key-accessible Lists

   public class MultiDimDictList: Dictionary<string, List<int>>  { }
   MultiDimDictList myDicList = new MultiDimDictList ();
   myDicList.Add("ages", new List<int>()); 
   myDicList.Add("Salaries", new List<int>()); 
   myDicList.Add("AccountIds", new List<int>()); 

Generic versions, to implement suggestion in comment from @user420667

  public class MultiDimList<T>: List<List<T>> {  }

and for the dictionary,

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  { }

  // to use it, in client code
   var myDicList = new MultiDimDictList<string, int> ();
   myDicList.Add("ages", new List<T>()); 
   myDicList["ages"].Add(23);
   myDicList["ages"].Add(32);
   myDicList["ages"].Add(18);

   myDicList.Add("salaries", new List<T>());
   myDicList["salaries"].Add(80000);
   myDicList["salaries"].Add(100000);

   myDicList.Add("accountIds", new List<T>()); 
   myDicList["accountIds"].Add(321123);
   myDicList["accountIds"].Add(342653);

or, even better, ...

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  
   {
       public void Add(K key, T addObject)
       {
           if(!ContainsKey(key)) Add(key, new List<T>());
           if (!base[key].Contains(addObject)) base[key].Add(addObject);
       }           
   }


  // and to use it, in client code
    var myDicList = new MultiDimDictList<string, int> ();
    myDicList.Add("ages", 23);
    myDicList.Add("ages", 32);
    myDicList.Add("ages", 18);
    myDicList.Add("salaries", 80000);
    myDicList.Add("salaries", 110000);
    myDicList.Add("accountIds", 321123);
    myDicList.Add("accountIds", 342653);

EDIT: to include an Add() method for nested instance:

public class NestedMultiDimDictList<K, K2, T>: 
           MultiDimDictList<K, MultiDimDictList<K2, T>>: 
{
       public void Add(K key, K2 key2, T addObject)
       {
           if(!ContainsKey(key)) Add(key, 
                  new MultiDimDictList<K2, T>());
           if (!base[key].Contains(key2)) 
               base[key].Add(key2, addObject);
       }    
}

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Options:
    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

get list of pandas dataframe columns based on data type

I use infer_objects()

Docstring: Attempt to infer better dtypes for object columns.

Attempts soft conversion of object-dtyped columns, leaving non-object and unconvertible columns unchanged. The inference rules are the same as during normal Series/DataFrame construction.

df.infer_objects().dtypes

Mount current directory as a volume in Docker on Windows 10

Other solutions for Git Bash provided by others didn't work for me. Apparently there is currently a bug/limitation in Git for Windows. See this and this.

I finally managed to get it working after finding this GitHub thread (which provides some additional solutions if you're interested, which might work for you, but didn't for me).

I ended up using the following syntax:

MSYS_NO_PATHCONV=1 docker run --rm -it -v $(pwd):/usr/src/project gcc:4.9

Note the MSYS_NO_PATHCONV=1 in front of the docker command and $(pwd) - round brackets, lower-case pwd, no quotes, no backslashes.

Also, I'm using Linux containers on Windows if that matters..

I tested this in the new Windows Terminal, ConEmu and GitBash, and all of them worked for me.

Checking if sys.argv[x] is defined

It's an ordinary Python list. The exception that you would catch for this is IndexError, but you're better off just checking the length instead.

if len(sys.argv) >= 2:
  startingpoint = sys.argv[1]
else:
  startingpoint = 'blah'

Clean out Eclipse workspace metadata

One of the things that you might want to try out is starting eclipse with the -clean option. If you have chosen to have eclipse use the same workspace every time then there is nothing else you need to do after that. With that option in place the workspace should be cleaned out.

However, if you don't have a default workspace chosen, when opening up eclipse you will be prompted to choose the workspace. At this point, choose the workspace you want cleaned up.

See "How to run eclipse in clean mode" and "Keeping Eclipse running clean" for more details.

How do I add a Font Awesome icon to input field?

simple way for new font awesome

  <div class="input-group">
                    <input type="text" class="form-control" placeholder="Search" name="txtSearch"  >
                    <div class="input-group-btn">
                        <button class="btn btn-default" type="submit"><i class="fas fa-search"></i></button>
                    </div>
                </div>

iOS Launching Settings -> Restrictions URL Scheme

In iOS 9 it works again!

To open Settings > General > Keyboard, I use:

prefs:root=General&path=Keyboard

Moreover, it is possible to go farther to Keyboards:

prefs:root=General&path=Keyboard/KEYBOARDS

Append Char To String in C?

I do not think you can declare a string like that in c. You may only do that for const char* and of course you can not modify a const char * as it is const.

You may use dynamic char array but you will have to take care of the reallocation.

EDIT: in fact this syntax compiles correctly. Still you can should not modify what str points to if it is initialized in the way you do it (from string literal)

Why does Boolean.ToString output "True" and not "true"

Only people from Microsoft can really answer that question. However, I'd like to offer some fun facts about it ;)

First, this is what it says in MSDN about the Boolean.ToString() method:

Return Value

Type: System.String

TrueString if the value of this instance is true, or FalseString if the value of this instance is false.

Remarks

This method returns the constants "True" or "False". Note that XML is case-sensitive, and that the XML specification recognizes "true" and "false" as the valid set of Boolean values. If the String object returned by the ToString() method is to be written to an XML file, its String.ToLower method should be called first to convert it to lowercase.

Here comes the fun fact #1: it doesn't return TrueString or FalseString at all. It uses hardcoded literals "True" and "False". Wouldn't do you any good if it used the fields, because they're marked as readonly, so there's no changing them.

The alternative method, Boolean.ToString(IFormatProvider) is even funnier:

Remarks

The provider parameter is reserved. It does not participate in the execution of this method. This means that the Boolean.ToString(IFormatProvider) method, unlike most methods with a provider parameter, does not reflect culture-specific settings.

What's the solution? Depends on what exactly you're trying to do. Whatever it is, I bet it will require a hack ;)

How are POST and GET variables handled in Python?

It somewhat depends on what you use as a CGI framework, but they are available in dictionaries accessible to the program. I'd point you to the docs, but I'm not getting through to python.org right now. But this note on mail.python.org will give you a first pointer. Look at the CGI and URLLIB Python libs for more.

Update

Okay, that link busted. Here's the basic wsgi ref

Using R to list all files with a specified extension

Try this which uses globs rather than regular expressions so it will only pick out the file names that end in .dbf

filenames <- Sys.glob("*.dbf")

How to convert milliseconds into a readable date?

This is a solution. Later you can split by ":" and take the values of the array

 /**
 * Converts milliseconds to human readeable language separated by ":"
 * Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
 */
function dhm(t){
    var cd = 24 * 60 * 60 * 1000,
        ch = 60 * 60 * 1000,
        d = Math.floor(t / cd),
        h = '0' + Math.floor( (t - d * cd) / ch),
        m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
    return [d, h.substr(-2), m.substr(-2)].join(':');
}

//Example
var delay = 190980000;                   
var fullTime = dhm(delay);
console.log(fullTime);

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

Key should be readable by the logged in user.

Try this:

chmod 400 ~/.ssh/Key file
chmod 400 ~/.ssh/vm_id_rsa.pub

UICollectionView spacing margins

Swift 4

    let flow = collectionView.collectionViewLayout as! UICollectionViewFlowLayout 
    // If you create collectionView programmatically then just create this flow by UICollectionViewFlowLayout() and init a collectionView by this flow.

    let itemSpacing: CGFloat = 3
    let itemsInOneLine: CGFloat = 3
    flow.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

    //collectionView.frame.width is the same as  UIScreen.main.bounds.size.width here.
    let width = UIScreen.main.bounds.size.width - itemSpacing * CGFloat(itemsInOneLine - 1) 
    flow.itemSize = CGSize(width: floor(width/itemsInOneLine), height: width/itemsInOneLine)
    flow.minimumInteritemSpacing = 3
    flow.minimumLineSpacing = itemSpacing

EDIT

If you want to change to scrollDirction horizontally:

flow.scrollDirection = .horizontal

NOTE

If you set items in one lines isn't correctly, check if your collection view has paddings. That is:

let width = UIScreen.main.bounds.size.width - itemSpacing * CGFloat(itemsInOneLine - 1)

should be the collectionView width.

enter image description here

How do I list all cron jobs for all users?

Under Ubuntu or debian, you can view crontab by /var/spool/cron/crontabs/ and then a file for each user is in there. That's only for user-specific crontab's of course.

For Redhat 6/7 and Centos, the crontab is under /var/spool/cron/.

How do I make a semi transparent background?

Good to know

Some web browsers have difficulty to render text with shadows on top of transparent background. Then you can use a semi transparent 1x1 PNG image as a background.

Note

Remember that IE6 don’t support PNG files.

How to delete/truncate tables from Hadoop-Hive?

To Truncate:

hive -e "TRUNCATE TABLE IF EXISTS $tablename"

To Drop:

hive -e "Drop TABLE IF EXISTS $tablename"

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

Replace

import { Router, Route, Link, browserHistory } from 'react-router';

With

import { BrowserRouter as Router, Route } from 'react-router-dom';

It will start working. It is because react-router-dom exports BrowserRouter

Is it possible to have multiple statements in a python lambda expression?

to demonstrate the lambda x:[f1(),f2()] effect which enables us to execute multiple functions in lambda. it also demonstrates the single line if else conditions if you really want to shrink the code.

  • note that f1() can be a lambda function also(recursive lambda or lambda within lambda). and that inner lambda can be a statement/function of your choice.
  • you can also put exec('statement') for example lambda x:[exec('a=[1]'),exec('b=2')]

a python implementation of touch(linux) command which creates empty files if they are not already existing.

def touch(fpath):
    check= os.path.exists(fpath)
    (lambda fname1:[open(fname1,"w+",errors="ignore").write(""),print('Touched',fname1)] 
    if not check else None) (fpath)

will print [ Touched fpath ] where fpath is file path given as input. will do nothing if file already exist.

the (lambda x: [ f(x), f2(x) ] ) (inp) <- we pass the 'inp' as input to lambda which in this case is the fpath.

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

In Alpine linux you should do:

apk add curl-dev python3-dev libressl-dev

<img>: Unsafe value used in a resource URL context

import {DomSanitizationService} from '@angular/platform-browser';
@Component({
 templateUrl: 'build/pages/veeu/veeu.html'
 })
  export class VeeUPage {
     trustedURL:any;
      static get parameters() {
               return [NavController, App, MenuController, 
              DomSanitizationService];
        }
      constructor(nav, app, menu, sanitizer) {
        this.app = app;
        this.nav = nav;
        this.menu = menu;
        this.sanitizer = sanitizer;  
        this.trustedURL  = sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
        } 
 }



 <iframe [src]='trustedURL' width="640" height="360" frameborder="0"
   webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>


User property binding instead of function.

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert an integer to a string in any base?

Well I personally use this function, written by me

import string

def to_base(value, base, digits=string.digits+string.ascii_letters):    # converts decimal to base n

    digits_slice = digits[0:base]

    temporary_var = value
    data = [temporary_var]

    while True:
        temporary_var = temporary_var // base
        data.append(temporary_var)
        if temporary_var < base:
            break

    result = ''
    for each_data in data:
        result += digits_slice[each_data % base]
    result = result[::-1]

    return result

This is how you can use it

print(to_base(7, base=2))

Output: "111"

print(to_base(23, base=3))

Output: "212"

Please feel free to suggest improvements in my code.

Is there any kind of hash code function in JavaScript?

What you described is covered by Harmony WeakMaps, part of the ECMAScript 6 specification (next version of JavaScript). That is: a set where the keys can be anything (including undefined) and is non-enumerable.

This means it's impossible to get a reference to a value unless you have a direct reference to the key (any object!) that links to it. It's important for a bunch of engine implementation reasons relating to efficiency and garbage collection, but it's also super cool for in that it allows for new semantics like revokable access permissions and passing data without exposing the data sender.

From MDN:

var wm1 = new WeakMap(),
    wm2 = new WeakMap();
var o1 = {},
    o2 = function(){},
    o3 = window;

wm1.set(o1, 37);
wm1.set(o2, "azerty");
wm2.set(o1, o2); // A value can be anything, including an object or a function.
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // Keys and values can be any objects. Even WeakMaps!

wm1.get(o2); // "azerty"
wm2.get(o2); // Undefined, because there is no value for o2 on wm2.
wm2.get(o3); // Undefined, because that is the set value.

wm1.has(o2); // True
wm2.has(o2); // False
wm2.has(o3); // True (even if the value itself is 'undefined').

wm1.has(o1);   // True
wm1.delete(o1);
wm1.has(o1);   // False

WeakMaps are available in current Firefox, Chrome and Edge. They're also supported in Node v7 , and in v6 with the --harmony-weak-maps flag.

Print values for multiple variables on the same line from within a for-loop

Try out cat and sprintf in your for loop.

eg.

cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))

See here

Shortest way to check for null and assign another value if not

With C#6 there is a slightly shorter way for the case where planRec.approved_by is not a string:

this.approved_by = planRec.approved_by?.ToString() ?? "";

How to print a int64_t type in C

Coming from the embedded world, where even uclibc is not always available, and code like

uint64_t myval = 0xdeadfacedeadbeef; printf("%llx", myval);

is printing you crap or not working at all -- i always use a tiny helper, that allows me to dump properly uint64_t hex:

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

char* ullx(uint64_t val)
{
    static char buf[34] = { [0 ... 33] = 0 };
    char* out = &buf[33];
    uint64_t hval = val;
    unsigned int hbase = 16;

    do {
        *out = "0123456789abcdef"[hval % hbase];
        --out;
        hval /= hbase;
    } while(hval);

    *out-- = 'x', *out = '0';

    return out;
}

How to retrieve data from a SQL Server database in C#?

    DataTable formerSlidesData = new DataTable();
    DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
                if (formerSlidesData.Rows.Count > 0)
                {
                    DataRow rowa = formerSlidesData.Rows[0];

                    cabinet = Convert.ToInt32(rowa["cabinet"]);
                    box = Convert.ToInt32(rowa["box"]);
                    drawer = Convert.ToInt32(rowa["drawer"]);
                }

"Register" an .exe so you can run it from any command line in Windows

Add to the PATH, steps below (Windows 10):

  1. Type in search bar "environment..." and choose Edit the system environment variables which opens up the System Properties window
  2. Click the Environment Variables... button
  3. In the Environment Variables tab, double click the Path variable in the System variables section
  4. Add the path to the folder containing the .exe to the Path by double clicking on the empty line and paste the path.
  5. Click ok and exit. Open a new cmd prompt and hit the command from any folder and it should work.

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

This is a slight modification to the earlier answers...

There is no need for $parse

angular.directive('input', [function () {
  'use strict';

  var directiveDefinitionObject = {
    restrict: 'E',
    require: '?ngModel',
    link: function postLink(scope, iElement, iAttrs, ngModelController) {
      if (iAttrs.value && ngModelController) {
        ngModelController.$setViewValue(iAttrs.value);
      }
    }
  };

  return directiveDefinitionObject;
}]);

Port 443 in use by "Unable to open process" with PID 4

I had a similar issue where port 443 was blocked by PID 4. After breaking my head for several hours I found the command netsh show urlacl which gave me an idea of the system process blocking the port.

To run command run cmd or windows shell in administrator mode.

netsh

http

show urlacl

I got response a which showed 443 was blocked by NT Service SSTPSvc Reserved URL

Response

https://+:443/sra_{BA195980-CD49-458b-9E23-C84EE0ADCD75}/ User: NT SERVICE\SstpSvc Listen: Yes Delegate: Yes User: BUILTIN\Administrators Listen: No Delegate: No User: NT AUTHORITY\SYSTEM Listen: Yes Delegate: Yes

With this information I followed the microsoft link to change the listening port for SSTP based vpn. https://support.microsoft.com/en-in/kb/947032

This resolved my port issue.

Passing parameter via url to sql server reporting service

Try changing "Reports" to "ReportServer" in your url. For that just access this http://host/ReportServer/ and from there you can go to the report pages. There append your parmaters like this &<parameter>=<value>

For more detailed information:

http://dobrzanski.net/2008/08/11/reporting-services-problem-with-passing-parameters-directly-in-the-url/

https://www.mssqltips.com/sqlservertip/1336/pass-parameters-and-options-with-a-url-in-sql-reporting-services/

String was not recognized as a valid DateTime " format dd/MM/yyyy"

Based on this reference, the next approach worked for me:

// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017" 
var formatInfo = new DateTimeFormatInfo()
{
     ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);

Address validation using Google Maps API

The answer probably depends how critical it is for you to receive support and possible customization for this service.

Google can certainly do this. Look into their XML and Geocoding API's. You should be able to craft an XML message asking Google to return Map coordinates for a given address. If the address is not found (invalid), you will receive an appropriate response. Here's a useful page: http://code.google.com/apis/maps/documentation/services.html#XML_Requests

Note that Google's aim in providing the Maps API is to plot addresses on actual maps. While you can certainly use the data for other purposes, you are at the mercy of Google should one of their maps not exactly correspond to your legal or commercial address validation needs. If you paid for one of the services you mentioned, you would likely be able to receive support should certain addresses not resolve the way you expect them to.

In other words, you get what you pay for ;) . If you have the time, though, why not try implementing a Google-based solution then going from there? The API looks pretty slick, and it's free, after all.

Connection string using Windows Authentication

For connecting to a sql server database via Windows authentication basically needs which server you want to connect , what is your database name , Integrated Security info and provider name.

Basically this works:

<connectionStrings>      
<add name="MyConnectionString"
         connectionString="data source=ServerName;
   Initial Catalog=DatabaseName;Integrated Security=True;"
         providerName="System.Data.SqlClient" />
</connectionStrings> 

Setting Integrated Security field true means basically you want to reach database via Windows authentication, if you set this field false Windows authentication will not work.

It is also working different according which provider you are using.

  • SqlClient both Integrated Security=true; or IntegratedSecurity=SSPI; is working.

  • OleDb it is Integrated Security=SSPI;

  • Odbc it is Trusted_Connection=yes;
  • OracleClient it is Integrated Security=yes;

Integrated Security=true throws an exception when used with the OleDb provider.

How do I check if an element is really visible with JavaScript?

I don't know how much of this is supported in older or not-so-modern browsers, but I'm using something like this (without the neeed for any libraries):

function visible(element) {
  if (element.offsetWidth === 0 || element.offsetHeight === 0) return false;
  var height = document.documentElement.clientHeight,
      rects = element.getClientRects(),
      on_top = function(r) {
        var x = (r.left + r.right)/2, y = (r.top + r.bottom)/2;
        return document.elementFromPoint(x, y) === element;
      };
  for (var i = 0, l = rects.length; i < l; i++) {
    var r = rects[i],
        in_viewport = r.top > 0 ? r.top <= height : (r.bottom > 0 && r.bottom <= height);
    if (in_viewport && on_top(r)) return true;
  }
  return false;
}

It checks that the element has an area > 0 and then it checks if any part of the element is within the viewport and that it is not hidden "under" another element (actually I only check on a single point in the center of the element, so it's not 100% assured -- but you could just modify the script to itterate over all the points of the element, if you really need to...).

Update

Modified on_top function that check every pixel:

on_top = function(r) {
  for (var x = Math.floor(r.left), x_max = Math.ceil(r.right); x <= x_max; x++)
  for (var y = Math.floor(r.top), y_max = Math.ceil(r.bottom); y <= y_max; y++) {
    if (document.elementFromPoint(x, y) === element) return true;
  }
  return false;
};

Don't know about the performance :)

Shadow Effect for a Text in Android?

put these in values/colors.xml

<resources>
    <color name="light_font">#FBFBFB</color>
    <color name="grey_font">#ff9e9e9e</color>
    <color name="text_shadow">#7F000000</color>
    <color name="text_shadow_white">#FFFFFF</color>
</resources>

Then in your layout xml here are some example TextView's

Example of Floating text on Light with Dark shadow

<TextView android:id="@+id/txt_example1"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textSize="14sp"
                  android:textStyle="bold"
                  android:textColor="@color/light_font"
                  android:shadowColor="@color/text_shadow"
                  android:shadowDx="1"
                  android:shadowDy="1"
                  android:shadowRadius="2" />

enter image description here

Example of Etched text on Light with Dark shadow

<TextView android:id="@+id/txt_example2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/light_font"
                android:shadowColor="@color/text_shadow"
                android:shadowDx="-1"
                android:shadowDy="-1"
                android:shadowRadius="1" />

enter image description here

Example of Crisp text on Light with Dark shadow

<TextView android:id="@+id/txt_example3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/grey_font"
                android:shadowColor="@color/text_shadow_white"
                android:shadowDx="-2"
                android:shadowDy="-2"
                android:shadowRadius="1" />

enter image description here

Notice the positive and negative values... I suggest to play around with the colors/values yourself but ultimately you can adjust these settings to get the effect your looking for.

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Nonatomic

Nonatomic will not generate threadsafe routines thru @synthesize accessors. atomic will generate threadsafe accessors so atomic variables are threadsafe (can be accessed from multiple threads without botching of data)

Copy

copy is required when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

Assign

Assign is somewhat the opposite to copy. When calling the getter of an assign property, it returns a reference to the actual data. Typically you use this attribute when you have a property of primitive type (float, int, BOOL...)

Retain

retain is required when the attribute is a pointer to a reference counted object that was allocated on the heap. Allocation should look something like:

NSObject* obj = [[NSObject alloc] init]; // ref counted var

The setter generated by @synthesize will add a reference count to the object when it is copied so the underlying object is not autodestroyed if the original copy goes out of scope.

You will need to release the object when you are finished with it. @propertys using retain will increase the reference count and occupy memory in the autorelease pool.

Strong

strong is a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.

This is a good website to learn about strong and weak for iOS 5. http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1

Weak

weak is similar to strong except that it won't increase the reference count by 1. It does not become an owner of that object but just holds a reference to it. If the object's reference count drops to 0, even though you may still be pointing to it here, it will be deallocated from memory.

The above link contain both Good information regarding Weak and Strong.

How is an HTTP POST request made in node.js?

There are dozens of open-source libraries available that you can use to making an HTTP POST request in Node.

1. Axios (Recommended)

const axios = require('axios');

const data = {
    name: 'John Doe',
    job: 'Content Writer'
};

axios.post('https://reqres.in/api/users', data)
    .then((res) => {
        console.log(`Status: ${res.status}`);
        console.log('Body: ', res.data);
    }).catch((err) => {
        console.error(err);
    });

2. Needle

const needle = require('needle');

const data = {
    name: 'John Doe',
    job: 'Content Writer'
};

needle('post', 'https://reqres.in/api/users', data, {json: true})
    .then((res) => {
        console.log(`Status: ${res.statusCode}`);
        console.log('Body: ', res.body);
    }).catch((err) => {
        console.error(err);
    });

3. Request

const request = require('request');

const options = {
    url: 'https://reqres.in/api/users',
    json: true,
    body: {
        name: 'John Doe',
        job: 'Content Writer'
    }
};

request.post(options, (err, res, body) => {
    if (err) {
        return console.log(err);
    }
    console.log(`Status: ${res.statusCode}`);
    console.log(body);
});

4. Native HTTPS Module

const https = require('https');

const data = JSON.stringify({
    name: 'John Doe',
    job: 'Content Writer'
});

const options = {
    hostname: 'reqres.in',
    path: '/api/users',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
    }
};


const req = https.request(options, (res) => {
    let data = '';

    console.log('Status Code:', res.statusCode);

    res.on('data', (chunk) => {
        data += chunk;
    });

    res.on('end', () => {
        console.log('Body: ', JSON.parse(data));
    });

}).on("error", (err) => {
    console.log("Error: ", err.message);
});

req.write(data);
req.end();

For details, check out this article.

Default instance name of SQL Server Express

If you navigate to where you have installed SQLExpress, e.g.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn

You can run SQLLocalDB.exe and get a list of the all instances installed on your machine.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn>SqlLocalDB.exe info
MSSQLLocalDB
ProjectsV12
v11.0

Then you can get further information on the instance.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn>SqlLocalDB.exe info MSSQLLocalDB Name: MSSQLLocalDB
Version: 13.0.1601.5
Shared name:
Owner: Domain\User
Auto-create: Yes
State: Stopped
Last start time: 22/09/2016 10:19:33
Instance pipe name:

How do I correctly upgrade angular 2 (npm) to the latest version?

Just start here:

https://update.angular.io

Select the version you're using and it will give you a step by step guide.

I recommend choosing 'Advanced' to see all steps. Complexity is a relative concept - and I don't know whose stupid idea this feature was, but if you select 'Basic' it won't show you all steps needed and you may miss something important that your otherwise 'Basic' application is using.

enter image description here

As of version 6 there is a new Angular CLI command ng update which intelligently goes through your dependencies and performs checks to make sure you're updating the right things :-)

The steps will outline how to use it :-)

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

If you need one single regex, try:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

A short explanation:

(?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z])        // use positive look ahead to see if at least one upper case letter exists
(?=.*\d)           // use positive look ahead to see if at least one digit exists
(?=.*\W])        // use positive look ahead to see if at least one non-word character exists

And I agree with SilentGhost, \W might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?] (feel free to add more of course!)

Reading CSV file and storing values into an array

Still wrong. You need to compensate for "" in quotes. Here is my solution Microsoft style csv.

               /// <summary>
    /// Microsoft style csv file.  " is the quote character, "" is an escaped quote.
    /// </summary>
    /// <param name="fileName"></param>
    /// <param name="sepChar"></param>
    /// <param name="quoteChar"></param>
    /// <param name="escChar"></param>
    /// <returns></returns>
    public static List<string[]> ReadCSVFileMSStyle(string fileName, char sepChar = ',', char quoteChar = '"')
    {
        List<string[]> ret = new List<string[]>();

        string[] csvRows = System.IO.File.ReadAllLines(fileName);

        foreach (string csvRow in csvRows)
        {
            bool inQuotes = false;
            List<string> fields = new List<string>();
            string field = "";
            for (int i = 0; i < csvRow.Length; i++)
            {
                if (inQuotes)
                {
                    // Is it a "" inside quoted area? (escaped litteral quote)
                    if(i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i+1] == quoteChar)
                    {
                        i++;
                        field += quoteChar;
                    }
                    else if(csvRow[i] == quoteChar)
                    {
                        inQuotes = false;
                    }
                    else
                    {
                        field += csvRow[i];
                    }
                }
                else // Not in quoted region
                {
                     if (csvRow[i] == quoteChar)
                    {
                        inQuotes = true;
                    }
                    if (csvRow[i] == sepChar)
                    {
                        fields.Add(field);
                        field = "";
                    }
                    else 
                    {
                        field += csvRow[i];
                    }
                }
            }
            if (!string.IsNullOrEmpty(field))
            {
                fields.Add(field);
                field = "";
            }
            ret.Add(fields.ToArray());
        }

        return ret;
    }
}

how to remove css property using javascript?

removeProperty will remove a style from an element.

Example:

div.style.removeProperty('zoom');

MDN documentation page:
CSSStyleDeclaration.removeProperty

Properly escape a double quote in CSV

Not only double quotes, you will be in need for single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

Use fputcsv() to write, and fgetcsv() to read, which will take care of all.

How to draw a graph in PHP?

By far the easiest solution is to just use the Google Chart API http://code.google.com/apis/chart/

You can make bar graphs, pie charts, use 3D, and it's as easy as building a url with some parameters. See the simple example below.

This Pie Chart is really easy to make

Batch script to install MSI

Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like

  • Using start /wait
  • Using !ERRORLEVEL! variable instead of %ERRORLEVEL%
  • Using SetLocal EnableDelayedExpansion

Nothing works and what mostly annoys me it's the fact that it works in the command line.

Hide horizontal scrollbar on an iframe?

I'd suggest doing this with a combination of

  1. CSS overflow-y: hidden;
  2. scrolling="no" (for HTML4)
  3. and seamless="seamless" (for HTML5)*

* The seamless attribute has been removed from the standard, and no browsers support it.


_x000D_
_x000D_
.foo {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  overflow-y: hidden;_x000D_
}
_x000D_
<iframe src="https://bing.com" _x000D_
        class="foo" _x000D_
        scrolling="no" >_x000D_
</iframe>
_x000D_
_x000D_
_x000D_

iCheck check if checkbox is checked

this works for me... try it

_x000D_
_x000D_
// Check #x_x000D_
$( "#x" ).prop( "checked", true );_x000D_
 _x000D_
// Uncheck #x_x000D_
$( "#x" ).prop( "checked", false );
_x000D_
_x000D_
_x000D_

How to generate a GUID in Oracle?

You can run the following query

 select sys_guid() from dual
 union all
 select sys_guid() from dual
 union all 
 select sys_guid() from dual

How to change context root of a dynamic web project in Eclipse?

I'm sure you've moved on by now, but I thought I'd answer anyway.

Some of these answers give workarounds. What actually must happen is that you clean and re-publish your project to "activate" the new URI. This is done by right-clicking your server (in the Servers view) and choosing Clean. Then you start (or restart it). Most of the other answers here suggest you do things that in effect accomplish this.

The file that's changing is workspace/.metadata/.plugins/org.eclipse.wst.server.core/publish/publish.dat unless, that is, you've got more than one server in your workspace in which case it will be publishN.dat on that same path.

Hope this helps somebody.


Not sure if this is proper etiquette or not — I am editing this answer to give exact steps for Eclipse Indigo.

  1. In your project's Properties, choose Web Project Settings.

  2. Change Context root to app.

    screen shot of Eclipse project properties Web Project Settings

  3. Choose Window > Show View > Servers.

  4. Stop the server by either clicking the red square box ("Stop the server" tooltip) or context-click on the server listing to choose "Stop".

  5. On the server you want to use, context-click to choose "Clean…".

    enter image description here

  6. Click OK in this confirmation dialog box.

    Screenshot of dialog asking to update server configuration to match the changed context root

Now you can run your app with the new "app" URL such as:

http://localhost:8080/app/

Doing this outside of Eclipse, on your production server, is even easier --> Rename the war file. Export your Vaadin app as a WAR file (File > Export > Web > WAR file). Move the WAR file to your web server's servlet container such as Tomcat. Rename your WAR file, in this case to app.war. When you start the servlet container, most such as Tomcat will auto-deploy the app, which includes expanding the war file to a folder. In this case, we should see a folder named app. You should be good to go. Test your URL. For a domain such as *example.com" this would be:

http://www.example.com/app/

Vaadin toolkit programmers may need to rebuild their widget set if using visual add ons.

jQuery keypress() event not firing?

Your original code has $('document')... when it should have $(document) without the quotes.

How to rebase local branch onto remote master

Step 1:

git fetch origin

Step 2:

git rebase origin/master

Step 3:(Fix if any conflicts)

git add .

Step 4:

git rebase --continue

Step 5:

git push --force

Google maps Marker Label with multiple characters

You can change easy marker label css without use any extra plugin.

var marker = new google.maps.Marker({
        position: this.overlay_text,
        draggable: true,
        icon: '',
        label: {
          text: this.overlay_field_text,
          color: '#fff',
          fontSize: '20px',
          fontWeight: 'bold',
          fontFamily: 'custom-label'
        },
        map:map
      });
      marker.setMap(map);

$("[style*='custom-label']").css({'text-shadow': '2px 2px #000'})

How to add a linked source folder in Android Studio?

Just in case anyone is interested, heres a complete Java module gradle file that correctly generates and references the built artefacts within an Android multi module application

buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath "net.ltgt.gradle:gradle-apt-plugin:0.15"
    }
}

apply plugin: "net.ltgt.apt"
apply plugin: "java-library"
apply plugin: "idea"

idea {
    module {
        sourceDirs += file("$buildDir/generated/source/apt/main")
        testSourceDirs += file("$buildDir/generated/source/apt/test")
    }
}

dependencies {

    // Dagger 2 and Compiler
    compile "com.google.dagger:dagger:2.15"
    apt "com.google.dagger:dagger-compiler:2.15"
    compile "com.google.guava:guava:24.1-jre"

}

sourceCompatibility = "1.8"
targetCompatibility = "1.8"

React-router v4 this.props.history.push(...) not working

Don't use with Router.

handleSubmit(e){
   e.preventDefault();
   this.props.form.validateFieldsAndScroll((err,values)=>{
      if(!err){
        this.setState({
            visible:false
        });
        this.props.form.resetFields();
        console.log(values.username);
        const path = '/list/';
        this.props.history.push(path);
      }
   })
}

It works well.

Installing a plain plugin jar in Eclipse 3.5

Since the advent of p2, you should be using the dropins directory instead.

To be completely clear create "plugins" under "/dropins" and make sure to restart eclipse with the "-clean" option.

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

Replace the earlier function with the provided one. The simplest solution is:

def __unicode__(self):

    return unicode(self.nom_du_site)

How to leave/exit/deactivate a Python virtualenv

You can use virtualenvwrapper in order to ease the way you work with virtualenv.

Installing virtualenvwrapper:

pip install virtualenvwrapper

If you are using a standard shell, open your ~/.bashrc or ~/.zshrc if you use Oh My Zsh. Add these two lines:

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

To activate an existing virtualenv, use command workon:

$ workon myenv
(myenv)$

In order to deactivate your virtualenv:

(myenv)$ deactivate

Here is my tutorial, step by step on how to install virtualenv and virtualenvwrapper.

Installing Java on OS X 10.9 (Mavericks)

I downloaded manually to here: Java for OS X 2014-001.

After that open your terminal and check the installation with java -version.

EDIT (January, 2015): Also see HT202912, About Java for OS X 2014-001:

enter image description here

Efficiently getting all divisors of a given number

int result_num;
bool flag;

cout << "Number          Divisors\n";

for (int number = 1; number <= 35; number++)
{
    flag = false;
    cout << setw(3) << number << setw(14);

    for (int i = 1; i <= number; i++) 
    {
        result_num = number % i;

        if (result_num == 0 && flag == true)
        {
            cout << "," << i;
        }

        if (result_num == 0 && flag == false)
        {
            cout << i;
        }

        flag = true;
    }

    cout << endl;   
}
cout << "Press enter to continue.....";
cin.ignore();
return 0;
}

Filtering a list based on a list of booleans

filtered_list = [list_a[i] for i in range(len(list_a)) if filter[i]]

How do I loop through items in a list box and then remove those item?

You can't make modification to the collection being iterated within the ForEach block.

A quick fix is to iterate over a copy of the collection. An easy way to make this copy is through the ArrayList constructor. The DataRowView objects in the copied collection will refer to, and be able to modify, the same underlying data as your code.

For Each item As DataRowView In New System.Collections.ArrayList(lbOrdersNeedToBeVoided.Items)

please read http://social.msdn.microsoft.com/Forums/en-AU/vbgeneral/thread/b4d1f649-d78a-4e5b-8ad8-1940e3379bed

Parsing a CSV file using NodeJS

this is my solution to get csv file from external url

const parse = require( 'csv-parse/lib/sync' );
const axios = require( 'axios' );
const readCSV = ( module.exports.readCSV = async ( path ) => {
try {
   const res = await axios( { url: path, method: 'GET', responseType: 'blob' } );
   let records = parse( res.data, {
      columns: true,
      skip_empty_lines: true
    } );

    return records;
 } catch ( e ) {
   console.log( 'err' );
 }

} );
readCSV('https://urltofilecsv');

NLTK and Stopwords Fail #lookuperror

I tried from ubuntu terminal and I don't know why the GUI didn't show up according to tttthomasssss answer. So I followed the comment from KLDavenport and it worked. Here is the summary:

Open your terminal/command-line and type python then

>>> import nltk .>>> nltk.download("stopwords")

This will store the stopwords corpus under the nltk_data. For my case it was /home/myusername/nltk_data/corpora/stopwords.

If you need another corpus then visit nltk data and find the corpus with their ID. Then use the ID to download like we did for stopwords.

Disabling Log4J Output in Java

Set level to OFF (instead of DEBUG, INFO, ....)

TypeLoadException says 'no implementation', but it is implemented

In my case it helped to reset the WinForms Toolbox.

I got the exception when opening a Form in the designer; however, compiling and running the code was possible and the code behaved as expected. The exception occurred in a local UserControl implementing an interface from one of my referenced libraries. The error emerged after this library was updated.

This UserControl was listed in the WinForms Toolbox. Probably Visual Studio kept a reference on an outdated version of the library or was caching an outdated version somewhere.

Here is how I recovered from this situation:

  1. Right click on the WinForms Toolbox and click on Reset Toolbox in the context menu. (This removes custom items from the Toolbox).
    In my case the Toolbox items were restored to their default state; however, the Pointer-arrow was missing in the Toolbox.
  2. Close Visual Studio.
    In my case Visual Studio terminated with a violation exception and aborted.
  3. Restart Visual Studio.
    Now everything is running smoothly.

Get checkbox list values with jQuery

Try this one..

var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
     console.log($(this).val());
     listCheck .push($(this).val());
});
console.log(listCheck);

How do I set session timeout of greater than 30 minutes

this will set your session to keep everything till the browser is closed

session.setMaxinactiveinterval(-1);

and this should set it for 1 day

session.setMaxInactiveInterval(60*60*24);

Why does Lua have no "continue" statement?

We can achieve it as below, it will skip even numbers

local len = 5
for i = 1, len do
    repeat 
        if i%2 == 0 then break end
        print(" i = "..i)
        break
    until true
end

O/P:

i = 1
i = 3
i = 5

Impact of Xcode build options "Enable bitcode" Yes/No

Bitcode makes crash reporting harder. Here is a quote from HockeyApp (which also true for any other crash reporting solutions):

When uploading an app to the App Store and leaving the "Bitcode" checkbox enabled, Apple will use that Bitcode build and re-compile it on their end before distributing it to devices. This will result in the binary getting a new UUID and there is an option to download a corresponding dSYM through Xcode.

Note: the answer was edited on Jan 2016 to reflect most recent changes

Twitter bootstrap remote modal shows same content every time

The problem is two-fold.

First, once a Modal object is instantiated, it is persistently attached to the element specified by data-target and subsequent calls to show that modal will only call toggle() on it, but will not update the values in the options. So, even though the href attributes are different on your different links, when the modal is toggled, the value for remote is not getting updated. For most options, one can get around this by directly editing the object. For instance:

$('#myModal').data('bs.modal').options.remote = "http://website.com/item/7";

However, that won't work in this case, because...

Second, the Modal plugin is designed to load the remote resource in the constructor of the Modal object, which unfortunately means that even if a change is made to the options.remote, it will never be reloaded.

A simple remedy is to destroy the Modal object before subsequent toggles. One option is to just destroy it after it finishes hiding:

$('body').on('hidden.bs.modal', '.modal', function () {
  $(this).removeData('bs.modal');
});

Note: Adjust the selectors as needed. This is the most general.

Plunker

Or you could try coming up with a more complicated scheme to do something like check whether the link launching the modal is different from the previous one. If it is, destroy; if it isn't, then no need to reload.

Using Axios GET with Authorization Header in React-Native App

Could not get this to work until I put Authorization in single quotes:

axios.get(URL, { headers: { 'Authorization': AuthStr } })

How can I combine multiple rows into a comma-delimited list in Oracle?

you can try this query.

select listagg(country_name,',') within group (order by country_name) cnt 
from countries; 

String replacement in java, similar to a velocity template

I use GroovyShell in java to parse template with Groovy GString:

Binding binding = new Binding();
GroovyShell gs = new GroovyShell(binding);
// this JSONObject can also be replaced by any Java Object
JSONObject obj = new JSONObject();
obj.put("key", "value");
binding.setProperty("obj", obj)
String str = "${obj.key}";
String exp = String.format("\"%s\".toString()", str);
String res = (String) gs.evaluate(exp);
// value
System.out.println(str);

duplicate 'row.names' are not allowed error

The answer here (https://stackoverflow.com/a/22408965/2236315) by @adrianoesch should help (e.g., solves "If you know of a solution that does not require the awkward workaround mentioned in your comment (shift the column names, copy the data), that would be great." and "...requiring that the data be copied" proposed by @Frank).

Note that if you open in some text editor, you should see that the number of header fields less than number of columns below the header row. In my case, the data set had a "," missing at the end of the last header field.

VBA collection: list of keys

If you intend to use the default VB6 Collection, then the easiest you can do is:

col1.add array("first key", "first string"), "first key"
col1.add array("second key", "second string"), "second key"
col1.add array("third key", "third string"), "third key"

Then you can list all values:

Dim i As Variant

For Each i In col1
  Debug.Print i(1)
Next

Or all keys:

Dim i As Variant

For Each i In col1
  Debug.Print i(0)
Next

Delete specific line from a text file?

No rocket scien code require .Hope this simple and short code will help.

List linesList = File.ReadAllLines("myFile.txt").ToList();            
linesList.RemoveAt(0);
File.WriteAllLines("myFile.txt"), linesList.ToArray());

OR use this

public void DeleteLinesFromFile(string strLineToDelete)
    {
        string strFilePath = "Provide the path of the text file";
        string strSearchText = strLineToDelete;
        string strOldText;
        string n = "";
        StreamReader sr = File.OpenText(strFilePath);
        while ((strOldText = sr.ReadLine()) != null)
        {
            if (!strOldText.Contains(strSearchText))
            {
                n += strOldText + Environment.NewLine;
            }
        }
        sr.Close();
        File.WriteAllText(strFilePath, n);
    }

Convert base64 string to image

ImageIO.write() will compress the image by default - the compressed image has a smaller size but looks strange sometimes. I use BufferedOutputStream to save the byte array data - this will keep the original image size.

Here is the code:

import javax.xml.bind.DatatypeConverter;
import java.io.*;

public class ImageTest {
    public static void main(String[] args) {
        String base64String = "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAHkAAAB5C...";
        String[] strings = base64String.split(",");
        String extension;
        switch (strings[0]) {//check image's extension
            case "data:image/jpeg;base64":
                extension = "jpeg";
                break;
            case "data:image/png;base64":
                extension = "png";
                break;
            default://should write cases for more images types
                extension = "jpg";
                break;
        }
        //convert base64 string to binary data
        byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
        String path = "C:\\Users\\Ene\\Desktop\\test_image." + extension;
        File file = new File(path);
        try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
            outputStream.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

In my case, I added below code in dependencies of app level build.gradle

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

After that, I clean the project and rebuild.My problem solved.

Can vue-router open a link in a new tab?

Somewhere in your project, typically main.js or router.js

import Router from 'vue-router'

Router.prototype.open = function (routeObject) {
  const {href} = this.resolve(routeObject)
  window.open(href, '_blank')
}

In your component:

<div @click="$router.open({name: 'User', params: {ID: 123}})">Open in new tab</div>

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

If the image is already used, you sholud:

  1. set image simensions to initial

    image.css('width', 'initial'); image.css('height', 'initial');

  2. get dimensions

    var originalWidth = $(this).width(); var originalHeight = $(this).height();

Are SSL certificates bound to the servers ip address?

The SSL certificates are going to be bound to hostname rather than IP if they are setup in the standard way. Hence why it works at one site rather than the other.

Even if the servers share the same hostname they may well have two different certificates and hence WebSphere will have a certificate trust issue as it won't be able to recognise the certificate on the second server as it is different to the first.

Show/Hide Table Rows using Javascript classes

AngularJS directives ng-show, ng-hide allows to display and hide a row:

   <tr ng-show="rw.isExpanded">
   </tr>

A row will be visible when rw.isExpanded == true and hidden when rw.isExpanded == false. ng-hide performs the same task but requires inverse condition.

How to upload files to server using Putty (ssh)

You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.

bootstrap 3 navbar collapse button not working

In <body> you should have two <script> tags:

<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="js/bootstrap.js"></script>

The first one will load jQuery from the CDN, and second one will load Bootstrap's Javascript from a local directory (in this case it's a directory called js).

Linux - Install redis-cli only

For centOS, maybe can try following steps

cd /tmp
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make
cp src/redis-cli /usr/local/bin/
chmod 755 /usr/local/bin/redis-cli

How can I show and hide elements based on selected option with jQuery?

You're running the code before the DOM is loaded.

Try this:

Live example:

http://jsfiddle.net/FvMYz/

$(function() {    // Makes sure the code contained doesn't run until
                  //     all the DOM elements have loaded

    $('#colorselector').change(function(){
        $('.colors').hide();
        $('#' + $(this).val()).show();
    });

});

Python - Get Yesterday's date as a string in YYYY-MM-DD format

You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.

datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:

>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)

>>> type(yesterday)                                                                                                                                                                                    
>>> datetime.datetime    

>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'

Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:

>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'

As a function:

def yesterday(string=False):
    yesterday = datetime.now() - timedelta(1)
    if string:
        return yesterday.strftime('%Y-%m-%d')
    return yesterday

How to get the type of T from a member of a generic class or method?

You can use this one for return type of generic list:

public string ListType<T>(T value)
{
    var valueType = value.GetType().GenericTypeArguments[0].FullName;
    return valueType;
}

How to set a timer in android

I am using a handler and runnable to create a timer. I wrapper this in an abstract class. Just derive/implement it and you are good to go:

 public static abstract class SimpleTimer {
    abstract void onTimer();

    private Runnable runnableCode = null;
    private Handler handler = new Handler();

    void startDelayed(final int intervalMS, int delayMS) {
        runnableCode = new Runnable() {
            @Override
            public void run() {
                handler.postDelayed(runnableCode, intervalMS);
                onTimer();
            }
        };
        handler.postDelayed(runnableCode, delayMS);
    }

    void start(final int intervalMS) {
        startDelayed(intervalMS, 0);
    }

    void stop() {
        handler.removeCallbacks(runnableCode);
    }
}

Note that the handler.postDelayed is called before the code to be executed - this will make the timer more closed timed as "expected". However in cases were the timer runs to frequently and the task (onTimer()) is long - there might be overlaps. If you want to start counting intervalMS after the task is done, move the onTimer() call a line above.

How to check SQL Server version

select charindex(  'Express',@@version)

if this value is 0 is not a express edition

Attaching click to anchor tag in angular

I had issues with the page reloading but was able to avoid that with routerlink=".":

<a routerLink="." (click)="myFunction()">My Function</a>

I received inspiration from the Angular Material docs on buttons: https://material.angular.io/components/button/examples

Full-screen iframe with a height of 100%

The following tested working

<iframe style="width:100%; height:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" src="index.html" frameborder="0" height="100%" width="100%"></iframe>

C# Base64 String to JPEG Image

So with the code you have provided.

var bytes = Convert.FromBase64String(resizeImage.Content);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
    imageFile.Write(bytes ,0, bytes.Length);
    imageFile.Flush();
}

How to validate an e-mail address in swift?

This a new version for "THE REASONABLE SOLUTION" by @Fattie, tested on Swift 4.1 in a new file called String+Email.swift:

import Foundation

extension String {
    private static let __firstpart = "[A-Z0-9a-z]([A-Z0-9a-z._%+-]{0,30}[A-Z0-9a-z])?"
    private static let __serverpart = "([A-Z0-9a-z]([A-Z0-9a-z-]{0,30}[A-Z0-9a-z])?\\.){1,5}"
    private static let __emailRegex = __firstpart + "@" + __serverpart + "[A-Za-z]{2,6}"

    public var isEmail: Bool {
        let predicate = NSPredicate(format: "SELF MATCHES %@", type(of:self).__emailRegex)
        return predicate.evaluate(with: self)
    }
}

So its usage is simple:

let str = "[email protected]"
if str.isEmail {
    print("\(str) is a valid e-mail address")
} else {
    print("\(str) is not a valid e-mail address")
}

I simply don't like to add a func to the String objects, as being an e-mail address is inherent to them (or not). So a Bool property would fit better than a func, from my understanding.

Load different application.yml in SpringBoot Test

This might be considered one of the options. now if you wanted to load a yml file ( which did not get loaded by default on applying the above annotations) the trick is to use

@ContextConfiguration(classes= {...}, initializers={ConfigFileApplicationContextInitializer.class})

Here is a sample code

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@DirtiesContext
@ContextConfiguration(classes= {DataSourceTestConfig.class}, initializers = {ConfigFileApplicationContextInitializer.class})
public class CustomDateDeserializerTest {


    private ObjectMapper objMapper;

    @Before
    public void setUp() {
        objMapper = new ObjectMapper();

    }

    @Test
    public void test_dateDeserialization() {

    }
}

Again make sure that the setup config java file - here DataSourceTestConfig.java contains the following property values.

@Configuration
@ActiveProfiles("test")
@TestPropertySource(properties = { "spring.config.location=classpath:application-test.yml" })
public class DataSourceTestConfig implements EnvironmentAware {

    private Environment env;

    @Bean
    @Profile("test")
    public DataSource testDs() {
       HikariDataSource ds = new HikariDataSource();

        boolean isAutoCommitEnabled = env.getProperty("spring.datasource.hikari.auto-commit") != null ? Boolean.parseBoolean(env.getProperty("spring.datasource.hikari.auto-commit")):false;
        ds.setAutoCommit(isAutoCommitEnabled);
        // Connection test query is for legacy connections
        //ds.setConnectionInitSql(env.getProperty("spring.datasource.hikari.connection-test-query"));
        ds.setPoolName(env.getProperty("spring.datasource.hikari.pool-name"));
        ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        long timeout = env.getProperty("spring.datasource.hikari.idleTimeout") != null ? Long.parseLong(env.getProperty("spring.datasource.hikari.idleTimeout")): 40000;
        ds.setIdleTimeout(timeout);
        long maxLifeTime = env.getProperty("spring.datasource.hikari.maxLifetime") != null ? Long.parseLong(env.getProperty("spring.datasource.hikari.maxLifetime")): 1800000 ;
        ds.setMaxLifetime(maxLifeTime);
        ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
        ds.setPoolName(env.getProperty("spring.datasource.hikari.pool-name"));
        ds.setUsername(env.getProperty("spring.datasource.username"));
        ds.setPassword(env.getProperty("spring.datasource.password"));
        int poolSize = env.getProperty("spring.datasource.hikari.maximum-pool-size") != null ? Integer.parseInt(env.getProperty("spring.datasource.hikari.maximum-pool-size")): 10;
        ds.setMaximumPoolSize(poolSize);

        return ds;
    }

    @Bean
    @Profile("test")
    public JdbcTemplate testJdbctemplate() {
        return new JdbcTemplate(testDs());
    }

    @Bean
    @Profile("test")
    public NamedParameterJdbcTemplate testNamedTemplate() {
        return new NamedParameterJdbcTemplate(testDs());
    }

    @Override
    public void setEnvironment(Environment environment) {
        // TODO Auto-generated method stub
        this.env = environment;
    }
}

Uncaught ReferenceError: function is not defined with onclick

I was receiving the error (I'm using Vue) and I switched my onclick="someFunction()" to @click="someFunction" and now they are working.

.NET: Simplest way to send POST with data and read response

Using HttpClient: as far as Windows 8 app development concerns, I came across this.

var client = new HttpClient();

var pairs = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("pqpUserName", "admin"),
        new KeyValuePair<string, string>("password", "test@123")
    };

var content = new FormUrlEncodedContent(pairs);

var response = client.PostAsync("youruri", content).Result;

if (response.IsSuccessStatusCode)
{


}

Custom ImageView with drop shadow

I believe this answer from UIFuel

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

     <!-- Drop Shadow Stack -->
     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#00CCCCCC" />
        </shape>
    </item>
     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#10CCCCCC" />
        </shape>
    </item>
     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#20CCCCCC" />
        </shape>
    </item>
     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#30CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#50CCCCCC" />
        </shape>
    </item>

    <!-- Background -->
    <item>
    <shape>
            <solid android:color="@color/white" />
        <corners android:radius="3dp" />
    </shape>
    </item>
</layer-list>

When is a C++ destructor called?

If the object is created not via a pointer(for example,A a1 = A();),the destructor is called when the object is destructed, always when the function where the object lies is finished.for example:

void func()
{
...
A a1 = A();
...
}//finish


the destructor is called when code is execused to line "finish".

If the object is created via a pointer(for example,A * a2 = new A();),the destructor is called when the pointer is deleted(delete a2;).If the point is not deleted by user explictly or given a new address before deleting it, the memory leak is occured. That is a bug.

In a linked list, if we use std::list<>, we needn't care about the desctructor or memory leak because std::list<> has finished all of these for us. In a linked list written by ourselves, we should write the desctructor and delete the pointer explictly.Otherwise, it will cause memory leak.

We rarely call a destructor manually. It is a function providing for the system.

Sorry for my poor English!

Fastest way to determine if record exists

Below is the simplest and fastest way to determine if a record exists in database or not Good thing is it works in all Relational DB's

SELECT distinct 1 products.id FROM products WHERE products.id = ?;

How to force a web browser NOT to cache images

When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it).

Change this, and you've fixed your problem. I use timestamps, as with the solutions proposed above: Image-<timestamp>.jpg

Presumably, whatever problems you're avoiding by keeping the same filename for the image can be overcome, but you don't say what they are.

Vuejs and Vue.set(), update array

VueJS can't pickup your changes to the state if you manipulate arrays like this.

As explained in Common Beginner Gotchas, you should use array methods like push, splice or whatever and never modify the indexes like this a[2] = 2 nor the .length property of an array.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    f: 'DD-MM-YYYY',_x000D_
    items: [_x000D_
      "10-03-2017",_x000D_
      "12-03-2017"_x000D_
    ]_x000D_
  },_x000D_
  methods: {_x000D_
_x000D_
    cha: function(index, item, what, count) {_x000D_
      console.log(item + " index > " + index);_x000D_
      val = moment(this.items[index], this.f).add(count, what).format(this.f);_x000D_
_x000D_
      this.items.$set(index, val)_x000D_
      console.log("arr length:  " + this.items.length);_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<div id="app">_x000D_
  <ul>_x000D_
    <li v-for="(index, item) in items">_x000D_
      <br><br>_x000D_
      <button v-on:click="cha(index, item, 'day', -1)">_x000D_
      - day</button> {{ item }}_x000D_
      <button v-on:click="cha(index, item, 'day', 1)">_x000D_
      + day</button>_x000D_
      <br><br>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Override devise registrations controller

I believe there is a better solution than rewrite the RegistrationsController. I did exactly the same thing (I just have Organization instead of Company).

If you set properly your nested form, at model and view level, everything works like a charm.

My User model:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  has_many :owned_organizations, :class_name => 'Organization', :foreign_key => :owner_id

  has_many :organization_memberships
  has_many :organizations, :through => :organization_memberships

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :username, :owned_organizations_attributes

  accepts_nested_attributes_for :owned_organizations
  ...
end

My Organization Model:

class Organization < ActiveRecord::Base
  belongs_to :owner, :class_name => 'User'
  has_many :organization_memberships
  has_many :users, :through => :organization_memberships
  has_many :contracts

  attr_accessor :plan_name

  after_create :set_owner_membership, :set_contract
  ...
end

My view : 'devise/registrations/new.html.erb'

<h2>Sign up</h2>

<% resource.owned_organizations.build if resource.owned_organizations.empty? %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <p><%= f.label :name %><br />
    <%= f.text_field :name %></p>

  <p><%= f.label :email %><br />
    <%= f.text_field :email %></p>

  <p><%= f.label :username %><br />
    <%= f.text_field :username %></p>

  <p><%= f.label :password %><br />
    <%= f.password_field :password %></p>

  <p><%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %></p>

  <%= f.fields_for :owned_organizations do |organization_form| %>

    <p><%= organization_form.label :name %><br />
      <%= organization_form.text_field :name %></p>

    <p><%= organization_form.label :subdomain %><br />
      <%= organization_form.text_field :subdomain %></p>

    <%= organization_form.hidden_field :plan_name, :value => params[:plan] %>

  <% end %>

  <p><%= f.submit "Sign up" %></p>
<% end %>

<%= render :partial => "devise/shared/links" %>

Is there a printf converter to print in binary format?

No standard and portable way.

Some implementations provide itoa(), but it's not going to be in most, and it has a somewhat crummy interface. But the code is behind the link and should let you implement your own formatter pretty easily.

Running CMD command in PowerShell

One solution would be to pipe your command from PowerShell to CMD. Running the following command will pipe the notepad.exe command over to CMD, which will then open the Notepad application.

PS C:\> "notepad.exe" | cmd

Once the command has run in CMD, you will be returned to a PowerShell prompt, and can continue running your PowerShell script.


Edits

CMD's Startup Message is Shown

As mklement0 points out, this method shows CMD's startup message. If you were to copy the output using the method above into another terminal, the startup message will be copied along with it.

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

This question and its answers led me to my own solution (with help from SO), though some say you shouldn't tamper with native prototypes:

  // IE does not support .includes() so I'm making my own:
  String.prototype.doesInclude=function(needle){
    return this.substring(needle) != -1;
  }

Then I just replaced all .includes() with .doesInclude() and my problem was solved.

bootstrap button shows blue outline when clicked

I'm using bootstrap 4, you can use outline and box-shadow.

#buttonId {
    box-shadow: none;
    outline: none;
}

Or if the button is inside an element like a div without back-ground, box-shadow is enough.

#buttonId {
     box-shadow: none;
}

Example: https://codepen.io/techednelson/pen/XRwgRB

How to access the elements of a 2D array?

If you have

a=[[1,1],[2,1],[3,1]]
b=[[1,2],[2,2],[3,2]]

Then

a[1][1]

Will work fine. It points to the second column, second row just like you wanted.

I'm not sure what you did wrong.

To multiply the cells in the third column you can just do

c = [a[2][i] * b[2][i] for i in range(len(a[2]))] 

Which will work for any number of rows.

Edit: The first number is the column, the second number is the row, with your current layout. They are both numbered from zero. If you want to switch the order you can do

a = zip(*a)

or you can create it that way:

a=[[1, 2, 3], [1, 1, 1]]

Wait for a void async method

I know this is an old question, but this is still a problem I keep walking into, and yet there is still no clear solution to do this correctly when using async/await in an async void signature method.

However, I noticed that .Wait() is working properly inside the void method.

and since async void and void have the same signature, you might need to do the following.

void LoadBlahBlah()
{
    blah().Wait(); //this blocks
}

Confusingly enough async/await does not block on the next code.

async void LoadBlahBlah()
{
    await blah(); //this does not block
}

When you decompile your code, my guess is that async void creates an internal Task (just like async Task), but since the signature does not support to return that internal Tasks

this means that internally the async void method will still be able to "await" internally async methods. but externally unable to know when the internal Task is complete.

So my conclusion is that async void is working as intended, and if you need feedback from the internal Task, then you need to use the async Task signature instead.

hopefully my rambling makes sense to anybody also looking for answers.

Edit: I made some example code and decompiled it to see what is actually going on.

static async void Test()
{
    await Task.Delay(5000);
}

static async Task TestAsync()
{
    await Task.Delay(5000);
}

Turns into (edit: I know that the body code is not here but in the statemachines, but the statemachines was basically identical, so I didn't bother adding them)

private static void Test()
{
    <Test>d__1 stateMachine = new <Test>d__1();
    stateMachine.<>t__builder = AsyncVoidMethodBuilder.Create();
    stateMachine.<>1__state = -1;
    AsyncVoidMethodBuilder <>t__builder = stateMachine.<>t__builder;
    <>t__builder.Start(ref stateMachine);
}
private static Task TestAsync()
{
    <TestAsync>d__2 stateMachine = new <TestAsync>d__2();
    stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
    stateMachine.<>1__state = -1;
    AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
    <>t__builder.Start(ref stateMachine);
    return stateMachine.<>t__builder.Task;
}

neither AsyncVoidMethodBuilder or AsyncTaskMethodBuilder actually have any code in the Start method that would hint of them to block, and would always run asynchronously after they are started.

meaning without the returning Task, there would be no way to check if it is complete.

as expected, it only starts the Task running async, and then it continues in the code. and the async Task, first it starts the Task, and then it returns it.

so I guess my answer would be to never use async void, if you need to know when the task is done, that is what async Task is for.

Reference — What does this symbol mean in PHP?

Question:

What does "&" mean here in PHP?

PHP "&" operator

Makes life more easier once we get used to it..(check example below carefully)

& usually checks bits that are set in both $a and $b are set.

have you even noticed how these calls works?

   error_reporting(E_ERROR | E_WARNING | E_PARSE);
    error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    error_reporting(E_ALL & ~E_NOTICE);
    error_reporting(E_ALL);

So behind all above is game of bitwise operator and bits.

One usefull case of these is easy configurations like give below, so a single integer field can store thousands of combos for you.

Most people have already read the docs but didn't reliase the real world use case of these bitwise operators.

Example That you 'll love

<?php

class Config {

    // our constants must be 1,2,4,8,16,32,64 ....so on
    const TYPE_CAT=1;
    const TYPE_DOG=2;
    const TYPE_LION=4;
    const TYPE_RAT=8;
    const TYPE_BIRD=16;
    const TYPE_ALL=31;

    private $config;

    public function __construct($config){
        $this->config=$config;

        if($this->is(Config::TYPE_CAT)){
            echo 'cat ';
        }
        if($this->is(Config::TYPE_DOG)){
            echo 'dog ';
        }
        if($this->is(Config::TYPE_RAT)){
            echo 'rat ';
        }
        if($this->is(Config::TYPE_LION)){
            echo 'lion ';
        }
        if($this->is(Config::TYPE_BIRD)){
            echo 'bird ';
        }
        echo "\n";
    }

    private function is($value){
        return $this->config & $value;
    }
}

new Config(Config::TYPE_ALL);
// cat dog rat lion bird
new Config(Config::TYPE_BIRD);
//bird
new Config(Config::TYPE_BIRD | Config::TYPE_DOG);
//dog bird
new Config(Config::TYPE_ALL & ~Config::TYPE_DOG & ~Config::TYPE_CAT);
//rat lion bird

How to get a unique device ID in Swift?

You can use devicecheck (in Swift 4) Apple documentation

func sendEphemeralToken() {
        //check if DCDevice is available (iOS 11)

        //get the **ephemeral** token
        DCDevice.current.generateToken {
        (data, error) in
        guard let data = data else {
            return
        }

        //send **ephemeral** token to server to 
        let token = data.base64EncodedString()
        //Alamofire.request("https://myServer/deviceToken" ...
    }
}

Typical usage:

Typically, you use the DeviceCheck APIs to ensure that a new user has not already redeemed an offer under a different user name on the same device.

Server action needs:

See WWDC 2017 — Session 702 (24:06)

more from Santosh Botre article - Unique Identifier for the iOS Devices

Your associated server combines this token with an authentication key that you receive from Apple and uses the result to request access to the per-device bits.

PHP how to get local IP of system

It is easy one. You can get the host name by this simple code.

$ip = getHostByName(getHostName());

Or you can also use $_SERVER['HTTP_HOST'] to get the hostname.

How do I run a class in a WAR from the command line?

Similar to what Richard Detsch but with a bit easier to follow (works with packages as well)

Step 1: Unwrap the War file.

jar -xvf MyWar.war

Step 2: move into the directory

cd WEB-INF

Step 3: Run your main with all dependendecies

java -classpath "lib/*:classes/." my.packages.destination.FileToRun

How to Set AllowOverride all

Plus those upvoted correct answers sometimes same error could be seen because of mismatched and different settings on SSL part of webserver configurations. (Obviously when not using .htaccess file).

Moment.js - two dates difference in number of days

From the moment.js docs: format('E') stands for day of week. thus your diff is being computed on which day of the week, which has to be between 1 and 7.

From the moment.js docs again, here is what they suggest:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Here is a JSFiddle for your particular case:

_x000D_
_x000D_
$('#test').click(function() {_x000D_
  var startDate = moment("13.04.2016", "DD.MM.YYYY");_x000D_
  var endDate = moment("28.04.2016", "DD.MM.YYYY");_x000D_
_x000D_
  var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
  $('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #ffb;_x000D_
  padding: 10px;_x000D_
  border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
_x000D_
_x000D_

Remove border radius from Select tag in bootstrap 3

the class is called:

.form-control { border-radius: 0; }

be sure to insert the override after including bootstraps css.

If you ONLY want to remove the radius on select form-controls use

select.form-control { ... }

instead

EDIT: works for me on chrome, firefox, opera, and safari, IE9+ (all running on linux/safari & IE on playonlinux)

How can you use optional parameters in C#?

A little late to the party, but I was looking for the answer to this question and ultimately figured out yet another way to do this. Declare the data types for the optional args of your web method to be type XmlNode. If the optional arg is omitted this will be set to null, and if it's present you can get is string value by calling arg.Value, i.e.,

[WebMethod]
public string Foo(string arg1, XmlNode optarg2)
{
    string arg2 = "";
    if (optarg2 != null)
    {
        arg2 = optarg2.Value;
    }
    ... etc
}

What's also decent about this approach is the .NET generated home page for the ws still shows the argument list (though you do lose the handy text entry boxes for testing).

Enable UTF-8 encoding for JavaScript

RobW is right on the first comment. You have to save the file in your IDE with encoding UTF-8. I moved my alert from .js file to my .html file and this solved the issue cause Visual Studio saves .html with UTF-8 encoding.

Click a button programmatically - JS

When using JavaScript to access an HTML element, there is a good chance that the element is not on the page and therefore not in the dom as far as JavaScript is concerned, when the code to access that element runs.

This problem can occur even though you can visually see the HTML element in the browser window or have the code set to be called in the onload method.

I ran into this problem after writing code to repopulate specific div elements on a page after retrieving the cookies.

What is apparently happening is that even though the HTML has loaded and is outputted by the browser, the JavaScript code is running before the page has completed loading.

The solution to this problem which just may be a JavaScript bug, is to place the code you want to run within a timer that delays the code run by 400 milliseconds or so. You will need to test it to determine how quick you can run the code.

I also made a point to test for the element before attempting to assign values to it.

window.setTimeout(function() { if( document.getElementById("book") ) { // Code goes here }, 400 /* but after 400 ms */);

This may or may not help you solve your problem, but keep this in mind and understand that browsers do not always function as expected.

SQL Update Multiple Fields FROM via a SELECT Statement

I would write it this way

UPDATE s
SET    OrgAddress1 = bd.OrgAddress1,    OrgAddress2 = bd.OrgAddress2,    
     ...    DestZip = bd.DestZip
--select s.OrgAddress1, bd.OrgAddress1, s.OrgAddress2, bd.OrgAddress2, etc 
FROM    Shipment s
JOIN ProfilerTest.dbo.BookingDetails bd on  bd.MyID =s.MyID2
WHERE    bd.MyID = @MyId 

This way the join is explicit as implicit joins are a bad thing IMHO. You can run the commented out select (usually I specify the fields I'm updating old and new values next to each other) to make sure that what I am going to update is exactly what I meant to update.

Python concatenate text files

An alternative to @inspectorG4dget answer (best answer to date 29-03-2016). I tested with 3 files of 436MB.

@inspectorG4dget solution: 162 seconds

The following solution : 125 seconds

from subprocess import Popen
filenames = ['file1.txt', 'file2.txt', 'file3.txt']
fbatch = open('batch.bat','w')
str ="type "
for f in filenames:
    str+= f + " "
fbatch.write(str + " > file4results.txt")
fbatch.close()
p = Popen("batch.bat", cwd=r"Drive:\Path\to\folder")
stdout, stderr = p.communicate()

The idea is to create a batch file and execute it, taking advantage of "old good technology". Its semi-python but works faster. Works for windows.

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

How to read data from a file in Lua

Just a little addition if one wants to parse a space separated text file line by line.

read_file = function (path)
local file = io.open(path, "rb") 
if not file then return nil end

local lines = {}

for line in io.lines(path) do
    local words = {}
    for word in line:gmatch("%w+") do 
        table.insert(words, word) 
    end    
  table.insert(lines, words)
end

file:close()
return lines;
end

How do I remove trailing whitespace using a regular expression?

Try just removing trailing spaces and tabs:

[ \t]+$

Is there any difference between GROUP BY and DISTINCT

I know it's an old post. But it happens that I had a query that used group by just to return distinct values when using that query in toad and oracle reports everything worked fine, I mean a good response time. When we migrated from Oracle 9i to 11g the response time in Toad was excellent but in the reporte it took about 35 minutes to finish the report when using previous version it took about 5 minutes.

The solution was to change the group by and use DISTINCT and now the report runs in about 30 secs.

I hope this is useful for someone with the same situation.

How to embed a PDF?

<iframe src="http://docs.google.com/gview?url=http://domain.com/pdf.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"></iframe>

Google docs allows you to embed PDFs, Microsoft Office Docs, and other applications by just linking to their services with an iframe. Its user-friendly, versatile, and attractive.

Get pixel color from canvas, on mousemove

Quick Answer

context.getImageData(x, y, 1, 1).data; returns an rgba array. e.g. [50, 50, 50, 255]


Here's a version of @lwburk's rgbToHex function that takes the rgba array as an argument.

function rgbToHex(rgb){
  return '#' + ((rgb[0] << 16) | (rgb[1] << 8) | rgb[2]).toString(16);
};