Programs & Examples On #Webcombo

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

How to convert date to timestamp in PHP?

If you want to know for sure whether a date gets parsed into something you expect, you can use DateTime::createFromFormat():

$d = DateTime::createFromFormat('d-m-Y', '22-09-2008');
if ($d === false) {
    die("Woah, that date doesn't look right!");
}
echo $d->format('Y-m-d'), PHP_EOL;
// prints 2008-09-22

It's obvious in this case, but e.g. 03-04-2008 could be 3rd of April or 4th of March depending on where you come from :)

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

Get today date in google appScript

The following can be used to get the date:

function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1;  if(month.toString().length==1){var month = 
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}

Why not use tables for layout in HTML?

I still don't quite understand how divs / CSS make it easier to change a page design when you consider the amount of testing to ensure the changes work on all browsers, especially with all the hacks and so on. Its a hugely frustrating and tedious process which wastes large amounts of time and money. Thankfully the 508 legislation only applies to the USA (land of the free - yeah right) and so being as I am based in the UK, I can develop web sites in whatever style I choose. Contrary to popular (US) belief, legislation made in Washington doesn't apply to the rest of the world - thank goodness for that. It must have been a good day in the world of web design the day the legislation came into force. I think I'm becoming increasingly cynical as I get older with 25 years in the IT industry but I feel sure this kind of legislation is just to protect jobs. In reality anyone can knock together a reasonable web page with a couple of tables. It takes a lot more effort and knowledge to do this with DIVs / CSS. In my experience it can take hours and hours Googling to find solutions to quite simple problems and reading incomprehensible articles in forums full of idealistic zealots all argueing about the 'right' way to do things. You can't just dip your toe in the water and get things to work properly in every case. It also seems to me that the lack of a definitive guide to using DIVS / CSS "out of the box", that applies to all situations, working on browsers, and written using 'normal' language with no geek speak, also smells of a bit of protectionism.
I'm an application developer and I would say it takes almost twice as long to figure out layout problems and test against all browsers than it does to create the basic application, design and implement business objects, and create the database back end. My time = money, both for me and my customers alike so I am sorry if I don't reject all the pro DIV / CSS arguments in favour of cutting costs and providing value for money for my customers. Maybe its just the way that developers minds work, but it seems to me far easier to change a complex table structure than it is to modify DIVs / CSS. Thankfully it now appears that a solution to these issues is now available - its called WPF.

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

How do I solve the "server DNS address could not be found" error on Windows 10?

Steps to manually configure DNS:

  1. You can access Network and Sharing center by right clicking on the Network icon on the taskbar.

  2. Now choose adapter settings from the side menu.

  3. This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.

  4. In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.

  5. Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.

    Select ‘use the following DNS address’ option. Now fill the following fields as given here.

    Preferred DNS server: 208.67.222.222

    Alternate DNS server : 208.67.220.220

    This is an available Open DNS address. You may also use google DNS server addresses.

    After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.

You have to add this DNS server address in the router configuration also (by referring the router manual for more information).

Refer : for above method & alternative

If none of this works, then open command prompt(Run as Administrator) and run these:

ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit

Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).

Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue

Changing the background color of a drop down list transparent in html

Or maybe

 background: transparent !important;
 color: #ffffff;

How to determine whether a substring is in a different string

You can also try find() method. It determines if string str occurs in string, or in a substring of string.

str1 = "please help me out so that I could solve this"
str2 = "please help me out"

if (str1.find(str2)>=0):
  print("True")
else:
  print ("False")

Export result set on Dbeaver to CSV

You don't need to use the clipboard, you can export directly the whole resultset (not just what you see) to a file :

  1. Execute your query
  2. Right click any anywhere in the results
  3. click "Export resultset..." to open the export wizard
  4. Choose the format you want (CSV according to your question)
  5. Review the settings in the next panes when clicking "Next".
  6. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.


In newer versions of DBeaver you can just :

  1. right click the SQL of the query you want to export
  2. Execute > Export from query
  3. Choose the format you want (CSV according to your question)
  4. Review the settings in the next panes when clicking "Next".
  5. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.

Compared to the previous way of doing exports, this saves you step 1 (executing the query) which can be handy with time/resource intensive queries.

TypeScript function overloading

Function overloading in typescript:

According to Wikipedia, (and many programming books) the definition of method/function overloading is the following:

In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

In typescript we cannot have different implementations of the same function that are called according to the number and type of arguments. This is because when TS is compiled to JS, the functions in JS have the following characteristics:

  • JavaScript function definitions do not specify data types for their parameters
  • JavaScript functions do not check the number of arguments when called

Therefore, in a strict sense, one could argue that TS function overloading doesn't exists. However, there are things you can do within your TS code that can perfectly mimick function overloading.

Here is an example:

function add(a: number, b: number, c: number): number;
function add(a: number, b: number): any;
function add(a: string, b: string): any;

function add(a: any, b: any, c?: any): any {
  if (c) {
    return a + c;
  }
  if (typeof a === 'string') {
    return `a is ${a}, b is ${b}`;
  } else {
    return a + b;
  }
}

The TS docs call this method overloading, and what we basically did is supplying multiple method signatures (descriptions of possible parameters and types) to the TS compiler. Now TS can figure out if we called our function correctly during compile time and give us an error if we called the function incorrectly.

How to disable scrolling temporarily?

I found solution in this post. In my context I wish deactivate vertical scroll when I'm scrolling horizontally inside a

Like this =>

let scrollContainer = document.getElementById('scroll-container');
document.getElementById('scroll-container').addEventListener(
    "wheel",
    (event) => {
        event.preventDefault();
        scrollContainer.scrollLeft += event.deltaY;
    },
    {
        // allow preventDefault()
        passive: false
    }
);

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

I am now using Google Apps (for Email) and Heroku as web server. I am using Google Apps 301 Permanent Redirect feature to redirect the naked domain to WWW.your_domain.com

You can find the step-by-step instructions here https://stackoverflow.com/a/20115583/1440255

Pycharm does not show plot

I was facing above error when i am trying to plot histogram and below points worked for me.

OS : Mac Catalina 10.15.5

Pycharm Version : Community version 2019.2.3

Python version : 3.7

  1. I changed import statement as below (from - to)

from :

import matplotlib.pylab as plt

to:

import matplotlib.pyplot as plt

  1. and plot statement to below (changed my command form pyplot to plt)

from:

plt.pyplot.hist(df["horsepower"])

# set x/y labels and plot title
plt.pyplot.xlabel("horsepower")
plt.pyplot.ylabel("count")
plt.pyplot.title("horsepower bins") 

to :

plt.hist(df["horsepower"])

# set x/y labels and plot title
plt.xlabel("horsepower")
plt.ylabel("count")
plt.title("horsepower bins")
  1. use plt.show to display histogram

plt.show()

How to disable <br> tags inside <div> by css?

I used it like this:

@media (max-width: 450px) {
  br {
    display: none;
  }
}

nb: media query via Foundation nb2: this is useful if one of the editor intend to use
tags in his/her copy and you need to deal with it specifically under some conditions—on mobile for example.

storing user input in array

You have at least these 3 issues:

  1. you are not getting the element's value properly
  2. The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
  3. Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.

You can save all three values at once by doing:

var title=new Array();
var names=new Array();//renamed to names -added an S- 
                      //to avoid conflicts with the input named "name"
var tickets=new Array();

function insert(){
    var titleValue = document.getElementById('title').value;
    var actorValue = document.getElementById('name').value;
    var ticketsValue = document.getElementById('tickets').value;
    title[title.length]=titleValue;
    names[names.length]=actorValue;
    tickets[tickets.length]=ticketsValue;
  }

And then change the show function to:

function show() {
  var content="<b>All Elements of the Arrays :</b><br>";
  for(var i = 0; i < title.length; i++) {
     content +=title[i]+"<br>";
  }
  for(var i = 0; i < names.length; i++) {
     content +=names[i]+"<br>";
  }
  for(var i = 0; i < tickets.length; i++) {
     content +=tickets[i]+"<br>";
  }
  document.getElementById('display').innerHTML = content; //note that I changed 
                                                    //to 'display' because that's
                                              //what you have in your markup
}

Here's a jsfiddle for you to play around.

How to remove newlines from beginning and end of a string?

If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:

Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:

 s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")

Complete Example:

public class RemoveLineBreaks {
    public static void main(String[] args) {
        var s = "\nHello\nWorld\n";
        System.out.println("before: >"+s+"<");
        s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
        System.out.println("after: >"+s+"<");
    }
}

It outputs:

before: >
Hello
World
<
after: >Hello
World<

Blue and Purple Default links, how to remove?

REMOVE DEFAULT LINK SOLVED that :visited thing is css.... you just go to your HTML and add a simple

< a href="" style="text-decoration: none" > < /a>

... thats the way html pages used to be

Possible cases for Javascript error: "Expected identifier, string or number"

Here is a easy technique to debug the problem: echo out the script/code to the console. Copy the code from the console into your IDE. Most IDE's perform error checking on the code and highlight errors. You should be able to see the error almost immediately in your JavaScript/HTML editor.

How to create a trie in Python

from collections import defaultdict

Define Trie:

_trie = lambda: defaultdict(_trie)

Create Trie:

trie = _trie()
for s in ["cat", "bat", "rat", "cam"]:
    curr = trie
    for c in s:
        curr = curr[c]
    curr.setdefault("_end")

Lookup:

def word_exist(trie, word):
    curr = trie
    for w in word:
        if w not in curr:
            return False
        curr = curr[w]
    return '_end' in curr

Test:

print(word_exist(trie, 'cam'))

How to find encoding of a file via script on Linux?

In php you can check like below :

Specifying encoding list explicitly :

php -r "echo 'probably : ' . mb_detect_encoding(file_get_contents('myfile.txt'), 'UTF-8, ASCII, JIS, EUC-JP, SJIS, iso-8859-1') . PHP_EOL;"

More accurate "mb_list_encodings":

php -r "echo 'probably : ' . mb_detect_encoding(file_get_contents('myfile.txt'), mb_list_encodings()) . PHP_EOL;"

Here in first example, you can see that i put a list of encodings (detect list order) that might be matching. To have more accurate result you can use all possible encodings via : mb_list_encodings()

Note mb_* functions require php-mbstring

apt-get install php-mbstring

How to get URL of current page in PHP

if you want just the parts of url after http://domain.com, try this:

<?php echo $_SERVER['REQUEST_URI']; ?>

if the current url was http://domain.com/some-slug/some-id, echo will return only '/some-slug/some-id'.

if you want the full url, try this:

<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>

How to use Redirect in the new react-router-dom of Reactjs

To navigate to another component you can use this.props.history.push('/main');

import React, { Component, Fragment } from 'react'

class Example extends Component {

  redirect() {
    this.props.history.push('/main')
  }

  render() {
    return (
      <Fragment>
        {this.redirect()}
      </Fragment>
    );
   }
 }

 export default Example

Explaining Apache ZooKeeper

My approach to understand zookeeper was, to play around with the CLI client. as described in Getting Started Guide and Command line interface

From this I learned that zookeeper's surface looks very similar to a filesystem and clients can create and delete objects and read or write data.

Example CLI commands

create /myfirstnode mydata
ls /
get /myfirstnode
delete /myfirstnode

Try yourself

How to spin up a zookeper environment within minutes on docker for windows, linux or mac:

One time set up:

docker network create dn

Run server in a terminal window:

docker run --network dn --name zook -d zookeeper
docker logs -f zookeeper

Run client in a second terminal window:

docker run -it --rm --network dn zookeeper zkCli.sh -server zook

See also documentation of image on dockerhub

C char* to int conversion

Use atoi() from <stdlib.h>

http://linux.die.net/man/3/atoi

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s)
{
  int sign=1;
  if(*s == '-'){
    sign = -1;
    s++;
  }
  int num=0;
  while(*s){
    num=((*s)-'0')+num*10;
    s++;   
  }
  return num*sign;
}

How to run composer from anywhere?

composer.phar can be ran on its own, no need to prefix it with php. This should solve your problem (being in the difference of bash's $PATH and php's include_path).

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

Put several images in a "controlling" container, and change the container's class instead. In CSS, add rules to manage images' visibility depending on the container's class. This will produce the same effect as changing img src property of a a single image.

HTML:

<span id="light" class="red">
    <img class="red" src="red.png" />
    <img class="yellow" src="yellow.png" />
    <img class="green" src="green.png" />
</span>

CSS:

#light         { ... }
#light         *        { display: none; }     // all images are hidden
#light.red     .red     { display: inline; }   // show red image when #light is red
#light.yellow  .yellow  { display: inline; }   // .. or yellow
#light.green   .green   { display: inline; }   // .. or green

Note that it will preload all images, like with CSS backround-images, but unlike changing img src via JS.

"Could not find a valid gem in any repository" (rubygame and others)

Use :

gem sources --add http://rubygems.org/

Do you want to add this insecure source? [yn] [YES]

then use

gem install sass

and done

How to display a readable array - Laravel

You can use var_dump or print_r functions on Blade themplate via Controller functions :

class myController{

   public function showView(){
     return view('myView',["myController"=>$this]);
   }
   public function myprint($obj){
     echo "<pre>";
     print_r($obj);
     echo "</pre>";
   }
}

And use your blade themplate :

$myController->myprint($users);

Get file size before uploading

<script type="text/javascript">
function AlertFilesize(){
    if(window.ActiveXObject){
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var filepath = document.getElementById('fileInput').value;
        var thefile = fso.getFile(filepath);
        var sizeinbytes = thefile.size;
    }else{
        var sizeinbytes = document.getElementById('fileInput').files[0].size;
    }

    var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
    fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}

    alert((Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>

<input id="fileInput" type="file" onchange="AlertFilesize();" />

Work on IE and FF

Laravel 5 - How to access image uploaded in storage within View?

One option would be to create a symbolic link between a subfolder in your storage directory and public directory.

For example

ln -s /path/to/laravel/storage/avatars /path/to/laravel/public/avatars

This is also the method used by Envoyer, a deployment manager built by Taylor Otwell, the developer of Laravel.

Smooth scroll to specific div on click

You can use basic css to achieve smooth scroll

html {
  scroll-behavior: smooth;
}

What is the best way to add a value to an array in state

the best away now.

this.setState({ myArr: [...this.state.myArr, new_value] })

Can't connect to Postgresql on port 5432

You have to edit postgresql.conf file and change line with 'listen_addresses'.

This file you can find in the /etc/postgresql/9.3/main directory.

Default Ubuntu config have allowed only localhost (or 127.0.0.1) interface, which is sufficient for using, when every PostgreSQL client work on the same computer, as PostgreSQL server. If you want connect PostgreSQL server from other computers, you have change this config line in this way:

listen_addresses = '*'

Then you have edit pg_hba.conf file, too. In this file you have set, from which computers you can connect to this server and what method of authentication you can use. Usually you will need similar line:

host    all         all         192.168.1.0/24        md5

Please, read comments in this file...

EDIT:

After the editing postgresql.conf and pg_hba.conf you have to restart postgresql server.

EDIT2: Highlited configuration files.

Custom events in jQuery?

Here is how I author custom events:

var event = jQuery.Event('customEventName');
$(element).trigger(event);

Granted, you could simply do

$(element).trigger('eventname');

But the way I wrote allows you to detect whether the user has prevented default or not by doing

var prevented = event.isDefaultPrevented();

This allows you to listen to your end-user's request to stop processing a particular event, such as if you click a button element in a form but do not want to the form to post if there is an error.


I then usually listen to events like so

$(element).off('eventname.namespace').on('eventname.namespace', function () {
    ...
});

Once again, you could just do

$(element).on('eventname', function () {
    ...
});

But I've always found this somewhat unsafe, especially if you're working in a team.

There is nothing wrong with the following:

$(element).on('eventname', function () {});

However, assume that I need to unbind this event for whatever reason (imagine a disabled button). I would then have to do

$(element).off('eventname', function () {});

This will remove all eventname events from $(element). You cannot know whether someone in the future will also bind an event to that element, and you'd be inadvertently unbinding that event as well

The safe way to avoid this is to namespace your events by doing

$(element).on('eventname.namespace', function () {});

Lastly, you may have noticed that the first line was

$(element).off('eventname.namespace').on('eventname.namespace', ...)

I personally always unbind an event before binding it just to make sure that the same event handler never gets called multiple times (imagine this was the submit button on a payment form and the event had been bound 5 times)

nuget 'packages' element is not declared warning

You can always make simple xsd schema for 'packages.config' to get rid of this warning. To do this, create file named "packages.xsd":

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
      targetNamespace="urn:packages" xmlns="urn:packages">
  <xs:element name="packages">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="package" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="id" type="xs:string" use="required" />
            <xs:attribute name="version" type="xs:string" use="required" />
            <xs:attribute name="targetFramework" type="xs:string" use="optional" />
            <xs:attribute name="allowedVersions" type="xs:string" use="optional" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Location of this file (two options)

  • In the same folder as 'packages.config' file,
  • If you want to share packages.xsd across multiple projects, move it to the Visual Studio Schemas folder (the path may slightly differ, it's D:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas for me).

Then, edit <packages> tag in packages.config file (add xmlns attribute):

<packages xmlns="urn:packages">

Now the warning should disappear (even if packages.config file is open in Visual Studio).

Iterate a certain number of times without storing the iteration number anywhere

This will print 'hello' 3 times without storing i...

[print('hello') for i in range(3)]

How do I check my gcc C++ compiler version for my Eclipse?

The answer is:

gcc --version

Rather than searching on forums, for any possible option you can always type:

gcc --help

haha! :)

Auto start node.js server on boot

This isn't something to configure in node.js at all, this is purely OS responsibility (Windows in your case). The most reliable way to achieve this is through a Windows Service.

There's this super easy module that installs a node script as a windows service, it's called node-windows (npm, github, documentation). I've used before and worked like a charm.

var Service = require('node-windows').Service;

// Create a new service object
var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js'
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});

svc.install();

p.s.

I found the thing so useful that I built an even easier to use wrapper around it (npm, github).

Installing it:

npm install -g qckwinsvc

Installing your service:

> qckwinsvc
prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed

Uninstalling your service:

> qckwinsvc --uninstall
prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled

Calling an executable program using awk

#!/usr/bin/awk -f

BEGIN {
    command = "ls -lh"

    command |getline
}

Runs "ls -lh" in an awk script

Merging dictionaries in C#

This doesn't explode if there are multiple keys ("righter" keys replace "lefter" keys), can merge a number of dictionaries (if desired) and preserves the type (with the restriction that it requires a meaningful default public constructor):

public static class DictionaryExtensions
{
    // Works in C#3/VS2008:
    // Returns a new dictionary of this ... others merged leftward.
    // Keeps the type of 'this', which must be default-instantiable.
    // Example: 
    //   result = map.MergeLeft(other1, other2, ...)
    public static T MergeLeft<T,K,V>(this T me, params IDictionary<K,V>[] others)
        where T : IDictionary<K,V>, new()
    {
        T newMap = new T();
        foreach (IDictionary<K,V> src in
            (new List<IDictionary<K,V>> { me }).Concat(others)) {
            // ^-- echk. Not quite there type-system.
            foreach (KeyValuePair<K,V> p in src) {
                newMap[p.Key] = p.Value;
            }
        }
        return newMap;
    }

}

How do I convert seconds to hours, minutes and seconds?

If you need to get datetime.time value, you can use this trick:

my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()

You cannot add timedelta to time, but can add it to datetime.

UPD: Yet another variation of the same technique:

my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()

Instead of 1 you can use any number greater than 0. Here we use the fact that datetime.fromordinal will always return datetime object with time component being zero.

Selenium WebDriver findElement(By.xpath()) not working for me

You should add the tag name in the xpath, like:

element = findElement(By.xpath("//input[@test-id='test-username']");

Button Center CSS

when all else fails I just

<center> content </center>

I know its not "up to standards" any more, but if it works it works

How to pass params with history.push/Link/Redirect in react-router v4?

First of all, you need not do var r = this; as this in if statement refers to the context of the callback itself which since you are using arrow function refers to the React component context.

According to the docs:

history objects typically have the following properties and methods:

  • length - (number) The number of entries in the history stack
  • action - (string) The current action (PUSH, REPLACE, or POP)
  • location - (object) The current location. May have the following properties:

    • pathname - (string) The path of the URL
    • search - (string) The URL query string
    • hash - (string) The URL hash fragment
    • state - (string) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
  • push(path, [state]) - (function) Pushes a new entry onto the history stack
  • replace(path, [state]) - (function) Replaces the current entry on the history stack
  • go(n) - (function) Moves the pointer in the history stack by n entries
  • goBack() - (function) Equivalent to go(-1)
  • goForward() - (function) Equivalent to go(1)
  • block(prompt) - (function) Prevents navigation

So while navigating you can pass props to the history object like

this.props.history.push({
  pathname: '/template',
  search: '?query=abc',
  state: { detail: response.data }
})

or similarly for the Link component or the Redirect component

<Link to={{
      pathname: '/template',
      search: '?query=abc',
      state: { detail: response.data }
    }}> My Link </Link>

and then in the component which is rendered with /template route, you can access the props passed like

this.props.location.state.detail

Also keep in mind that, when using history or location objects from props you need to connect the component with withRouter.

As per the Docs:

withRouter

You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as <Route> render props: { match, location, history }.

Java equivalent to #region in C#

On Mac and Android Studio follow this sequence:

  1. Highlight the source code to fold
  2. Press Alt+Command+t
  3. Select <editor-fold>

Also you can select other options:

enter image description here

Angularjs - ng-cloak/ng-show elements blink

In addition to the accepted answer if you're using an alternative method of triggering ng-cloak...

You may also wish to add some additional specificities to your CSS/LESS:

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],
.ng-cloak, .x-ng-cloak,
.ng-hide {
    display: none !important;
}

Creating a JavaScript cookie on a domain and reading it across sub domains

You want:

document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;

As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

Differences between hard real-time, soft real-time, and firm real-time?

The simplest way to distinguish between the different kinds of real-time system types is answering the question:

Is a delayed system response (after the deadline) is still useful or not?

So depending on the answer you get for this question, your system could be included as one of the following categories:

  1. Hard: No, and delayed answers are considered a system failure

This is the case when missing the dead-line will make the system unusable. For example the system controlling the car Airbag system should detect the crash and inflate rapidly the bag. The whole process takes more or less one-twenty-fifth of a second. Thus, if the system for example react with 1 second of delay the consequences could be mortal and it will be no benefit having the bag inflated once the car has already crashed.

  1. Firm: No, but delayed answers are not necessary a system failure

This is the case when missing the deadline is tolerable but it will affect the quality of the service. As a simple example consider a video encryption system. Normally the password of encryption is generated in the server (video Head end) and sent to the customer set-top box. This process should be synchronized so normally the set-top box receives the password before starts receiving the encrypted video frames. In this case a delay it may lead to video glitches since the set-top box is not able to decode the frames because it hasn't received the password yet. In this case the service (film, an interesting football match, etc) could be affected by not meeting the deadline. Receiving the password with delay in this case is not useful since the frames encrypted with the same have already caused the glitches.

  1. Soft: Yes, but the system service is degraded

As from the the wikipedia description the usefulness of a result degrades after its deadline. That means, getting a response from the system out of the deadline is still useful for the end user but its usefulness degrade after reaching the deadline. A simple example for this case is a software that automatically controls the temperature of a room (or a building). In this case if the system has some delays reading the temperature sensors it will be a little bit slow to react upon brusque temperature changes. However, at the end it will end up reacting to the change and adjusting accordingly the temperature to keep it constant for example. So in this case the delayed reaction is useful, but it degrades the system quality of service.

Annotation-specified bean name conflicts with existing, non-compatible bean def

Refresh gradle project on Eclipse solved this problem for me

get current date from [NSDate date] but set the time to 10:00 am

this nsdate used different format:

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMM dd, yyyy HH:mm"];

NSDate *now = [[NSDate alloc] init];

NSString *dateString = [format stringFromDate:now];

NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"MMM dd, yyyy"];

NSDate *parsed = [inFormat dateFromString:dateString]; 

convert big endian to little endian in C [without using provided func]

Here's a fairly generic version; I haven't compiled it, so there are probably typos, but you should get the idea,

void SwapBytes(void *pv, size_t n)
{
    assert(n > 0);

    char *p = pv;
    size_t lo, hi;
    for(lo=0, hi=n-1; hi>lo; lo++, hi--)
    {
        char tmp=p[lo];
        p[lo] = p[hi];
        p[hi] = tmp;
    }
}
#define SWAP(x) SwapBytes(&x, sizeof(x));

NB: This is not optimised for speed or space. It is intended to be clear (easy to debug) and portable.

Update 2018-04-04 Added the assert() to trap the invalid case of n == 0, as spotted by commenter @chux.

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

The simplest way of doing this which I find useful is the below.

This might not be the official way but it works well.

Suppose you have a project named "XYZ" on your PC. Now you want to make a git repo of this project on github and use its functionalities.

Step 1: go to "www.github.com"

Step 2: create a repository with a "README.md" file (name it as you like it)

Step 3: clone the repository to your PC.

Step 4: In the cloned folder you will get two things : ".git" folder and a "README.md" file. Copy these two in your project folder "XYZ".

Step 5: Delete the cloned repo.

Step 6: add, commit and push all the files and folders of your project.

Now, you can just use your project "XYZ" as a git repository.

The entity name must immediately follow the '&' in the entity reference

Just in case someone from Blogger arrives, I had this problem when using Beautify extension in VSCode. Don´t use it, don´t beautify it.

How to change the pop-up position of the jQuery DatePicker control

$('.PDatePicker').MdPersianDateTimePicker({
                Placement: 'top',          
            });

Parse query string in JavaScript

Here is a fast and easy way of parsing query strings in JavaScript:

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    console.log('Query variable %s not found', variable);
}

Now make a request to page.html?x=Hello:

console.log(getQueryVariable('x'));

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In case you are uploading an sql file on cpanel, then try and replace root with your cpanel username in your sql file.

in the case above you could write

CREATE DEFINER = control_panel_username@localhost FUNCTION fnc_calcWalkedDistance

then upload the file. Hope it helps

MySQL SELECT AS combine two columns into one

In case of NULL columns it is better to use IF clause like this which combine the two functions of : CONCAT and COALESCE and uses special chars between the columns in result like space or '_'

SELECT FirstName , LastName , 
IF(FirstName IS NULL AND LastName IS NULL, NULL,' _ ',CONCAT(COALESCE(FirstName ,''), COALESCE(LastName ,''))) 
AS Contact_Phone FROM   TABLE1

What is w3wp.exe?

Chris pretty much sums up what w3wp is. In order to disable the warning, go to this registry key:

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Debugger

And set the value DisableAttachSecurityWarning to 1.

How can I override Bootstrap CSS styles?

A bit late but what I did is I added a class to the root div then extends every bootstrap elements in my custom stylesheet:

.overrides .list-group-item {
    border-radius: 0px;
}
.overrides .some-elements-from-bootstrap { 
    /* styles here */
}
<div class="container-fluid overrides">
    <div class="row">
        <div class="col-sm-4" style="background-color: red">
            <ul class="list-group">
                <li class="list-group-item"><a href="#">Hey</a></li>
                <li class="list-group-item"><a href="#">I was doing</a></li>
                <li class="list-group-item"><a href="#">Just fine</a></li>
                <li class="list-group-item"><a href="#">Until I met you</a></li>
                <li class="list-group-item"><a href="#">I drink too much</a></li>
                <li class="list-group-item"><a href="#">And that's an issue</a></li>
                <li class="list-group-item"><a href="#">But I'm okay</a></li>
            </ul>
        </div>
        <div class="col-sm-8" style="background-color: blue">
            right
        </div>
    </div>
</div>

Update multiple rows in same query using PostgreSQL

Let's say you have an array of IDs and equivalent array of statuses - here is an example how to do this with a static SQL (a sql query that doesn't change due to different values) of the arrays :

drop table if exists results_dummy;
create table results_dummy (id int, status text, created_at timestamp default now(), updated_at timestamp default now());
-- populate table with dummy rows
insert into results_dummy
(id, status)
select unnest(array[1,2,3,4,5]::int[]) as id, unnest(array['a','b','c','d','e']::text[]) as status;

select * from results_dummy;

-- THE update of multiple rows with/by different values
update results_dummy as rd
set    status=new.status, updated_at=now()
from (select unnest(array[1,2,5]::int[]) as id,unnest(array['a`','b`','e`']::text[]) as status) as new
where rd.id=new.id;

select * from results_dummy;

-- in code using **IDs** as first bind variable and **statuses** as the second bind variable:
update results_dummy as rd
set    status=new.status, updated_at=now()
from (select unnest(:1::int[]) as id,unnest(:2::text[]) as status) as new
where rd.id=new.id;

How do I select between the 1st day of the current month and current day in MySQL?

try this :

SET @StartDate = DATE_SUB(DATE(NOW()),INTERVAL (DAY(NOW())-1) DAY);
SET @EndDate = ADDDATE(CURDATE(),1);
select * from table where (date >= @StartDate and date < @EndDate);

Regex for allowing alphanumeric,-,_ and space

Character sets will help out a ton here. You want to create a matching set for the characters that you want to validate:

  • You can match alphanumeric with a \w, which is the same as [A-Za-z0-9_] in JavaScript (other languages can differ).
  • That leaves - and spaces, which can be combined into a matching set such as [\w\- ]. However, you may want to consider using \s instead of just the space character (\s also matches tabs, and other forms of whitespace)
    • Note that I'm escaping - as \- so that the regex engine doesn't confuse it with a character range like A-Z
  • Last up, you probably want to ensure that the entire string matches by anchoring the start and end via ^ and $

The full regex you're probably looking for is:

/^[\w\-\s]+$/

(Note that the + indicates that there must be at least one character for it to match; use a * instead, if a zero-length string is also ok)

Finally, http://www.regular-expressions.info/ is an awesome reference


Bonus Points: This regex does not match non-ASCII alphas. Unfortunately, the regex engine in most browsers does not support named character sets, but there are some libraries to help with that.

For languages/platforms that do support named character sets, you can use /^[\p{Letter}\d\_\-\s]+$/

Manually Set Value for FormBuilder Control

  let cloneObj = Object.assign({}, this.form.getRawValue(), someClass);
  this.form.complexForm.patchValue(cloneObj);

If you don't want manually set each field.

Scroll part of content in fixed position container

Set the scrollable div to have a max-size and add overflow-y: scroll; to it's properties.

Edit: trying to get the jsfiddle to work, but it's not scrolling properly. This will take some time to figure out.

Decimal precision and scale in EF Code First

this code line could be a simpler way to acomplish the same:

 public class ProductConfiguration : EntityTypeConfiguration<Product>
    {
        public ProductConfiguration()
        {
            this.Property(m => m.Price).HasPrecision(10, 2);
        }
    }

Select box arrow style

for any1 using ie8 and dont want to use a plugin i've made something inspired by Rohit Azad and Bacotasan's blog, i just added a span using JS to show the selected value.

the html:

<div class="styled-select">
   <select>
      <option>Here is the first option</option>
      <option>The second option</option>
   </select>
   <span>Here is the first option</span>
</div>

the css (i used only an arrow for BG but you could put a full image and drop the positioning):

.styled-select div
{
    display:inline-block;
    border: 1px solid darkgray;
    width:100px;
    background:url("/Style Library/Nifgashim/Images/drop_arrrow.png") no-repeat 10px 10px;
    position:relative;
}

.styled-select div select
{
    height: 30px;
    width: 100px;
    font-size:14px;
    font-family:ariel;

    -moz-opacity: 0.00;
    opacity: .00;
    filter: alpha(opacity=00);
}

.styled-select div span
{
    position: absolute;
    right: 10px;
    top: 6px;
    z-index: -5;
}

the js:

$(".styled-select select").change(function(e){
     $(".styled-select span").html($(".styled-select select").val());
});

How to launch Safari and open URL from iOS app

Because this answer is deprecated since iOS 10.0, a better answer would be:

if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}else{
    UIApplication.shared.openURL(url)
}

y en Objective-c

[[UIApplication sharedApplication] openURL:@"url string" options:@{} completionHandler:^(BOOL success) {
        if (success) {
            NSLog(@"Opened url");
        }
    }];

send checkbox value in PHP form

if(isset($_POST["newsletter"]) && $_POST["newsletter"] == "newsletter"){
    //checked
}

Python: List vs Dict for look up table

You don't actually need to store 10 million values in the table, so it's not a big deal either way.

Hint: think about how large your result can be after the first sum of squares operation. The largest possible result will be much smaller than 10 million...

Best way to resolve file path too long exception

You can create a symbolic link with a shorter directory. First open command line for example by Shift + RightClick in your desired folder with a shorter path (you may have to run it as administrator).

Then type with relative or absolute paths:

mklink ShortPath\To\YourLinkedSolution C:\Path\To\Your\Solution /D

And then start the Solution from the shorter path. The advantage here is: You don't have to move anything.

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

How do I disable form fields using CSS?

input[name=username] { disabled: true; /* Does not work */ }

I know this question is quite old but for other users who come across this problem, I suppose the easiest way to disable input is simply by ':disabled'

<input type="text" name="username" value="admin" disabled />
<style type="text/css">
  input[name=username]:disabled {
    opacity: 0.5 !important; /* Fade effect */
    cursor: not-allowed; /* Cursor change to disabled state*/
  }
</style>

In reality, if you have some script to disable the input dynamically/automatically with javascript or jquery that would automatically disable based on the condition you add.

In jQuery for Example:

if (condition) {
// Make this input prop disabled state
  $('input').prop('disabled', true);
}
else {
// Do something else
}

Hope the answer in CSS helps.

android on Text Change Listener

check String before set another EditText to empty. if Field1 is empty then why need to change again to ( "" )? so you can check the size of Your String with s.lenght() or any other solution

another way that you can check lenght of String is:

String sUsername = Field1.getText().toString();
if (!sUsername.matches(""))
{
// do your job
}

Sass Variable in CSS calc() function

To use $variables inside your calc() of the height property:

HTML:

<div></div>

SCSS:

$a: 4em;

div {
  height: calc(#{$a} + 7px);
  background: #e53b2c;
}

How to get the indices list of all NaN value in numpy array?

np.isnan combined with np.argwhere

x = np.array([[1,2,3,4],
              [2,3,np.nan,5],
              [np.nan,5,2,3]])
np.argwhere(np.isnan(x))

output:

array([[1, 2],
       [2, 0]])

Field 'id' doesn't have a default value?

It amazing for me, for solving Field 'id' doesn't have a default value? I have tried all the possible ways what are given here like..

set sql_mode=""
set @@sql_mode = ''; etc

but unfortunately these didn't work for me. So after long investigation, I found that

@Entity
@Table(name="vendor_table")
public class Customer {
    @Id
    @Column(name="cid")
    private int cid;
.....
}

@Entity
@Table(name="vendor_table")
public class Vendor {
    @Id
    private int vid;
    @Column
    private String vname;
    .....
}

here you can see that both tables are having same name. It is very funny mistake, was done by me :)))). After correcting this,my problem was gone off.

Format decimal for percentage values?

If you want to use a format that allows you to keep the number like your entry this format works for me: "# \\%"

What are these attributes: `aria-labelledby` and `aria-hidden`

The primary consumers of these properties are user agents such as screen readers for blind people. So in the case with a Bootstrap modal, the modal's div has role="dialog". When the screen reader notices that a div becomes visible which has this role, it'll speak the label for that div.

There are lots of ways to label things (and a few new ones with ARIA), but in some cases it is appropriate to use an existing element as a label (semantic) without using the <label> HTML tag. With HTML modals the label is usually a <h> header. So in the Bootstrap modal case, you add aria-labelledby=[IDofModalHeader], and the screen reader will speak that header when the modal appears.

Generally speaking a screen reader is going to notice whenever DOM elements become visible or invisible, so the aria-hidden property is frequently redundant and can probably be skipped in most cases.

How can I parse a String to BigDecimal?

Try the correct constructor http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String)

You can directly instanciate the BigDecimal with the String ;)

Example:

BigDecimal bigDecimalValue= new BigDecimal("0.5");

How to add a string to a string[] array? There's no .Add function

Use List<T> from System.Collections.Generic

List<string> myCollection = new List<string>();

…

myCollection.Add(aString);

Or, shorthand (using collection initialiser):

List<string> myCollection = new List<string> {aString, bString}

If you really want an array at the end, use

myCollection.ToArray();

You might be better off abstracting to an interface, such as IEnumerable, then just returning the collection.

Edit: If you must use an array, you can preallocate it to the right size (i.e. the number of FileInfo you have). Then, in the foreach loop, maintain a counter for the array index you need to update next.

private string[] ColeccionDeCortes(string Path)
{
    DirectoryInfo X = new DirectoryInfo(Path);
    FileInfo[] listaDeArchivos = X.GetFiles();
    string[] Coleccion = new string[listaDeArchivos.Length];
    int i = 0;

    foreach (FileInfo FI in listaDeArchivos)
    {
        Coleccion[i++] = FI.Name;
        //Add the FI.Name to the Coleccion[] array, 
    }

    return Coleccion;
}

jQuery remove special characters from string and more

Assuming by "special" you mean non-word characters, then that is pretty easy.

str = str.replace(/[_\W]+/g, "-")

Ternary operator (?:) in Bash

There's also a very similar but simpler syntax for ternary conditionals in bash:

a=$(( b == 5 ? 123 : 321  ))

Select first occurring element after another element

I use latest CSS and "+" didn't work for me so I end up with

:first-child

Set Culture in an ASP.Net MVC app

I'm using this localization method and added a route parameter that sets the culture and language whenever a user visits example.com/xx-xx/

Example:

routes.MapRoute("DefaultLocalized",
            "{language}-{culture}/{controller}/{action}/{id}",
            new
            {
                controller = "Home",
                action = "Index",
                id = "",
                language = "nl",
                culture = "NL"
            });

I have a filter that does the actual culture/language setting:

using System.Globalization;
using System.Threading;
using System.Web.Mvc;

public class InternationalizationAttribute : ActionFilterAttribute {

    public override void OnActionExecuting(ActionExecutingContext filterContext) {

        string language = (string)filterContext.RouteData.Values["language"] ?? "nl";
        string culture = (string)filterContext.RouteData.Values["culture"] ?? "NL";

        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));

    }
}

To activate the Internationalization attribute, simply add it to your class:

[Internationalization]
public class HomeController : Controller {
...

Now whenever a visitor goes to http://example.com/de-DE/Home/Index the German site is displayed.

I hope this answers points you in the right direction.

I also made a small MVC 5 example project which you can find here

Just go to http://{yourhost}:{port}/en-us/home/index to see the current date in English (US), or change it to http://{yourhost}:{port}/de-de/home/index for German etcetera.

Can you Run Xcode in Linux?

The easiest option to do that is running a VM with a OSX copy.

Get properties of a class

Just for fun

class A {
    private a1 = void 0;
    private a2 = void 0;
}

class B extends A {
    private a3 = void 0;
    private a4 = void 0;
}

class C extends B {
    private a5 = void 0;
    private a6 = void 0;
}

class Describer {
    private static FRegEx = new RegExp(/(?:this\.)(.+?(?= ))/g); 
    static describe(val: Function, parent = false): string[] {
        var result = [];
        if (parent) {
            var proto = Object.getPrototypeOf(val.prototype);
            if (proto) {
                result = result.concat(this.describe(proto.constructor, parent));
            } 
        }
        result = result.concat(val.toString().match(this.FRegEx) || []);
        return result;
    }
}

console.log(Describer.describe(A)); // ["this.a1", "this.a2"]
console.log(Describer.describe(B)); // ["this.a3", "this.a4"]
console.log(Describer.describe(C, true)); // ["this.a1", ..., "this.a6"]

Update: If you are using custom constructors, this functionality will break.

How to get a vCard (.vcf file) into Android contacts from website

Just to let you know: I just tried it using a vCard 2.1 file created according to the vCard 2.1 spec. I found that vCard 2.1, despite being an old version, already covered everything I needed, including a base64-encoded photo and international character sets.

It worked perfectly on my unmodified Android 4.1.1 device (Galaxy S3). It also worked on an old iPhone 3GS (iOS 5, via the Evernote app) and a coworker's unmodified old Android 2.1 device. You only need to set the Content-disposition to attachment as suggested above.

A minor problem was that I triggered the VCF download using a QR code, which I scanned with the Microsoft Tag app. That app told me Android couldn't handle the text/x-vcard media type (or just text/vcard, no matter). Once I opened the link in a Web browser (I tried Chrome and the Android default browser), it worked fine.

How can I display two div in one line via css inline property

use inline-block instead of inline. Read more information here about the difference between inline and inline-block.

.inline { 
display: inline-block; 
border: 1px solid red; 
margin:10px;
}

DEMO

How to delete a folder in C++?

My own implementation based off hB0 that also allows you to view the number of files in each folder also with a little performance boost.

#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <windows.h>
#include <conio.h>

union seperated {
  struct {
    unsigned int low;
    unsigned int high;
  } uint;
  unsigned long long ull;
};

unsigned long long num_dirs  = 1;
unsigned long long num_files = 0;
seperated size_files;

int DeleteDirectory( char* refRootDirectory );      //predeclare it

int DeleteDirectory( char* refRootDirectory ) {
    HANDLE      hFile;              // Handle to directory
    std::string strFilePath;            // Filepath
    WIN32_FIND_DATA FileInformation;    // File information
    int     dwError;            // Folder deleting error
    std::string strPattern;         // Pattern

    strPattern = (std::string)(refRootDirectory) + "\\*.*";
    hFile = ::FindFirstFile( strPattern.c_str(), &FileInformation );

    if( hFile != INVALID_HANDLE_VALUE )
    {
        do {
            if( FileInformation.cFileName[0] != '.' ) {
                strFilePath.erase();
                strFilePath = std::string(refRootDirectory) + "\\" + FileInformation.cFileName;

                if( FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
                    DeleteDirectory( (char*)strFilePath.c_str() );

                    dwError = ::GetLastError();
                    if( dwError != ERROR_NO_MORE_FILES ) {
                        std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                        return dwError;
                    } else {
                        // Set directory attributes
                        if( ! ::SetFileAttributes(refRootDirectory,FILE_ATTRIBUTE_NORMAL) ) {
                            std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                            return ::GetLastError();
                        }

                        // Delete directory
                        if( ! ::RemoveDirectory(refRootDirectory) ) {
                            std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                            return ::GetLastError();
                        }
                    }

                    ++num_dirs;
                } else {

                    // Set file attributes
                    if( ! ::SetFileAttributes(strFilePath.c_str(),FILE_ATTRIBUTE_NORMAL) ) {
                        std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                        return ::GetLastError();
                    }

                    // Delete file
                    if ( ! ::DeleteFile(strFilePath.c_str()) ) {
                        std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                        return ::GetLastError();
                    }

                    size_files.ull       += FileInformation.nFileSizeLow;
                    size_files.uint.high += FileInformation.nFileSizeHigh;

                    ++num_files;
                }
            }
        } while( ::FindNextFile(hFile,&FileInformation) );

        // Close handle
        ::FindClose( hFile  );
    }

    return 0;
}

unsigned long long num_files_total=0;
unsigned long long num_dirs_total=0;
unsigned long long total_size_files=0;

void my_del_directory( char* dir_name ) {
    int iRC = DeleteDirectory( dir_name );
    //int iRC=0;

    std::cout << "\"" << dir_name << "\""
             "\n    Folders: " << num_dirs
          << "\n    Files:   " << num_files
          << "\n    Size:    " << size_files.ull << " Bytes";
    if(iRC)
    {
        std::cout << "\n!ERROR!: " << iRC;
    }
    std::cout << "\n\n";

    num_dirs_total   += num_dirs;
    num_files_total  += num_files;
    total_size_files += size_files.ull;
    num_dirs  = 1;
    num_files = 0;
    size_files.ull = 0ULL;
    return;
}

int main( void )
{
    size_files.ull = 0ULL;

    my_del_directory( (char*)"C:\Windows\temp"      );
        // This will clear out the System temporary directory on windows systems

    std::cout << "\n\nResults" << "\nTotal Folders: " << num_dirs_total
                   << "\nTotal Files:   " << num_files_total
                   << "\nTotal Size:    " << total_size_files << " Bytes\n";

    return 0;
}

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

#1071 - Specified key was too long; max key length is 767 bytes

you could add an column of the md5 of long columns

How to create a shared library with cmake?

This minimal CMakeLists.txt file compiles a simple shared library:

cmake_minimum_required(VERSION 2.8)

project (test)
set(CMAKE_BUILD_TYPE Release)

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
add_library(test SHARED src/test.cpp)

However, I have no experience copying files to a different destination with CMake. The file command with the COPY/INSTALL signature looks like it might be useful.

How to completely DISABLE any MOUSE CLICK

To disable all mouse click

var event = $(document).click(function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.stopImmediatePropagation();
    return false;
});

// disable right click
$(document).bind('contextmenu', function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.stopImmediatePropagation();
    return false;
});

to enable it again:

$(document).unbind('click');
$(document).unbind('contextmenu');

Prevent Android activity dialog from closing on outside touch

What worked for me was to create DialogFragment an set it to not be cancelable:

dialog.setCancelable(false);

How to pad a string with leading zeros in Python 3

I suggest this ugly method but it works:

length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)

I came here to find a lighter solution than this one!

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

You need to use a Theme.AppCompat theme (or descendant) with this activity

I had an activity with theme <android:theme="@android:style/Theme.Dialog"> used for showing dialog in my appWidget and i had same problem

i solved this error by changing activity code like below:

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.Theme_AppCompat_Dialog); //this line i added
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dialog);
}

How do I install Java on Mac OSX allowing version switching?

This is how I did it.

Step 1: Install Java 11

You can download Java 11 dmg for mac from here: https://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html

Step 2: After installation of Java 11. Confirm installation of all versions. Type the following command in your terminal.

/usr/libexec/java_home -V

Step 3: Edit .bash_profile

sudo nano ~/.bash_profile

Step 4: Add 11.0.1 as default. (Add below line to bash_profile file).

export JAVA_HOME=$(/usr/libexec/java_home -v 11.0.1)

to switch to any version

export JAVA_HOME=$(/usr/libexec/java_home -v X.X.X)

Now Press CTRL+X to exit the bash. Press 'Y' to save changes.

Step 5: Reload bash_profile

source ~/.bash_profile

Step 6: Confirm current version of Java

java -version

Smooth scroll to div id jQuery

Here is my solution to smooth scroll to div / anchor using jQuery in case you have a fixed header so that it doesn't scroll underneath it. Also it works if you link it from other page.

Just replace ".site-header" to div that contains your header.

$(function() {

$('a[href*="#"]:not([href="#"])').click(function() {
var headerheight = $(".site-header").outerHeight();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

  if (target.length) {
    $('html, body').animate({
      scrollTop: (target.offset().top - headerheight)
    }, 1000);
    return false;
  }
}
});

//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var headerheight = $(".site-header").outerHeight();
  var target = $('#'+location.href.split("#")[1]);
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top - headerheight
    }, 1);
    return false;
  }
}
});

How to encrypt and decrypt file in Android?

Use a CipherOutputStream or CipherInputStream with a Cipher and your FileInputStream / FileOutputStream.

I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding") for creating the Cipher class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.

Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.

If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.

Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes() but use String.getBytes(StandardCharsets.UTF_8).

To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.

Be warned that CipherInputStream may not report BadPaddingException, this includes BadPaddingException generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.

How do I check whether an array contains a string in TypeScript?

do like this:

departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
            return;
    }

What's the proper way to "go get" a private repository?

If you've already got git using SSH, this answer by Ammar Bandukwala is a simple workaround:


$ go get uses git internally. The following one liners will make git and consequently $ go get clone your package via SSH.

Github:

$ git config --global url."[email protected]:".insteadOf "https://github.com/"

BitBucket:

$ git config --global url."[email protected]:".insteadOf "https://bitbucket.org/"

How can I redirect a php page to another php page?

While all of the other answers work, they all have one big problem: it is up to the browser to decide what to do if they encounter a Location header. Usually browser stop processing the request and redirect to the URI indicated with the Location header. But a malicious user could just ignore the Location header and continue its request. Furthermore there may be other things that cause the php interpreter to continue evaluating the script past the Location header, which is not what you intended.

Image this:

<?php
if (!logged_id()) {
    header("Location:login.php");
}

delete_everything();
?>

What you want and expected is that not logged in users are redirected to the login page, so that only logged in users can delete_everything. But if the script gets executed past the Location header still everything gets deleted. Thus, it is import to ALWAYS put an exit after a Location header, like this:

<?php
if (!logged_id()) {
    header("Location:login.php");
    exit; // <- don't forget this!
}

delete_everything();
?>

So, to answer your question: to redirect from a php page to another page (not just php, you can redirect to any page this way), use this:

<?php 

header("Location:http://www.example.com/some_page.php"); 
exit; // <- don't forget this!

?>

Small note: the HTTP standard says that you must provide absolute URLs in the Location header (http://... like in my example above) even if you just want to redirect to another file on the same domain. But in practice relative URLs (Location:some_page.php) work in all browsers, though not being standard compliant.

Responding with a JSON object in Node.js (converting object/array to JSON string)

You have to use the JSON.stringify() function included with the V8 engine that node uses.

var objToJson = { ... };
response.write(JSON.stringify(objToJson));

Edit: As far as I know, IANA has officially registered a MIME type for JSON as application/json in RFC4627. It is also is listed in the Internet Media Type list here.

Node.js https pem error: routines:PEM_read_bio:no start line

You are probably using the wrong certificate file, what you need to do is generate a self signed certificate which can be done as follows

openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt

then use the server.crt

   var options = {
      key: fs.readFileSync('./key.pem', 'utf8'),
      cert: fs.readFileSync('./server.crt', 'utf8')
   };

Is there a decorator to simply cache function return values?

It sounds like you're not asking for a general-purpose memoization decorator (i.e., you're not interested in the general case where you want to cache return values for different argument values). That is, you'd like to have this:

x = obj.name  # expensive
y = obj.name  # cheap

while a general-purpose memoization decorator would give you this:

x = obj.name()  # expensive
y = obj.name()  # cheap

I submit that the method-call syntax is better style, because it suggests the possibility of expensive computation while the property syntax suggests a quick lookup.

[Update: The class-based memoization decorator I had linked to and quoted here previously doesn't work for methods. I've replaced it with a decorator function.] If you're willing to use a general-purpose memoization decorator, here's a simple one:

def memoize(function):
  memo = {}
  def wrapper(*args):
    if args in memo:
      return memo[args]
    else:
      rv = function(*args)
      memo[args] = rv
      return rv
  return wrapper

Example usage:

@memoize
def fibonacci(n):
  if n < 2: return n
  return fibonacci(n - 1) + fibonacci(n - 2)

Another memoization decorator with a limit on the cache size can be found here.

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

I have try with the SCFRench and with the Ru Hasha on octave.

And finally it works: but I have done some modification

function message = makefuns
    assignin('base','fun1', @fun1);   % Ru Hasha
    assignin('base', 'fun2', @fun2);  % Ru Hasha
    message.fun1=@fun1;               % SCFrench
    message.fun2=@fun2;               % SCFrench
end

function y=fun1(x)
    y=x;
end

function z=fun2
    z=1;
end

Can be called in other 'm' file:

printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());

update:

I added an answer because neither the +72 nor the +20 worked in octave for me. The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).

On a CSS hover event, can I change another div's styling?

A pure solution without jQuery:

Javascript (Head)

function chbg(color) {
    document.getElementById('b').style.backgroundColor = color;
}   

HTML (Body)

<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This is element a</div>
<div id="b">This is element b</div>

JSFiddle: http://jsfiddle.net/YShs2/

Appending to an existing string

Here's another way:

fist_segment = "hello,"
second_segment = "world."
complete_string = "#{first_segment} #{second_segment}"

Invalid application path

I was also getting this error. The problem for me turned out to be that I had two separate websites on the machine, and I had not designated which address went to which website. To resolve this, go to IIS Manager -> Select Web Site -> Bindings -> Add... -> Enter the host name that you want to resolve for this website. Repeat for any other websites on the machine.

HTH. Rick

how to check if List<T> element contains an item with a Particular Property Value

You can using the exists

if (pricePublicList.Exists(x => x.Size == 200))
{
   //code
}

How do I get the day of week given a date?

If you're not solely reliant on the datetime module, calendar might be a better alternative. This, for example, will provide you with the day codes:

calendar.weekday(2017,12,22);

And this will give you the day itself:

days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
days[calendar.weekday(2017,12,22)]

Or in the style of python, as a one liner:

["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][calendar.weekday(2017,12,22)]

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

Java 8 Distinct by property

Set<YourPropertyType> set = new HashSet<>();
list
        .stream()
        .filter(it -> set.add(it.getYourProperty()))
        .forEach(it -> ...);

Visual Studio "Could not copy" .... during build

In my case the files VS coulnd't copy were those of the .Task project, so the problem was that I had a few scheduled tasks running locally. Once I stopped and disabled them, the copy problem disappeared.

Twitter bootstrap modal-backdrop doesn't disappear

I suffered a similar issue: in my modal window, I have two buttons, "Cancel" and "OK". Originally, both buttons would close the modal window by invoking $('#myModal').modal('hide') (with "OK" previously executing some code) and the scenario would be the following:

  1. Open the modal window
  2. Do some operations, then click on "OK" do validate them and close the modal
  3. Open the modal again and dismiss by clicking on "Cancel"
  4. Re-open the modal, click again on "Cancel" ==> the backdrop is no longer accessible!

well, my fellow next desk saved my day: instead of invoking $('#myModal').modal('hide'), give your buttons the attribute data-dismiss="modal" and add a "click" event to your "Submit" button. In my problem, the HTML (well, TWIG) code for the button is:

<button id="modal-btn-ok" class="btn" data-dismiss="modal">OK</button>
<button id="modal-btn-cancel" class="btn" data-dismiss="modal">Cancel</button>

and in my JavaScript code, I have:

$("#modal-btn-ok").one("click", null, null, function(){
    // My stuff to be done
});

while no "click" event is attributed to the "Cancel" button. The modal now closes properly and lets me play again with the "normal" page. It actually seems that the data-dismiss="modal" should be the only way to indicate that a button (or whatever DOM element) should close a Bootstrap modal. The .modal('hide') method seems to behave in a not quite controllable way.

Hope this helps!

Why do you create a View in a database?

The one major advantage of a view over a stored procedure is that you can use a view just like you use a table. Namely, a view can be referred to directly in the FROM clause of a query. E.g., SELECT * FROM dbo.name_of_view.

In just about every other way, stored procedures are more powerful. You can pass in parameters, including out parameters that allow you effectively to return several values at once, you can do SELECT, INSERT, UPDATE, and DELETE operations, etc. etc.

If you want a View's ability to query from within the FROM clause, but you also want to be able to pass in parameters, there's a way to do that too. It's called a table-valued function.

Here's a pretty useful article on the topic:

http://databases.aspfaq.com/database/should-i-use-a-view-a-stored-procedure-or-a-user-defined-function.html

EDIT: By the way, this sort of raises the question, what advantage does a view have over a table-valued function? I don't have a really good answer to that, but I will note that the T-SQL syntax for creating a view is simpler than for a table-valued function, and users of your database may be more familiar with views.

How can I run an external command asynchronously from Python?

There are several answers here but none of them satisfied my below requirements:

  1. I don't want to wait for command to finish or pollute my terminal with subprocess outputs.

  2. I want to run bash script with redirects.

  3. I want to support piping within my bash script (for example find ... | tar ...).

The only combination that satiesfies above requirements is:

subprocess.Popen(['./my_script.sh "arg1" > "redirect/path/to"'],
                 stdout=subprocess.PIPE, 
                 stderr=subprocess.PIPE,
                 shell=True)

Java; String replace (using regular expressions)?

String input = "hello I'm a java dev" +
"no job experience needed" +
"senior software engineer" +
"java job available for senior software engineer";

String fixedInput = input.replaceAll("(java|job|senior)", "<b>$1</b>");

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

Those seem to be MySQL data types.

According to the documentation they take:

  1. tinyint = 1 byte
  2. smallint = 2 bytes
  3. mediumint = 3 bytes
  4. int = 4 bytes
  5. bigint = 8 bytes

And, naturally, accept increasingly larger ranges of numbers.

What does the M stand for in C# Decimal literal notation?

It means it's a decimal literal, as others have said. However, the origins are probably not those suggested elsewhere in this answer. From the C# Annotated Standard (the ECMA version, not the MS version):

The decimal suffix is M/m since D/d was already taken by double. Although it has been suggested that M stands for money, Peter Golde recalls that M was chosen simply as the next best letter in decimal.

A similar annotation mentions that early versions of C# included "Y" and "S" for byte and short literals respectively. They were dropped on the grounds of not being useful very often.

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

npm --depth 9999 update fixed the issue for me--apparently because package-lock.json was insisting on the outdated versions.

What is a superfast way to read large files line-by-line in VBA?

You can use Scripting.FileSystemObject to do that thing. From the Reference:

The ReadLine method allows a script to read individual lines in a text file. To use this method, open the text file, and then set up a Do Loop that continues until the AtEndOfStream property is True. (This simply means that you have reached the end of the file.) Within the Do Loop, call the ReadLine method, store the contents of the first line in a variable, and then perform some action. When the script loops around, it will automatically drop down a line and read the second line of the file into the variable. This will continue until each line has been read (or until the script specifically exits the loop).

And a quick example:

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ServerList.txt", 1)
Do Until objFile.AtEndOfStream
 strLine = objFile.ReadLine
 MsgBox strLine
Loop
objFile.Close

Programmatically change the height and width of a UIImageView Xcode Swift

u can use this code

var imageView = UIImageView(image: UIImage(name:"imageName"));
imageView.frame = CGrectMake(x,y imageView.frame.width*0.2,50);

or

var imageView = UIImageView(frame:CGrectMake(x,y, self.view.frame.size.width *0.2, 50)

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

try:

%matplotlib notebook

see jakevdp reply here

EDIT for JupyterLab users:

Follow the instructions to install jupyter-matplotlib

Then the magic command above is no longer needed, as in the example:

# Enabling the `widget` backend.
# This requires jupyter-matplotlib a.k.a. ipympl.
# ipympl can be install via pip or conda.
%matplotlib widget
# aka import ipympl

import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 2])
plt.show()

Finally, note Maarten Breddels' reply; IMHO ipyvolume is indeed very impressive (and useful!).

Measuring text height to be drawn on Canvas ( Android )

If anyone still has problem, this is my code.

I have a custom view which is square (width = height) and I want to assign a character to it. onDraw() shows how to get height of character, although I'm not using it. Character will be displayed in the middle of view.

public class SideBarPointer extends View {

    private static final String TAG = "SideBarPointer";

    private Context context;
    private String label = "";
    private int width;
    private int height;

    public SideBarPointer(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    private void init() {
//        setBackgroundColor(0x64FF0000);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        height = this.getMeasuredHeight();
        width = this.getMeasuredWidth();

        setMeasuredDimension(width, width);
    }

    protected void onDraw(Canvas canvas) {
        float mDensity = context.getResources().getDisplayMetrics().density;
        float mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;

        Paint previewPaint = new Paint();
        previewPaint.setColor(0x0C2727);
        previewPaint.setAlpha(200);
        previewPaint.setAntiAlias(true);

        Paint previewTextPaint = new Paint();
        previewTextPaint.setColor(Color.WHITE);
        previewTextPaint.setAntiAlias(true);
        previewTextPaint.setTextSize(90 * mScaledDensity);
        previewTextPaint.setShadowLayer(5, 1, 2, Color.argb(255, 87, 87, 87));

        float previewTextWidth = previewTextPaint.measureText(label);
//        float previewTextHeight = previewTextPaint.descent() - previewTextPaint.ascent();
        RectF previewRect = new RectF(0, 0, width, width);

        canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
        canvas.drawText(label, (width - previewTextWidth)/2, previewRect.top - previewTextPaint.ascent(), previewTextPaint);

        super.onDraw(canvas);
    }

    public void setLabel(String label) {
        this.label = label;
        Log.e(TAG, "Label: " + label);

        this.invalidate();
    }
}

Add JavaScript object to JavaScript object

As my first object is a native javascript object (used like a list of objects), push didn't work in my escenario, but I resolved it by adding new key as following:

MyObjList['newKey'] = obj;

In addition to this, may be usefull to know how to delete same object inserted before:

delete MyObjList['newKey'][id];

Hope it helps someone as it helped me;

Retrieve column values of the selected row of a multicolumn Access listbox

For multicolumn listbox extract data from any column of selected row by

 listboxControl.List(listboxControl.ListIndex,col_num)

where col_num is required column ( 0 for first column)

How to convert an iterator to a stream?

Great suggestion! Here's my reusable take on it:

public class StreamUtils {

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
        return asStream(sourceIterator, false);
    }

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator, boolean parallel) {
        Iterable<T> iterable = () -> sourceIterator;
        return StreamSupport.stream(iterable.spliterator(), parallel);
    }
}

And usage (make sure to statically import asStream):

List<String> aPrefixedStrings = asStream(sourceIterator)
                .filter(t -> t.startsWith("A"))
                .collect(toList());

How do I find an array item with TypeScript? (a modern, easier way)

You could just use underscore library.

Install it:

   npm install underscore --save
   npm install @types/underscore --save-dev

Import it

   import _ = require('underscore');

Use it

    var x = _.filter(
      [{ "id": 1 }, { "id": -2 }, { "id": 3 }],
      myObj => myObj.id < 0)
    );

How do I close a single buffer (out of many) in Vim?

How about

vim -O a a

That way you can edit a single file on your left and navigate the whole dir on your right... Just a thought, not the solution...

Spring Security exclude url patterns in security annotation configurartion

Found the solution in Spring security examples posted in Github.

WebSecurityConfigurerAdapter has a overloaded configure message that takes WebSecurity as argument which accepts ant matchers on requests to be ignored.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/authFailure");
}

See Spring Security Samples for more details

What is the difference between atan and atan2 in C++?

std::atan2 allows calculating the arctangent of all four quadrants. std::atan only allows calculating from quadrants 1 and 4.

Cannot push to GitHub - keeps saying need merge

I experienced the very same problem and it turned out I was on a different (local) branch than I thought I was AND the correct local branch was behind in commits from remote.

My solution: checkout the correct branch, cherry-pick the commit from the other local branch, git pull and git push

Argument Exception "Item with Same Key has already been added"

To illustrate the problem you are having, let's look at some code...

Dictionary<string, string> test = new Dictionary<string, string>();

test.Add("Key1", "Value1");  // Works fine
test.Add("Key2", "Value2");  // Works fine
test.Add("Key1", "Value3");  // Fails because of duplicate key

The reason that a dictionary has a key/value pair is a feature so you can do this...

var myString = test["Key2"];  // myString is now Value2.

If Dictionary had 2 Key2's, it wouldn't know which one to return, so it limits you to a unique key.

What is the difference between task and thread?

A task is something you want done.

A thread is one of the many possible workers which performs that task.

In .NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.

How to create dispatch queue in Swift 3

Compiles under >=Swift 3. This example contains most of the syntax that we need.

QoS - new quality of service syntax

weak self - to disrupt retain cycles

if self is not available, do nothing

async global utility queue - for network query, does not wait for the result, it is a concurrent queue, the block (usually) does not wait when started. Exception for a concurrent queue could be, when its task limit has been previously reached, then the queue temporarily turns into a serial queue and waits until some previous task in that queue completes.

async main queue - for touching the UI, the block does not wait for the result, but waits for its slot at the start. The main queue is a serial queue.

Of course, you need to add some error checking to this...

DispatchQueue.global(qos: .utility).async { [weak self] () -> Void in

    guard let strongSelf = self else { return }

    strongSelf.flickrPhoto.loadLargeImage { loadedFlickrPhoto, error in

        if error != nil {
            print("error:\(error)")
        } else {
            DispatchQueue.main.async { () -> Void in
                activityIndicator.removeFromSuperview()
                strongSelf.imageView.image = strongSelf.flickrPhoto.largeImage
            }
        }
    }
}

How to center links in HTML

p is not how you put text in a. That is the problem. The only solution is to put the text between <a> and </a>. For example:

<a href="https://stackoverflow.com/posts/64201994/edit" style="text-align:center;">Stack Overflow</a>

What is the Python equivalent of Matlab's tic and toc functions?

Updating Eli's answer to Python 3:

class Timer(object):
    def __init__(self, name=None, filename=None):
        self.name = name
        self.filename = filename

    def __enter__(self):
        self.tstart = time.time()

    def __exit__(self, type, value, traceback):
        message = 'Elapsed: %.2f seconds' % (time.time() - self.tstart)
        if self.name:
            message = '[%s] ' % self.name + message
        print(message)
        if self.filename:
            with open(self.filename,'a') as file:
                print(str(datetime.datetime.now())+": ",message,file=file)

Just like Eli's, it can be used as a context manager:

import time 
with Timer('Count'):
    for i in range(0,10_000_000):
        pass

Output:

[Count] Elapsed: 0.27 seconds

I have also updated it to print the units of time reported (seconds) and trim the number of digits as suggested by Can, and with the option of also appending to a log file. You must import datetime to use the logging feature:

import time
import datetime 
with Timer('Count', 'log.txt'):    
    for i in range(0,10_000_000):
        pass

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

This is kind of a hack but the best solution that I have found is to use a description tag with no \item. This will produce an error from the latex compiler; however, the error does not prevent the pdf from being generated.

\begin{description} 
     <YOUR TEXT HERE> 
\end{description}
  • This only worked on windows latex compiler

Login credentials not working with Gmail SMTP

I beleive I'm little late here. But I think this would help for the new peeps! If you're using smtp.gmail.com , then you have to do the following:

  1. Turn on the less secure apps

  2. You'll get the security mail in your gmail inbox, Click Yes,it's me in that.

  3. Now run your code again.

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

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

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

The documentation now reads:

--depth <depth>::

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

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

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

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


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

This is "Documentation/user-manual.txt"

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

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

Update 2020:

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

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


As commented by Richard Michael:

to backfill history: git pull --unshallow

And Olle Härstedt adds in the comments:

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

Changing :hover to touch/click for mobile devices

On most devices, the other answers work. For me, to ensure it worked on every device (in react) I had to wrap it in an anchor tag <a> and add the following: :hover, :focus, :active (in that order), as well as role="button" and tabIndex="0".

How to enable file sharing for my app?

In Xcode 8.3.3 add new row in .plist with true value

Application supports iTunes file sharing

Compare two files report difference in python

The difflib library is useful for this, and comes in the standard library. I like the unified diff format.

http://docs.python.org/2/library/difflib.html#difflib.unified_diff

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
        )
        for line in diff:
            sys.stdout.write(line)

Outputs:

--- hosts0
+++ hosts1
@@ -1,5 +1,4 @@
 one
 two
-dogs
 three

And here is a dodgy version that ignores certain lines. There might be edge cases that don't work, and there are surely better ways to do this, but maybe it will be good enough for your purposes.

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
            n=0,
        )
        for line in diff:
            for prefix in ('---', '+++', '@@'):
                if line.startswith(prefix):
                    break
            else:
                sys.stdout.write(line[1:])

jQuery - Uncaught RangeError: Maximum call stack size exceeded

Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.

Also based on your markup your selector is wrong. it should be #advisersDiv

Demo

function fadeIn() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
    setTimeout(fadeOut,1); //<-- Provide any delay here
};

function fadeOut() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
    setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();

Eclipse error "Could not find or load main class"

I am assuming that you had imported the project into your desktop eclipse installation? If that is the case, you should just select Project > Clean. Then rebuild your project. Worked like a charm for me.

Read file from aws s3 bucket using node fs

I prefer Buffer.from(data.Body).toString('utf8'). It supports encoding parameters. With other AWS services (ex. Kinesis Streams) someone may want to replace 'utf8' encoding with 'base64'.

new AWS.S3().getObject(
  { Bucket: this.awsBucketName, Key: keyName }, 
  function(err, data) {
    if (!err) {
      const body = Buffer.from(data.Body).toString('utf8');
      console.log(body);
    }
  }
);

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

How to set upload_max_filesize in .htaccess?

If you are getting 500 - Internal server error that means you don't have permission to set these values by .htaccess. You have to contact your web server providers and ask to set AllowOverride Options for your host or to put these lines in their virtual host configuration file.

How to use onResume()?

onResume() is one of the methods called throughout the activity lifecycle. onResume() is the counterpart to onPause() which is called anytime an activity is hidden from view, e.g. if you start a new activity that hides it. onResume() is called when the activity that was hidden comes back to view on the screen.

You're question asks abou what method is used to restart an activity. onCreate() is called when the activity is first created. In practice, most activities persist in the background through a series of onPause() and onResume() calls. An activity is only really "restarted" by onRestart() if it is first fully stopped by calling onStop() and then brought back to life. Thus if you are not actually stopping activities with onStop() it is most likley you will be using onResume().

Read the android doc in the above link to get a better understanding of the relationship between the different lifestyle methods. Regardless of which lifecycle method you end up using the general format is the same. You must override the standard method and include your code, i.e. what you want the activity to do at that point, in the commented section.

@Override
public void onResume(){
 //will be executed onResume
}

AttributeError: can't set attribute in python

namedtuples are immutable, just like standard tuples. You have two choices:

  1. Use a different data structure, e.g. a class (or just a dictionary); or
  2. Instead of updating the structure, replace it.

The former would look like:

class N(object):

    def __init__(self, ind, set, v):
        self.ind = ind
        self.set = set
        self.v = v

And the latter:

item = items[node.ind]
items[node.ind] = N(item.ind, item.set, node.v)

Edit: if you want the latter, Ignacio's answer does the same thing more neatly using baked-in functionality.

In Angular, What is 'pathmatch: full' and what effect does it have?

RouterModule.forRoot([
      { path: 'welcome', component: WelcomeComponent },
      { path: '', redirectTo: 'welcome', pathMatch: 'full' },
      { path: '**', component: 'pageNotFoundComponent' }
    ])

Case 1 pathMatch:'full': In this case, when app is launched on localhost:4200 (or some server) the default page will be welcome screen, since the url will be https://localhost:4200/

If https://localhost:4200/gibberish this will redirect to pageNotFound screen because of path:'**' wildcard

Case 2 pathMatch:'prefix':

If the routes have { path: '', redirectTo: 'welcome', pathMatch: 'prefix' }, now this will never reach the wildcard route since every url would match path:'' defined.

Python Binomial Coefficient

A bit shortened multiplicative variant given by PM 2Ring and alisianoi. Works with python 3 and doesn't require any packages.

def comb(n, k):
  # Remove the next two lines if out-of-range check is not needed
  if k < 0 or k > n:
    return None
  x = 1
  for i in range(min(k, n - k)):
    x = x*(n - i)//(i + 1)
  return x

Or

from functools import reduce
def comb(n, k):
  return (None if k < 0 or k > n else
    reduce(lambda x, i: x*(n - i)//(i + 1), range(min(k, n - k)), 1))

The division is done right after multiplication not to accumulate high numbers.

How to change the URI (URL) for a remote Git repository?

Change remote git URI to [email protected] rather than https://github.com

git remote set-url origin [email protected]:<username>/<repo>.git

Example:

git remote set-url origin [email protected]:Chetabahana/my_repo_name.git

The benefit is that you may do git push automatically when you use ssh-agent :

#!/bin/bash

# Check ssh connection
ssh-add -l &>/dev/null
[[ "$?" == 2 ]] && eval `ssh-agent`
ssh-add -l &>/dev/null
[[ "$?" == 1 ]] && expect $HOME/.ssh/agent

# Send git commands to push
git add . && git commit -m "your commit" && git push -u origin master

Put a script file $HOME/.ssh/agent to let it runs ssh-add using expect as below:

#!/usr/bin/expect -f
set HOME $env(HOME)
spawn ssh-add $HOME/.ssh/id_rsa
expect "Enter passphrase for $HOME/.ssh/id_rsa:"
send "<my_passphrase>\n";
expect "Identity added: $HOME/.ssh/id_rsa ($HOME/.ssh/id_rsa)"
interact

Where to get this Java.exe file for a SQL Developer installation

[Context] In a virtual machine of WinXP.

My "java.exe" was in the Oracle11g folder, under the path "C:\Oracle11g\product\11.2.0\dbhome_1\jdk\bin\java.exe".

Hope it helps!!

Whoops, looks like something went wrong. Laravel 5.0

First run command composer install

Then check for .env.example and .env files in your project folder.

.env file is your main configuration file for database and .env.example is backup file for .env file.

.env.example file will always be there but sometimes .env file can be missing. just copy the .env.example file and paste in the same project folder with filename .env .

now run php artisan key:generate command. this will generate key for your application.

Find all files in a folder

A lot of these answers won't actually work, having tried them myself. Give this a go:

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.txt"))
{
      Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}

It will move all .txt files on the desktop to the folder TextFiles.

Maximum length of HTTP GET request

A similar question is here: Is there a limit to the length of a GET request?

I've hit the limit and on my shared hosting account, but the browser returned a blank page before it got to the server I think.

How to make HTTP Post request with JSON body in Swift

var request = URLRequest(url: URL(string: "http://yogpande.apphb.com/api/my/posttblhouse")!)
        request.httpMethod = "POST"
        let postString = "[email protected]&password=1234567"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print("error=(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {     
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")

            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")
        }
        task.resume()
    }

Why is using the JavaScript eval function a bad idea?

If you spot the use of eval() in your code, remember the mantra “eval() is evil.”

This function takes an arbitrary string and executes it as JavaScript code. When the code in question is known beforehand (not determined at runtime), there’s no reason to use eval(). If the code is dynamically generated at runtime, there’s often a better way to achieve the goal without eval(). For example, just using square bracket notation to access dynamic properties is better and simpler:

// antipattern
var property = "name";
alert(eval("obj." + property));

// preferred
var property = "name";
alert(obj[property]);

Using eval() also has security implications, because you might be executing code (for example coming from the network) that has been tampered with. This is a common antipattern when dealing with a JSON response from an Ajax request. In those cases it’s better to use the browsers’ built-in methods to parse the JSON response to make sure it’s safe and valid. For browsers that don’t support JSON.parse() natively, you can use a library from JSON.org.

It’s also important to remember that passing strings to setInterval(), setTimeout(), and the Function() constructor is, for the most part, similar to using eval() and therefore should be avoided.

Behind the scenes, JavaScript still has to evaluate and execute the string you pass as programming code:

// antipatterns
setTimeout("myFunc()", 1000);
setTimeout("myFunc(1, 2, 3)", 1000);

// preferred
setTimeout(myFunc, 1000);
setTimeout(function () {
myFunc(1, 2, 3);
}, 1000);

Using the new Function() constructor is similar to eval() and should be approached with care. It could be a powerful construct but is often misused. If you absolutely must use eval(), you can consider using new Function() instead.

There is a small potential benefit because the code evaluated in new Function() will be running in a local function scope, so any variables defined with var in the code being evaluated will not become globals automatically.

Another way to prevent automatic globals is to wrap the eval() call into an immediate function.

biggest integer that can be stored in a double

The largest integer that can be represented in IEEE 754 double (64-bit) is the same as the largest value that the type can represent, since that value is itself an integer.

This is represented as 0x7FEFFFFFFFFFFFFF, which is made up of:

  • The sign bit 0 (positive) rather than 1 (negative)
  • The maximum exponent 0x7FE (2046 which represents 1023 after the bias is subtracted) rather than 0x7FF (2047 which indicates a NaN or infinity).
  • The maximum mantissa 0xFFFFFFFFFFFFF which is 52 bits all 1.

In binary, the value is the implicit 1 followed by another 52 ones from the mantissa, then 971 zeros (1023 - 52 = 971) from the exponent.

The exact decimal value is:

179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368

This is approximately 1.8 x 10308.

How do I automatically update a timestamp in PostgreSQL

Using 'now()' as default value automatically generates time-stamp.

Make a float only show two decimal places

It is not a matter of how the number is stored, it is a matter of how you are displaying it. When converting it to a string you must round to the desired precision, which in your case is two decimal places.

E.g.:

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];

%.02f tells the formatter that you will be formatting a float (%f) and, that should be rounded to two places, and should be padded with 0s.

E.g.:

%f = 25.000000
%.f = 25
%.02f = 25.00

Java - How to access an ArrayList of another class?

Two ways

1)instantiate the first class and getter for arrayList

or

2)Make arraylist as static

And finally

Java Basics By Oracle

How to pass parameters on onChange of html select

You can try bellow code

<select onchange="myfunction($(this).val())" id="myId">
    </select>

Combining C++ and C - how does #ifdef __cplusplus work?

It's about the ABI, in order to let both C and C++ application use C interfaces without any issue.

Since C language is very easy, code generation was stable for many years for different compilers, such as GCC, Borland C\C++, MSVC etc.

While C++ becomes more and more popular, a lot things must be added into the new C++ domain (for example finally the Cfront was abandoned at AT&T because C could not cover all the features it needs). Such as template feature, and compilation-time code generation, from the past, the different compiler vendors actually did the actual implementation of C++ compiler and linker separately, the actual ABIs are not compatible at all to the C++ program at different platforms.

People might still like to implement the actual program in C++ but still keep the old C interface and ABI as usual, the header file has to declare extern "C" {}, it tells the compiler generate compatible/old/simple/easy C ABI for the interface functions if the compiler is C compiler not C++ compiler.

How to replace a set of tokens in a Java String?

You could try using a templating library like Apache Velocity.

http://velocity.apache.org/

Here is an example:

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;

public class TemplateExample {
    public static void main(String args[]) throws Exception {
        Velocity.init();

        VelocityContext context = new VelocityContext();
        context.put("name", "Mark");
        context.put("invoiceNumber", "42123");
        context.put("dueDate", "June 6, 2009");

        String template = "Hello $name. Please find attached invoice" +
                          " $invoiceNumber which is due on $dueDate.";
        StringWriter writer = new StringWriter();
        Velocity.evaluate(context, writer, "TemplateName", template);

        System.out.println(writer);
    }
}

The output would be:

Hello Mark. Please find attached invoice 42123 which is due on June 6, 2009.

Running Selenium Webdriver with a proxy in Python

Proxy with verification. This is a whole new python script in reference from a Mykhail Martsyniuk sample script.

# Load webdriver
from selenium import webdriver

# Load proxy option
from selenium.webdriver.common.proxy import Proxy, ProxyType

# Configure Proxy Option
prox = Proxy()
prox.proxy_type = ProxyType.MANUAL

# Proxy IP & Port
prox.http_proxy = “0.0.0.0:00000”
prox.socks_proxy = “0.0.0.0:00000”
prox.ssl_proxy = “0.0.0.0:00000”

# Configure capabilities 
capabilities = webdriver.DesiredCapabilities.CHROME
prox.add_to_capabilities(capabilities)

# Configure ChromeOptions
driver = webdriver.Chrome(executable_path='/usr/local/share chromedriver',desired_capabilities=capabilities)

# Verify proxy ip
driver.get("http://www.whatsmyip.org/")

get parent's view from a layout

This also works:

this.getCurrentFocus()

It gets the view so I can use it.

How to capture the "virtual keyboard show/hide" event in Android?

what I did is created simple binding to hide view when keyboard is visible. Solution is based on current AndroidX implementation for WindowInsetsCompat which is still in beta (androidx core 1.5) - source

private fun isKeyboardVisible(insets: WindowInsets): Boolean {
    val insetsCompat = WindowInsetsCompat.toWindowInsetsCompat(insets)
    val systemWindow = insetsCompat.systemWindowInsets
    val rootStable = insetsCompat.stableInsets
    if (systemWindow.bottom > rootStable.bottom) {
        // This handles the adjustResize case on < API 30, since
        // systemWindow.bottom is probably going to be the IME
        return true
    }
    return false
}

@BindingAdapter("goneWhenKeyboardVisible")
fun View.goneWhenKeyboardVisible(enabled: Boolean) {
    if (enabled) {
        setOnApplyWindowInsetsListener { view, insets ->
            visibility = if (isKeyboardVisible(insets)) GONE else VISIBLE
            insets
        }
    } else {
        setOnApplyWindowInsetsListener(null)
        visibility = VISIBLE
    }
}

usage:

<FrameLayout
                android:id="@+id/bottom_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:goneWhenKeyboardVisible="@{true}"
                />

ln (Natural Log) in Python

math.log is the natural logarithm:

From the documentation:

math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).

Your equation is therefore:

n = math.log((1 + (FV * r) / p) / math.log(1 + r)))

Note that in your code you convert n to a str twice which is unnecessary

Add leading zeroes/0's to existing Excel values to certain length

I hit this page trying to pad hexadecimal values when I realized that DEC2HEX() provides that very feature for free.

You just need to add a second parameter. For example, tying to turn 12 into 0C
DEC2HEX(12,2) => 0C
DEC2HEX(12,4) => 000C
... and so on

Center align with table-cell

Here is a good starting point.

HTML:

<div class="containing-table">
    <div class="centre-align">
        <div class="content"></div>
    </div>
</div>

CSS:

.containing-table {
    display: table;
    width: 100%;
    height: 400px; /* for demo only */
    border: 1px dotted blue;
}
.centre-align {
    padding: 10px;
    border: 1px dashed gray;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.content {
    width: 50px;
    height: 50px;
    background-color: red;
    display: inline-block;
    vertical-align: top; /* Removes the extra white space below the baseline */
}

See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/

.containing-table establishes the width and height context for .centre-align (the table-cell).

You can apply text-align and vertical-align to alter .centre-align as needed.

Note that .content needs to use display: inline-block if it is to be centered horizontally using the text-align property.

How to insert close button in popover for Bootstrap

As a very simple solution to this, I did the following:

1) Add the following CSS:

.sub_step_info .popover::after {
    content:url('/images/cross.png');
    position:absolute;
    display:inline-block;
    top:15px;
    right:5px;
    width:15px;
    text-align:center;
    cursor:pointer;
}

2) Set data-trigger="manual" on the popover trigger element

3) Then based on https://github.com/twbs/bootstrap/issues/16802:

$('[data-trigger="manual"]').click(function() {
    $(this).popover('toggle');
}).blur(function() {
    $(this).popover('hide');
}); 

This uses the basis that anywhere on the popover is clickable but by focusing on the cross you'll encourage the behaviour you're after.

Git remote branch deleted, but still it appears in 'branch -a'

In our particular case, we use Stash as our remote Git repository. We tried all the previous answers and nothing was working. We ended up having to do the following:

git branch –D branch-name (delete from local)
git push origin :branch-name (delete from remote)

Then when users went to pull changes, they needed to do the following:

git fetch -p

Chrome Dev Tools - Modify javascript and reload

I know it's not the asnwer to the precise question (Chrome Developer Tools) but I'm using this workaround with success: http://www.telerik.com/fiddler

(pretty sure some of the web devs already know about this tool)

  1. Save the file locally
  2. Edit as required
  3. Profit!

enter image description here

Full docs: http://docs.telerik.com/fiddler/KnowledgeBase/AutoResponder

PS. I would rather have it implemented in Chrome as a flag preserve after reload, cannot do this now, forums and discussion groups blocked on corporate network :)

Correct Semantic tag for copyright info - html5

it is better to include it in a <small> tag The HTML <small> tag is used for specifying small print.

Small print (also referred to as "fine print" or "mouseprint") usually refers to the part of a document that contains disclaimers, caveats, or legal restrictions, such as copyrights. And this tag is supported in all major browsers.

<footer>
 <small>&copy; Copyright 2058, Example Corporation</small>
</footer>

How can I convert a string to boolean in JavaScript?

function convertBoolean(value): boolean {
    if (typeof value == 'string') {
        value = value.toLowerCase();
    }
    switch (value) {
        case true:
        case "true":
        case "evet": // Locale
        case "t":
        case "e": // Locale
        case "1":
        case "on":
        case "yes":
        case 1:
            return true;
        case false:
        case "false":
        case "hayir": // Locale
        case "f":
        case "h": // Locale
        case "0":
        case "off":
        case "no":
        case 0:
            return false;
        default:
            return null;
    }
}

How do I auto-resize an image to fit a 'div' container?

A simple solution (4-step fix!!) that seems to work for me, is below. The example uses the width to determine the overall size, but you can also flip it to use the height instead.

  1. Apply CSS styling to the image container (for example, <img>)
  2. Set the width property to the dimension you want
    • For dimensions, use % for relative size, or autoscaling (based on image container or display)
    • Use px (or other) for a static, or set dimension
  3. Set the height property to automatically adjust, based on the width
  4. ENJOY!

For example,

<img style="width:100%; height:auto;"
    src="https://googledrive.com/host/0BwDx0R31u6sYY1hPWnZrencxb1k/thanksgiving.png"
/>

Dynamically change color to lighter or darker by percentage CSS (Javascript)

HSL Colors provide an answer, a HSL color value is specified with: hsl(hue [0,255], saturation %, lightness %).

HSL is supported in IE9+, Firefox, Chrome, Safari, and in Opera 10+

a
{
color:hsl(240,65%,50%);
}
a.lighter 
{
color:hsl(240,65%,75%);
}

How to re-render flatlist?

Put variables that will be changed by your interaction at extraData

You can be creative.

For example if you are dealing with a changing list with checkboxes on them.

<FlatList
      data={this.state.data.items}
      extraData={this.state.data.items.length * (this.state.data.done.length + 1) }
      renderItem={({item}) => <View>  

Remove Null Value from String array in java

It seems no one has mentioned about using nonNull method which also can be used with streams in Java 8 to remove null (but not empty) as:

String[] origArray = {"Apple", "", "Cat", "Dog", "", null};
String[] cleanedArray = Arrays.stream(firstArray).filter(Objects::nonNull).toArray(String[]::new);
System.out.println(Arrays.toString(origArray));
System.out.println(Arrays.toString(cleanedArray));

And the output is:

[Apple, , Cat, Dog, , null]

[Apple, , Cat, Dog, ]

If we want to incorporate empty also then we can define a utility method (in class Utils(say)):

public static boolean isEmpty(String string) {
        return (string != null && string.isEmpty());
    }

And then use it to filter the items as:

Arrays.stream(firstArray).filter(Utils::isEmpty).toArray(String[]::new);

I believe Apache common also provides a utility method StringUtils.isNotEmpty which can also be used.

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

On new El Capitan installation where SIP(rootless prevents access to usr/lib/) is on by default and you cannot create the symlink unless you are in recovery mode. As @yannisxu said you can disable SIP and do your symlink to /usr/lib/local and this will work.

you can use the following command on MAC OSX El Capitan instead of turning off SIP:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

There used to be an option where you can login as root and this can disable SIP but in the final release that is now obsolete, you can read more about it here: https://forums.developer.apple.com/thread/4686

Question:

There is a nvram boot-args command available in Developer Beta 1 which can disable SIP when run with root privileges:

nvram boot-args="rootless=0"

Will this option of disabling SIP also be available in the El Capitan release version? Or is this strictly for the Developer Builds?

Answer:

This nvram boot-args command will be going away. It will not be available in the El Capitan release version and may disappear before the end of the Developer Betas. Keep an eye on the release notes for future Developer Betas.

How to implement debounce in Vue2?

 public debChannel = debounce((key) => this.remoteMethodChannelName(key), 200)

vue-property-decorator

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

Get the current time in C

You can use this function to get current local time. if you want gmt then use the gmtime function instead of localtime. cheers

time_t my_time;
struct tm * timeinfo; 
time (&my_time);
timeinfo = localtime (&my_time);
CCLog("year->%d",timeinfo->tm_year+1900);
CCLog("month->%d",timeinfo->tm_mon+1);
CCLog("date->%d",timeinfo->tm_mday);
CCLog("hour->%d",timeinfo->tm_hour);
CCLog("minutes->%d",timeinfo->tm_min);
CCLog("seconds->%d",timeinfo->tm_sec);

What is the recommended way to delete a large number of items from DynamoDB?

According to the DynamoDB documentation you could just delete the full table.

See below:

"Deleting an entire table is significantly more efficient than removing items one-by-one, which essentially doubles the write throughput as you do as many delete operations as put operations"

If you wish to delete only a subset of your data, then you could make separate tables for each month, year or similar. This way you could remove "last month" and keep the rest of your data intact.

This is how you delete a table in Java using the AWS SDK:

DeleteTableRequest deleteTableRequest = new DeleteTableRequest()
  .withTableName(tableName);
DeleteTableResult result = client.deleteTable(deleteTableRequest);

How to toggle boolean state of react component?

Since nobody posted this, I am posting the correct answer. If your new state update depends on the previous state, always use the functional form of setState which accepts as argument a function that returns a new state.

In your case:

this.setState(prevState => ({
  check: !prevState.check
}));

See docs


Since this answer is becoming popular, adding the approach that should be used for React Hooks (v16.8+):

If you are using the useState hook, then use the following code (in case your new state depends on the previous state):

const [check, setCheck] = useState(false);
// ...
setCheck(prevCheck => !prevCheck);

Show default value in Spinner in android

Spinner sp = (Spinner)findViewById(R.id.spinner); 
sp.setSelection(pos);

here pos is integer (your array item position)

array is like below then pos = 0;

String str[] = new String{"Select Gender","male", "female" };

then in onItemSelected

@Override
    public void onItemSelected(AdapterView<?> main, View view, int position,
            long Id) {

        if(position > 0){
          // get spinner value
        }else{
          // show toast select gender
        }

    }

Show div on scrollDown after 800px

You can also, do this.

$(window).on("scroll", function () {
   if ($(this).scrollTop() > 800) {
      #code here
   } else {
      #code here
   }
});

Change route params without reloading in Angular 2

You could use location.go(url) which will basically change your url, without change in route of application.

NOTE this could cause other effect like redirect to child route from the current route.

Related question which describes location.go will not intimate to Router to happen changes.

When to use std::size_t?

size_t is a very readable way to specify the size dimension of an item - length of a string, amount of bytes a pointer takes, etc. It's also portable across platforms - you'll find that 64bit and 32bit both behave nicely with system functions and size_t - something that unsigned int might not do (e.g. when should you use unsigned long

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

A comparison between the different Visual Studio Express editions can be found at Visual Studio Express (archive.org link). The difference between Windows and Windows Desktop is that with the Windows edition you can build Windows Store Apps (using .NET, WPF/XAML) while the Windows Desktop edition allows you to write classic Windows Desktop applications. It is possible to install both products on the same machine.

Visual Studio Express 2010 allows you to build Windows Desktop applications. Writing Windows Store applications is not possible with this product.

For learning I would suggest Notepad and the command line. While an IDE provides significant productivity enhancements to professionals, it can be intimidating to a beginner. If you want to use an IDE nevertheless I would recommend Visual Studio Express 2013 for Windows Desktop.


Update 2015-07-27: In addition to the Express Editions, Microsoft now offers Community Editions. These are still free for individual developers, open source contributors, and small teams. There are no Web, Windows, and Windows Desktop releases anymore either; the Community Edition can be used to develop any app type. In addition, the Community Edition does support (3rd party) Add-ins. The Community Edition offers the same functionality as the commercial Professional Edition.