Programs & Examples On #Encode

to convert some data (e.g. string, picture) to some representation (e.g. bytes, electrical signals)

What is base 64 encoding used for?

In the early days of computers, when telephone line inter-system communication was not particularly reliable, a quick & dirty method of verifying data integrity was used: "bit parity". In this method, every byte transmitted would have 7-bits of data, and the 8th would be 1 or 0, to force the total number of 1 bits in the byte to be even.

Hence 0x01 would be transmited as 0x81; 0x02 would be 0x82; 0x03 would remain 0x03 etc.

To further this system, when the ASCII character set was defined, only 00-7F were assigned characters. (Still today, all characters set in the range 80-FF are non-standard)

Many routers of the day put the parity check and byte translation into hardware, forcing the computers attached to them to deal strictly with 7-bit data. This force email attachments (and all other data, which is why HTTP & SMTP protocols are text-based), to be convert into a text-only format.

Few of the routers survived into the 90s. I severely doubt any of them are in use today.

PHP "pretty print" json_encode

PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).

This should do the job:

$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);

See http://www.php.net/manual/en/function.json-encode.php

Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)

How to HTML encode/escape a string? Is there a built-in?

You can use either h() or html_escape(), but most people use h() by convention. h() is short for html_escape() in rails.

In your controller:

@stuff = "<b>Hello World!</b>"

In your view:

<%=h @stuff %>

If you view the HTML source: you will see the output without actually bolding the data. I.e. it is encoded as &lt;b&gt;Hello World!&lt;/b&gt;.

It will appear an be displayed as <b>Hello World!</b>

Write Base64-encoded image to file

With Java 8's Base64 API

byte[] decodedImg = Base64.getDecoder()
                    .decode(encodedImg.getBytes(StandardCharsets.UTF_8));
Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
Files.write(destinationFile, decodedImg);

If your encoded image starts with something like data:image/png;base64,iVBORw0..., you'll have to remove the part. See this answer for an easy way to do that.

C# Base64 String to JPEG Image

So with the code you have provided.

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

Convert int to ASCII and back in Python

If multiple characters are bound inside a single integer/long, as was my issue:

s = '0123456789'
nchars = len(s)
# string to int or long. Type depends on nchars
x = sum(ord(s[byte])<<8*(nchars-byte-1) for byte in range(nchars))
# int or long to string
''.join(chr((x>>8*(nchars-byte-1))&0xFF) for byte in range(nchars))

Yields '0123456789' and x = 227581098929683594426425L

How to convert a string or integer to binary in Ruby?

I am almost a decade late but if someone still come here and want to find the code without using inbuilt function like to_S then I might be helpful.

find the binary

def find_binary(number)
  binary = []  
  until(number == 0)
    binary << number%2
    number = number/2
  end
  puts binary.reverse.join
end

Base64 Java encode and decode a string

The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries

Java 11 and up

import java.util.Base64;

public class Base64Encoding {

    public static void main(String[] args) {
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        String str = "77+9x6s=";

        // encode data using BASE64
        String encoded = enc.encodeToString(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data
        String decoded = new String(dec.decode(encoded));
        System.out.println("decoded value is \t" + decoded);
        System.out.println("original value is \t" + str);
    }
}

Java 6 - 10

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

public class EncodeString64 {
    public static void main(String[] args) throws UnsupportedEncodingException {

        String str = "77+9x6s=";
        // encode data using BASE64
        String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data 
        String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
        System.out.println("decoded value is \t" + decoded);

        System.out.println("original value is \t" + str);
    }
}

The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.

Encode URL in JavaScript?

The best answer is to use encodeURIComponent on values in the query string (and nowhere else).

However, I find that many APIs want to replace " " with "+" so I've had to use the following:

const value = encodeURIComponent(value).replace('%20','+');
const url = 'http://example.com?lang=en&key=' + value

escape is implemented differently in different browsers and encodeURI doesn't encode many characters (like # and even /) -- it's made to be used on a full URI/URL without breaking it – which isn't super helpful or secure.

And as @Jochem points out below, you may want to use encodeURIComponent() on a (each) folder name, but for whatever reason these APIs don't seem to want + in folder names so plain old encodeURIComponent works great.

Example:

const escapedValue = encodeURIComponent(value).replace('%20','+');
const escapedFolder = encodeURIComponent('My Folder'); // no replace
const url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`;

Python Unicode Encode Error

Likely, your problem is that you parsed it okay, and now you're trying to print the contents of the XML and you can't because theres some foreign Unicode characters. Try to encode your unicode string as ascii first:

unicodeData.encode('ascii', 'ignore')

the 'ignore' part will tell it to just skip those characters. From the python docs:

>>> # Python 2: u = unichr(40960) + u'abcd' + unichr(1972)
>>> u = chr(40960) + u'abcd' + chr(1972)
>>> u.encode('utf-8')
'\xea\x80\x80abcd\xde\xb4'
>>> u.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128)
>>> u.encode('ascii', 'ignore')
'abcd'
>>> u.encode('ascii', 'replace')
'?abcd?'
>>> u.encode('ascii', 'xmlcharrefreplace')
'&#40960;abcd&#1972;'

You might want to read this article: http://www.joelonsoftware.com/articles/Unicode.html, which I found very useful as a basic tutorial on what's going on. After the read, you'll stop feeling like you're just guessing what commands to use (or at least that happened to me).

AJAX POST and Plus Sign ( + ) -- How to Encode?

To make it more interesting and to hopefully enable less hair pulling for someone else. Using python, built dictionary for a device which we can use curl to configure.

Problem: {"timezone":"+5"} //throws an error " 5"

Solution: {"timezone":"%2B"+"5"} //Works

So, in a nutshell:

var = {"timezone":"%2B"+"5"}
json = JSONEncoder().encode(var)
subprocess.call(["curl",ipaddress,"-XPUT","-d","data="+json])

Thanks to this post!

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you are using Windows command line to print the data, you should use

chcp 65001

This worked for me!

How to get current location in Android

First you need to define a LocationListener to handle location changes.

private final LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(final Location location) {
        //your code here
    }
};

Then get the LocationManager and ask for location updates

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);
}

And finally make sure that you have added the permission on the Manifest,

For using only network based location use this one

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

For GPS based location, this one

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

How to set the default value of an attribute on a Laravel model

You can set Default attribute in Model also>

protected $attributes = [
        'status' => self::STATUS_UNCONFIRMED,
        'role_id' => self::ROLE_PUBLISHER,
    ];

You can find the details in these links

1.) How to set a default attribute value for a Laravel / Eloquent model?

2.) https://laracasts.com/index.php/discuss/channels/eloquent/eloquent-help-generating-attribute-values-before-creating-record


You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators

2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators

3.) Universal accessors and mutators in Laravel 4

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

how to change the default positioning of modal in bootstrap?

If you need to change the bottom position of the modal, you need to modify the max-height of the modal-body:

.modal-body {
  max-height: 75vh;
}

As other answers have said, you can adjust the right and top on the modal-dialog :

.modal-dialog {
  top: 10vh;
  right: 5vw;
}
  • "vh" means "% of view height"
  • "vw" means "% of view width"

Why is Thread.Sleep so harmful

I have a use case that I don't quite see covered here, and will argue that this is a valid reason to use Thread.Sleep():

In a console application running cleanup jobs, I need to make a large amount of fairly expensive database calls, to a DB shared by thousands of concurrent users. In order to not hammer the DB and exclude others for hours, I'll need a pause between calls, in the order of 100 ms. This is not related to timing, just to yielding access to the DB for other threads.

Spending 2000-8000 cycles on context switching between calls that may take 500 ms to execute is benign, as does having 1 MB of stack for the thread, which runs as a single instance on a server.

How to insert values into the database table using VBA in MS access

since you mentioned you are quite new to access, i had to invite you to first remove the errors in the code (the incomplete for loop and the SQL statement). Otherwise, you surely need the for loop to insert dates in a certain range.

Now, please use the code below to insert the date values into your table. I have tested the code and it works. You can try it too. After that, add your for loop to suit your scenario

Dim StrSQL As String
Dim InDate As Date
Dim DatDiff As Integer

InDate = Me.FromDateTxt

StrSQL = "INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );"

DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True

Java SSLHandshakeException "no cipher suites in common"

It looks like you are trying to connect using TLSv1.2, which isn't widely implemented on servers. Does your destination support tls1.2?

How to reset the state of a Redux store?

UPDATE NGRX4

If you are migrating to NGRX 4, you may have noticed from the migration guide that the rootreducer method for combining your reducers has been replaced with ActionReducerMap method. At first, this new way of doing things might make resetting state a challenge. It is actually straight-forward, yet the way of doing this has changed.

This solution is inspired by the meta-reducers API section of the NGRX4 Github docs.

First, lets say your are combining your reducers like this using NGRX's new ActionReducerMap option:

//index.reducer.ts
export const reducers: ActionReducerMap<State> = {
    auth: fromAuth.reducer,
    layout: fromLayout.reducer,
    users: fromUsers.reducer,
    networks: fromNetworks.reducer,
    routingDisplay: fromRoutingDisplay.reducer,
    routing: fromRouting.reducer,
    routes: fromRoutes.reducer,
    routesFilter: fromRoutesFilter.reducer,
    params: fromParams.reducer
}

Now, lets say you want to reset state from within app.module `

//app.module.ts
import { IndexReducer } from './index.reducer';
import { StoreModule, ActionReducer, MetaReducer } from '@ngrx/store';
...
export function debug(reducer: ActionReducer<any>): ActionReducer<any> {
    return function(state, action) {

      switch (action.type) {
          case fromAuth.LOGOUT:
            console.log("logout action");
            state = undefined;
      }

      return reducer(state, action);
    }
  }

  export const metaReducers: MetaReducer<any>[] = [debug];

  @NgModule({
    imports: [
        ...
        StoreModule.forRoot(reducers, { metaReducers}),
        ...
    ]
})

export class AppModule { }

`

And that is basically one way to achieve the same affect with NGRX 4.

Java: Get first item from a collection

Guava provides an onlyElement Collector, but only use it if you expect the collection to have exactly one element.

Collection<String> stringCollection = ...;
String string = collection.stream().collect(MoreCollectors.onlyElement())

If you are unsure of how many elements there are, use findFirst.

Optional<String> optionalString = collection.stream().findFirst();

Reading file using relative path in python project

I was thundered when the following code worked.

import os

for file in os.listdir("../FutureBookList"):
    if file.endswith(".adoc"):
        filename, file_extension = os.path.splitext(file)
        print(filename)
        print(file_extension)
        continue
    else:
        continue

So, I checked the documentation and it says:

Changed in version 3.6: Accepts a path-like object.

path-like object:

An object representing a file system path. A path-like object is either a str or...

I did a little more digging and the following also works:

with open("../FutureBookList/file.txt") as file:
   data = file.read()

What is the difference between utf8mb4 and utf8 charsets in MySQL?

MySQL added this utf8mb4 code after 5.5.3, Mb4 is the most bytes 4 meaning, specifically designed to be compatible with four-byte Unicode. Fortunately, UTF8MB4 is a superset of UTF8, except that there is no need to convert the encoding to UTF8MB4. Of course, in order to save space, the general use of UTF8 is enough.

The original UTF-8 format uses one to six bytes and can encode 31 characters maximum. The latest UTF-8 specification uses only one to four bytes and can encode up to 21 bits, just to represent all 17 Unicode planes. UTF8 is a character set in Mysql that supports only a maximum of three bytes of UTF-8 characters, which is the basic multi-text plane in Unicode.

To save 4-byte-long UTF-8 characters in Mysql, you need to use the UTF8MB4 character set, but only 5.5. After 3 versions are supported (View version: Select version ();). I think that in order to get better compatibility, you should always use UTF8MB4 instead of UTF8. For char type data, UTF8MB4 consumes more space and, according to Mysql's official recommendation, uses VARCHAR instead of char.

In MariaDB utf8mb4 as the default CHARSET when it not set explicitly in the server config, hence COLLATE utf8mb4_unicode_ci is used.

Refer MariaDB CHARSET & COLLATE Click

CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CSS Cell Margin

Following Cian's solution of setting a border in place of a margin, I discovered you can set border color to transparent to avoid having to color match the background. Works in FF17, IE9, Chrome v23. Seems like a decent solution provided you don't also need an actual border.

How do I align a label and a textarea?

Just wrap the textarea with the label and set the textarea style to

vertical-align: middle;

Here is some magic for all textareas on the page:)

<style>
    label textarea{
        vertical-align: middle;
    }
</style>

<label>Blah blah blah Description: <textarea>dura bura</textarea></label>

No input file specified

The No input file specified is a message you are presented with because of the implementation of PHP on your server, which in this case indicates a CGI implementation (can be verified with phpinfo()).

Now, to properly explain this, you need to have some basic understanding on how your system works with URL's. Based on your .htaccess file, it seems that your CMS expects the URL to passed along as a PATH_INFO variable. CGI and FastCGI implementations do not have PATH_INFO available, so when trying to pass the URI along, PHP fails with that message.

We need to find an alternative.

One option is to try and fix this. Looking into the documentation for core php.ini directives you can see that you can change the workings for your implementation. Although, GoDaddy probably won't allow you to change PHP settings on a shared enviroment.

We need to find an alternative to modifying PHP settings
Looking into system/uri.php on line 40, you will see that the CMS attempts two types of URI detection - the first being PATH_INFO, which we just learned won't work - the other being the REQUEST_URI.

This should basically, be enough - but the parsing of the URI passed, will cause you more trouble, as the URI, which you could pass to REQUEST_URI variable, forces parse_url() to only return the URL path - which basically puts you back to zero.

Now, there's actually only one possibilty left - and that's changing the core of the CMS. The URI detection part is insufficient.

Add QUERY_STRING to the array on line 40 as the first element in system/uri.php and change your .htaccess to look like this:

RewriteEngine On 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule ^(.*)$ index.php?/$1 [L]

This will pass the URI you request to index.php as QUERY_STRING and have the URI detection to find it.

This, on the other hand, makes it impossible to update the CMS without changing core files till this have been fixed. That sucks...

Need a better option?
Find a better CMS.

List comprehension vs map

Actually, map and list comprehensions behave quite differently in the Python 3 language. Take a look at the following Python 3 program:

def square(x):
    return x*x
squares = map(square, [1, 2, 3])
print(list(squares))
print(list(squares))

You might expect it to print the line "[1, 4, 9]" twice, but instead it prints "[1, 4, 9]" followed by "[]". The first time you look at squares it seems to behave as a sequence of three elements, but the second time as an empty one.

In the Python 2 language map returns a plain old list, just like list comprehensions do in both languages. The crux is that the return value of map in Python 3 (and imap in Python 2) is not a list - it's an iterator!

The elements are consumed when you iterate over an iterator unlike when you iterate over a list. This is why squares looks empty in the last print(list(squares)) line.

To summarize:

  • When dealing with iterators you have to remember that they are stateful and that they mutate as you traverse them.
  • Lists are more predictable since they only change when you explicitly mutate them; they are containers.
  • And a bonus: numbers, strings, and tuples are even more predictable since they cannot change at all; they are values.

For-loop vs while loop in R

Because 1 is numeric, but not integer (i.e. it's a floating point number), and 1:6000 is numeric and integer.

> print(class(1))
[1] "numeric"
> print(class(1:60000))
[1] "integer"

60000 squared is 3.6 billion, which is NOT representable in signed 32-bit integer, hence you get an overflow error:

> as.integer(60000)*as.integer(60000)
[1] NA
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow

3.6 billion is easily representable in floating point, however:

> as.single(60000)*as.single(60000)
[1] 3.6e+09

To fix your for code, convert to a floating point representation:

function (N)
{
    for(i in as.single(1:N)) {
        y <- i*i
    }
}

Checking if a variable is initialized

With C++-11 or Boost libs you could consider storing the variable using smart pointers. Consider this MVE where toString() behaviour depends on bar being initialized or not:

#include <memory>
#include <sstream>

class Foo {

private:
    std::shared_ptr<int> bar;

public:
    Foo() {}
    void setBar(int bar) {
        this->bar = std::make_shared<int>(bar);
    }
    std::string toString() const {
        std::ostringstream ss;
        if (bar)           // bar was set
            ss << *bar;
        else               // bar was never set
            ss << "unset";
        return ss.str();
    }
};

Using this code

Foo f;
std::cout << f.toString() << std::endl;
f.setBar(42);
std::cout << f.toString() << std::endl;

produces the output

unset
42

How do I format currencies in a Vue component?

I used the custom filter solution proposed by @Jess but in my project we are using Vue together with TypeScript. This is how it looks like with TypeScript and class decorators:

import Component from 'vue-class-component';
import { Filter } from 'vue-class-decorator';

@Component
export default class Home extends Vue {

  @Filter('toCurrency')
  private toCurrency(value: number): string {
    if (isNaN(value)) {
        return '';
    }

    var formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 0
    });
    return formatter.format(value);
  }
}

In this example the filter can only be used inside the component. I haven't tried to implement it as a global filter, yet.

How to insert array of data into mysql using php

First of all you should stop using mysql_*. MySQL supports multiple inserting like

INSERT INTO example
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

You just have to build one string in your foreach loop which looks like that

$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";

and then insert it after the loop

$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;

Another way would be Prepared Statements, which are even more suited for your situation.

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

No server in windows>preferences

I had the same issue. I was using eclipse platform and server was missing in my show view. To fix this go:

  • help>install new software

  • in work with : select : "Indigo Update Site - http://download.eclipse.org/releases/indigo/" , once selected, all available software will be displayed in the section under type filter text

  • Expand “Web, XML, and Java EE Development” and select "JST Server adapters extensions"

  • then click next and finish. The server should be displayed in show view

Pandas dataframe fillna() only some columns in place

You can using dict , fillna with different value for different column

df.fillna({'a':0,'b':0})
Out[829]: 
     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

After assign it back

df=df.fillna({'a':0,'b':0})
df
Out[831]: 
     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

React Native android build failed. SDK location not found

Delete the local.properties from the android folder in your react project and try it.

I've done this and succeeded.

How to subtract date/time in JavaScript?

You can use getTime() method to convert the Date to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date with setTime(). See here an example.

What is the right way to debug in iPython notebook?

Your return function is in line of def function(main function), you must give one tab to it. And Use

%%debug 

instead of

%debug 

to debug the whole cell not only line. Hope, maybe this will help you.

Python Function to test ping

Here is a simplified function that returns a boolean and has no output pushed to stdout:

import subprocess, platform
def pingOk(sHost):
    try:
        output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)

    except Exception, e:
        return False

    return True

Get the position of a spinner in Android

The way to get the selection of the spinner is:

  spinner1.getSelectedItemPosition();

Documentation reference: http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()

However, in your code, the one place you are referencing it is within your setOnItemSelectedListener(). It is not necessary to poll the spinner, because the onItemSelected method gets passed the position as the "position" variable.

So you could change that line to:

TestProjectActivity.this.number = position + 1;

If that does not fix the problem, please post the error message generated when your app crashes.

Convert String to Type in C#

If you really want to get the type by name you may use the following:

System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");

Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.

Request string without GET arguments

You can use $_GET for url params, or $_POST for post params, but the $_REQUEST contains the parameters from $_GET $_POST and $_COOKIE, if you want to hide the URI parameter from the user you can convert it to a session variable like so:

<?php

session_start();
if (isset($_REQUEST['param']) && !isset($_SESSION['param'])) {

    // Store all parameters received
    $_SESSION['param'] = $_REQUEST['param'];

    // Redirect without URI parameters
    header('Location: /file.php');
    exit;
}
?>
<html>
<body>
<?php
  echo $_SESSION['param'];
?>
</body>
</html>

EDIT

use $_SERVER['PHP_SELF'] to get the current file name or $_SERVER['REQUEST_URI'] to get the requested URI

C++ - how to find the length of an integer

There is a much better way to do it

    #include<cmath>
    ...
    int size = trunc(log10(num)) + 1
....

works for int and decimal

Write to custom log file from a Bash script

@chepner make a good point that logger is dedicated to logging messages.

I do need to mention that @Thomas Haratyk simply inquired why I didn't simply use echo.

At the time, I didn't know about echo, as I'm learning shell-scripting, but he was right.

My simple solution is now this:

#!/bin/bash
echo "This logs to where I want, but using echo" > /var/log/mycustomlog

The example above will overwrite the file after the >

So, I can append to that file with this:

#!/bin/bash
echo "I will just append to my custom log file" >> /var/log/customlog

Thanks guys!

  • on a side note, it's simply my personal preference to keep my personal logs in /var/log/, but I'm sure there are other good ideas out there. And since I didn't create a daemon, /var/log/ probably isn't the best place for my custom log file. (just saying)

Reading the selected value from asp:RadioButtonList using jQuery

Try this:

$("input[name='<%=RadioButtonList1.UniqueID %>']:checked").val()

How to remove trailing and leading whitespace for user-provided input in a batch file?

The solution below works very well for me.

Only 4 lines and works with most (all?) characters.


Solution:

:Trim
SetLocal EnableDelayedExpansion
set Params=%*
for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b
exit /b

Test:

@echo off

call :Test1 & call :Test2 & call :Test3 & exit /b

:Trim
SetLocal EnableDelayedExpansion
set Params=%*
for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b
exit /b

:Test1
set Value=   a b c   
set Expected=a b c
call :Trim Actual %Value%
if "%Expected%" == "%Actual%" (echo Test1 passed) else (echo Test1 failed)
exit /b

:Test2
SetLocal EnableDelayedExpansion
set Value=   a \ / : * ? " ' < > | ` ~ @ # $ [ ] & ( ) + - _ = z    
set Expected=a \ / : * ? " ' < > | ` ~ @ # $ [ ] & ( ) + - _ = z
call :Trim Actual !Value!
if !Expected! == !Actual! (echo Test2 passed) else (echo Test2 failed)
exit /b

:Test3
set /p Value="Enter string to trim: " %=%
echo Before: [%Value%]
call :Trim Value %Value%
echo After : [%Value%]
exit /b

Disable Scrolling on Body

Set height and overflow:

html, body {margin: 0; height: 100%; overflow: hidden}

http://jsfiddle.net/q99hvawt/

Get java.nio.file.Path object from java.io.File

Yes, you can get it from the File object by using File.toPath(). Keep in mind that this is only for Java 7+. Java versions 6 and below do not have it.

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

How to add a footer to the UITableView?

These samples work well. You can check section and then return a height to show or hide section. Don't forget to extend your viewcontroller from UITableViewDelegate.

Objective-C

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0)
    {
        // to hide footer for section 0 
        return 0.0;
    }
    else
    {
        // show footer for every section except section 0 
        return HEIGHT_YOU_WANT;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = [UIColor blackColor];
    return footerView;
}

Swift

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView()
    footerView.backgroundColor = UIColor.black
    return footerView
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    if section == 0 {
        // to hide footer for section 0
        return 0.0
    } else {
        // show footer for every section except section 0
        return HEIGHT_YOU_WANT
    }
}

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

how to display employee names starting with a and then b in sql

select * 
from stores 
where name like 'a%' or 
name like 'b%' 
order by name

SQLite Query in Android to count rows

See rawQuery(String, String[]) and the documentation for Cursor

Your DADABASE_COMPARE SQL statement is currently invalid, loginname and loginpass won't be escaped, there is no space between loginname and the and, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as

select count(*) from users where uname=boband pwd=password);

Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.

To use selectionArgs you would do something like

final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";

private void someMethod() {
    Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
    ...
}

Chrome: Uncaught SyntaxError: Unexpected end of input

I get this error when I have ommitted a closing brace character (})in JavaScript code. Check that your braces are properly balanced.

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

Stop a gif animation onload, on mouseover start the activation

css filter can stop gif from playing in chrome

just add

filter: blur(0.001px);

to your img tag then gif freezed to load via chrome performance concern :)

What's the best way to check if a file exists in C?

I think that access() function, which is found in unistd.h is a good choice for Linux (you can use stat too).

You can Use it like this:

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

void fileCheck(const char *fileName);

int main (void) {
    char *fileName = "/etc/sudoers";

    fileCheck(fileName);
    return 0;
}

void fileCheck(const char *fileName){

    if(!access(fileName, F_OK )){
        printf("The File %s\t was Found\n",fileName);
    }else{
        printf("The File %s\t not Found\n",fileName);
    }

    if(!access(fileName, R_OK )){
        printf("The File %s\t can be read\n",fileName);
    }else{
        printf("The File %s\t cannot be read\n",fileName);
    }

    if(!access( fileName, W_OK )){
        printf("The File %s\t it can be Edited\n",fileName);
    }else{
        printf("The File %s\t it cannot be Edited\n",fileName);
    }

    if(!access( fileName, X_OK )){
        printf("The File %s\t is an Executable\n",fileName);
    }else{
        printf("The File %s\t is not an Executable\n",fileName);
    }
}

And you get the following Output:

The File /etc/sudoers    was Found
The File /etc/sudoers    cannot be read
The File /etc/sudoers    it cannot be Edited
The File /etc/sudoers    is not an Executable

Android Studio : unmappable character for encoding UTF-8

In Android Studio resolved it by

  1. Navigate to File > Editor > File Encodings.
  2. In global encoding set the encoding to ISO-8859-1
  3. In Project encoding set the encoding to UTF-8 and the same case to Default encoding for properties files.
  4. Rebuild project.

proper way to logout from a session in PHP

From the session_destroy() page in the PHP manual:

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

After installing Free BitDefender AntiVirus the services related to the AntiVirus used about 80 MB of my computer's Memory. I also noticed that after installing BitDefender the service related to windows Presentation Font Cache was also installed: "WPFFontCache_v0300.exe". I disabled the service from stating automatically and now BitDefender Free AntiVirus use only 15-20 MB (!!!) of my computer's Memory! As far as I concern, this service affected negatively the memory usage of my PC inother services. I recommend you to disable it.

Nullable type as a generic parameter possible?

The shorter way :

public static T ValueOrDefault<T>(this DataRow reader, string columnName) => 
        reader.IsNull(columnName) ? default : (T) reader[columnName];

return 0 for int, and null for int?

iOS: how to perform a HTTP POST request?

Here is how POST HTTP request works for iOS 8+ using NSURLSession:

- (void)call_PostNetworkingAPI:(NSURL *)url withCompletionBlock:(void(^)(id object,NSError *error,NSURLResponse *response))completion
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    config.URLCache = nil;
    config.timeoutIntervalForRequest = 5.0f;
    config.timeoutIntervalForResource =10.0f;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
    NSMutableURLRequest *Req=[NSMutableURLRequest requestWithURL:url];
    [Req setHTTPMethod:@"POST"];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:Req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {

            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            if (dict != nil) {
                completion(dict,error,response);
            }
        }else
        {
            completion(nil,error,response);
        }
    }];
    [task resume];

}

Hope this will satisfy your following requirement.

How to use WinForms progress bar?

Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

public void DoWork(IProgress<int> progress)
{
    // This method is executed in the context of
    // another thread (different than the main UI thread),
    // so use only thread-safe code
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);

        // Use progress to notify UI thread that progress has
        // changed
        if (progress != null)
            progress.Report((j + 1) * 100 / 100000);
    }
}

private async void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;

    var progress = new Progress<int>(v =>
    {
        // This lambda is executed in context of UI thread,
        // so it can safely update form controls
        progressBar1.Value = v;
    });

    // Run operation in another thread
    await Task.Run(() => DoWork(progress));

    // TODO: Do something after all calculations
}

Tasks are currently the preferred way to implement what BackgroundWorker does.

Tasks and Progress are explained in more detail here:

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

I feel the performance characteristics change from one DBMS to another. It's all on how they choose to implement it. Since I have worked extensively on Oracle, I'll tell from that perspective.

COUNT(*) - Fetches entire row into result set before passing on to the count function, count function will aggregate 1 if the row is not null

COUNT(1) - Will not fetch any row, instead count is called with a constant value of 1 for each row in the table when the WHERE matches.

COUNT(PK) - The PK in Oracle is indexed. This means Oracle has to read only the index. Normally one row in the index B+ tree is many times smaller than the actual row. So considering the disk IOPS rate, Oracle can fetch many times more rows from Index with a single block transfer as compared to entire row. This leads to higher throughput of the query.

From this you can see the first count is the slowest and the last count is the fastest in Oracle.

How do I use ROW_NUMBER()?

SELECT num, UserName FROM 
 (SELECT UserName, ROW_NUMBER() OVER(ORDER BY UserId) AS num
  From Users) AS numbered
WHERE UserName='Joe'

animating addClass/removeClass with jQuery

Although, the question is fairly old, I'm adding info not present in other answers.

The OP is using stop() to stop the current animation as soon as the event completes. However, using the right mix of parameters with the function should help. eg. stop(true,true) or stop(true,false) as this affects the queued animations well.

The following link illustrates a demo that shows the different parameters available with stop() and how they differ from finish().

http://api.jquery.com/finish/

Although the OP had no issues using JqueryUI, this is for other users who may come across similar scenarios but cannot use JqueryUI/need to support IE7 and 8 too.

Reverse order of foreach list items

If you don't mind destroying the array (or a temp copy of it) you can do:

$stack = array("orange", "banana", "apple", "raspberry");

while ($fruit = array_pop($stack)){
    echo $fruit . "\n<br>"; 
}

produces:

raspberry 
apple 
banana 
orange 

I think this solution reads cleaner than fiddling with an index and you are less likely to introduce index handling mistakes, but the problem with it is that your code will likely take slightly longer to run if you have to create a temporary copy of the array first. Fiddling with an index is likely to run faster, and it may also come in handy if you actually need to reference the index, as in:

$stack = array("orange", "banana", "apple", "raspberry");
$index = count($stack) - 1;
while($index > -1){
    echo $stack[$index] ." is in position ". $index . "\n<br>";
    $index--;
} 

But as you can see, you have to be very careful with the index...

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Did you update the project (right-click on the project, "Maven" > "Update project...")? Otherwise, you need to check if pom.xml contains the necessary slf4j dependencies, e.g.:

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
    </dependency>

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

My solution uses positioning to get wrapped lines automatically line up correctly. So you don't have to worry about setting padding-right on the li:before.

_x000D_
_x000D_
ul {_x000D_
  margin-left: 0;_x000D_
  padding-left: 0;_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
  position: relative;_x000D_
  margin-left: 1em;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  position: absolute;_x000D_
  left: -1em;_x000D_
  content: "+";_x000D_
}
_x000D_
<ul>_x000D_
  <li>Item 1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 2 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 3 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 4</li>_x000D_
  <li>Item 5</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Loading another html page from javascript

You can use the following code :

<!DOCTYPE html>
<html>
    <body onLoad="triggerJS();">

    <script>
        function triggerJS(){
        location.replace("http://www.google.com");
        /*
        location.assign("New_WebSite_Url");
        //Use assign() instead of replace if you want to have the first page in the history (i.e if you want the user to be able to navigate back when New_WebSite_Url is loaded)
        */
        }
    </script>

    </body>
</html>

Android notification is not showing

Notifications may not be shown if you show the notifications rapidly one after the other or cancel an existing one, then right away show it again (e.g. to trigger a heads-up-notification to notify the user about a change in an ongoing notification). In these cases the system may decide to just block the notification when it feels they might become too overwhelming/spammy for the user.

Please note, that at least on stock Android (tested with 10) from the outside this behavior looks a bit random: it just sometimes happens and sometimes it doesn't. My guess is, there is a very short time threshold during which you are not allowed to send too many notifications. Calling NotificationManager.cancel() and then NotificationManager.notify() might then sometimes cause this behavior.

If you have the option, when updating a notification don't cancel it before, but just call NotificationManager.notify() with the updated notification. This doesn't seem to trigger the aforementioned blocking by the system.

JS regex: replace all digits in string

find the numbers and then replaced with strings which specified. It is achieved by two methods

  1. Using a regular expression literal

  2. Using keyword RegExp object

Using a regular expression literal:

<script type="text/javascript">

var string = "my contact number is 9545554545. my age is 27.";
alert(string.replace(/\d+/g, "XXX"));

</script>

**Output:**my contact number is XXX. my age is XXX.

for more details:

http://www.infinetsoft.com/Post/How-to-replace-number-with-string-in-JavaScript/1156

How to set java.net.preferIPv4Stack=true at runtime?

well,

I used System.setProperty("java.net.preferIPv4Stack" , "true"); and it works from JAVA, but it doesn't work on JBOSS AS7.

Here is my work around solution,

Add the below line to the end of the file ${JBOSS_HOME}/bin/standalone.conf.bat (just after :JAVA_OPTS_SET )

set "JAVA_OPTS=%JAVA_OPTS% -Djava.net.preferIPv4Stack=true"

Note: restart JBoss server

Why cannot cast Integer to String in java?

For int types use:

int myInteger = 1;
String myString = Integer.toString(myInteger);

For Integer types use:

Integer myIntegerObject = new Integer(1);
String myString = myIntegerObject.toString();

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

Foreign keys work by joining a column to a unique key in another table, and that unique key must be defined as some form of unique index, be it the primary key, or some other unique index.

At the moment, the only unique index you have is a compound one on ISBN, Title which is your primary key.

There are a number of options open to you, depending on exactly what BookTitle holds and the relationship of the data within it.

I would hazard a guess that the ISBN is unique for each row in BookTitle. ON the assumption this is the case, then change your primary key to be only on ISBN, and change BookCopy so that instead of Title you have ISBN and join on that.

If you need to keep your primary key as ISBN, Title then you either need to store the ISBN in BookCopy as well as the Title, and foreign key on both columns, OR you need to create a unique index on BookTitle(Title) as a distinct index.

More generally, you need to make sure that the column or columns you have in your REFERENCES clause match exactly a unique index in the parent table: in your case it fails because you do not have a single unique index on Title alone.

How to focus on a form input text field on page load using jQuery?

The line $('#myTextBox').focus() alone won't put the cursor in the text box, instead use:

$('#myTextBox:text:visible:first').focus();

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

First off, if you're starting a new project, go with Entity Framework ("EF") - it now generates much better SQL (more like Linq to SQL does) and is easier to maintain and more powerful than Linq to SQL ("L2S"). As of the release of .NET 4.0, I consider Linq to SQL to be an obsolete technology. MS has been very open about not continuing L2S development further.

1) Performance

This is tricky to answer. For most single-entity operations (CRUD) you will find just about equivalent performance with all three technologies. You do have to know how EF and Linq to SQL work in order to use them to their fullest. For high-volume operations like polling queries, you may want to have EF/L2S "compile" your entity query such that the framework doesn't have to constantly regenerate the SQL, or you can run into scalability issues. (see edits)

For bulk updates where you're updating massive amounts of data, raw SQL or a stored procedure will always perform better than an ORM solution because you don't have to marshal the data over the wire to the ORM to perform updates.

2) Speed of Development

In most scenarios, EF will blow away naked SQL/stored procs when it comes to speed of development. The EF designer can update your model from your database as it changes (upon request), so you don't run into synchronization issues between your object code and your database code. The only time I would not consider using an ORM is when you're doing a reporting/dashboard type application where you aren't doing any updating, or when you're creating an application just to do raw data maintenance operations on a database.

3) Neat/Maintainable code

Hands down, EF beats SQL/sprocs. Because your relationships are modeled, joins in your code are relatively infrequent. The relationships of the entities are almost self-evident to the reader for most queries. Nothing is worse than having to go from tier to tier debugging or through multiple SQL/middle tier in order to understand what's actually happening to your data. EF brings your data model into your code in a very powerful way.

4) Flexibility

Stored procs and raw SQL are more "flexible". You can leverage sprocs and SQL to generate faster queries for the odd specific case, and you can leverage native DB functionality easier than you can with and ORM.

5) Overall

Don't get caught up in the false dichotomy of choosing an ORM vs using stored procedures. You can use both in the same application, and you probably should. Big bulk operations should go in stored procedures or SQL (which can actually be called by the EF), and EF should be used for your CRUD operations and most of your middle-tier's needs. Perhaps you'd choose to use SQL for writing your reports. I guess the moral of the story is the same as it's always been. Use the right tool for the job. But the skinny of it is, EF is very good nowadays (as of .NET 4.0). Spend some real time reading and understanding it in depth and you can create some amazing, high-performance apps with ease.

EDIT: EF 5 simplifies this part a bit with auto-compiled LINQ Queries, but for real high volume stuff, you'll definitely need to test and analyze what fits best for you in the real world.

Java 256-bit AES Password-Based Encryption

Generating your own key from a byte array is easy:

byte[] raw = ...; // 32 bytes in size for a 256 bit key
Key skey = new javax.crypto.spec.SecretKeySpec(raw, "AES");

But creating a 256-bit key isn't enough. If the key generator cannot generate 256-bit keys for you, then the Cipher class probably doesn't support AES 256-bit either. You say you have the unlimited jurisdiction patch installed, so the AES-256 cipher should be supported (but then 256-bit keys should be too, so this might be a configuration problem).

Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skey);
byte[] encrypted = cipher.doFinal(plainText.getBytes());

A workaround for lack of AES-256 support is to take some freely available implementation of AES-256, and use it as a custom provider. This involves creating your own Provider subclass and using it with Cipher.getInstance(String, Provider). But this can be an involved process.

Find the division remainder of a number

Use the % instead of the / when you divide. This will return the remainder for you. So in your case

26 % 7 = 5

How to handle change of checkbox using jQuery?

$('#myForm').on('change', 'input[type=checkbox]', function() {
    this.checked ? this.value = 'apple' : this.value = 'pineapple';
});

How to check user is "logged in"?

if (User.Identity.IsAuthenticated)
{
    Page.Title = "Home page for " + User.Identity.Name;
}
else
{
    Page.Title = "Home page for guest user.";
}

ModelState.IsValid == false, why?

Paste the below code in the ActionResult of your controller and place the debugger at this point.

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

Get current application physical path within Application_Start

System.AppDomain.CurrentDomain.BaseDirectory

This will give you the running directory of your application. This even works for web applications. Afterwards, you can reach your file.

Android: Changing Background-Color of the Activity (Main View)

Try this:

_x000D_
_x000D_
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"


</androidx.constraintlayout.widget.ConstraintLayout>
    />
_x000D_
_x000D_
_x000D_

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

If you are using Jersey for REST API's you can do as below

You don't have to change your webservices implementation.

I will explain for Jersey 2.x

1) First add a ResponseFilter as shown below

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;

public class CorsResponseFilter implements ContainerResponseFilter {

@Override
public void filter(ContainerRequestContext requestContext,   ContainerResponseContext responseContext)
    throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

  }
}

2) then in the web.xml , in the jersey servlet declaration add the below

    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>YOUR PACKAGE.CorsResponseFilter</param-value>
    </init-param>

Access POST values in Symfony2 request object

If you are newbie, welcome to Symfony2, an open-source project so if you want to learn a lot, you can open the source !

From "Form.php" :

getData() getNormData() getViewData()

You can find more details in this file.

gpg decryption fails with no secret key error

You can also sometimes get this error if you try to decrypt a secret while su-ed to a different user on a system with GPG 2.x installed. This bug has been reported against RHEL 6 but there is no fix available; apparently this is due to some design decisions in GPG 2.x. One workaround suggested in the bug report is to run the decryption inside of a tmux or screen session. More reading here.

Appending a line break to an output file in a shell script

Try

echo -en "`date` User `whoami` started the script.\n" >> output.log

Try issuing this multiple times. I hope you are looking for the same output.

Python DNS module import error

In my case, I hava writen the code in the file named "dns.py", it's conflict for the package, I have to rename the script filename.

Modifying a query string without reloading the page

Then the history API is exactly what you are looking for. If you wish to support legacy browsers as well, then look for a library that falls back on manipulating the URL's hash tag if the browser doesn't provide the history API.

How to print / echo environment variables?

This works too, with the semi-colon.

NAME=sam; echo $NAME

dynamic_cast and static_cast in C++

static_cast< Type* >(ptr)

static_cast in C++ can be used in scenarios where all type casting can be verified at compile time.

dynamic_cast< Type* >(ptr)

dynamic_cast in C++ can be used to perform type safe down casting. dynamic_cast is run time polymorphism. The dynamic_cast operator, which safely converts from a pointer (or reference) to a base type to a pointer (or reference) to a derived type.

eg 1:

#include <iostream>
using namespace std;

class A
{
public:
    virtual void f(){cout << "A::f()" << endl;}
};

class B : public A
{
public:
    void f(){cout << "B::f()" << endl;}
};

int main()
{
    A a;
    B b;
    a.f();        // A::f()
    b.f();        // B::f()

    A *pA = &a;   
    B *pB = &b;   
    pA->f();      // A::f()
    pB->f();      // B::f()

    pA = &b;
    // pB = &a;      // not allowed
    pB = dynamic_cast<B*>(&a); // allowed but it returns NULL

    return 0;
}

For more information click here

eg 2:

#include <iostream>

using namespace std;

class A {
public:
    virtual void print()const {cout << " A\n";}
};

class B {
public:
    virtual void print()const {cout << " B\n";}
};

class C: public A, public B {
public:
    void print()const {cout << " C\n";}
};


int main()
{

    A* a = new A;
    B* b = new B;
    C* c = new C;

    a -> print(); b -> print(); c -> print();
    b = dynamic_cast< B*>(a);  //fails
    if (b)  
       b -> print();  
    else 
       cout << "no B\n";
    a = c;
    a -> print(); //C prints
    b = dynamic_cast< B*>(a);  //succeeds
    if (b)
       b -> print();  
    else 
       cout << "no B\n";
}

C++ Matrix Class

You could use a template like :

#include <iostream>
using std::cerr;
using std::endl;

//qt4type
typedef unsigned int quint32;

template <typename T>
void deletep(T &) {}
template <typename T>
void deletep(T* & ptr) {
    delete ptr;
    ptr = 0;
}
template<typename T>
class Matrix {
    public:
        typedef T value_type;
        Matrix() : _cols(0), _rows(0), _data(new T[0]), auto_delete(true) {};
        Matrix(quint32 rows, quint32 cols, bool auto_del = true);

        bool exists(quint32 row, quint32 col) const;
        T & operator()(quint32 row, quint32 col);
        T operator()(quint32 row, quint32 col) const;
        virtual ~Matrix();

        int size() const { return _rows * _cols; }
        int rows() const { return _rows; }
        int cols() const { return _cols; }
    private:
        Matrix(const Matrix &);
        quint32 _rows, _cols;
        mutable T * _data;
        const bool auto_delete;
};
template<typename T>
Matrix<T>::Matrix(quint32 rows, quint32 cols, bool auto_del) : _rows(rows), _cols(cols), auto_delete(auto_del) {
    _data = new T[rows * cols];
}
template<typename T>
inline T & Matrix<T>::operator()(quint32 row, quint32 col) {
    return _data[_cols * row + col];
}
template<typename T>
inline T Matrix<T>::operator()(quint32 row, quint32 col) const {
    return _data[_cols * row + col];
}

template<typename T>
bool Matrix<T>::exists(quint32 row, quint32 col) const {
    return (row < _rows && col < _cols);
}

template<typename T>
Matrix<T>::~Matrix() {
    if(auto_delete){
        for(int i = 0, c = size(); i < c; ++i){
            //will do nothing if T isn't a pointer
            deletep(_data[i]);
        }
    }
    delete [] _data;
}

int main() {
    Matrix< int > m(10,10);
    quint32 i = 0;
    for(int x = 0; x < 10; ++x) {
        for(int y = 0; y < 10; ++y, ++i) {
            m(x, y) = i;
        }
    }
    for(int x = 0; x < 10; ++x) {
        for(int y = 0; y < 10; ++y) {
            cerr << "@(" << x << ", " << y << ") : " << m(x,y) << endl;
        }
    }
}

*edit, fixed a typo.

How do I replace text in a selection?

This frustrated the heck out of me, and none of the above answers really got me what I wanted. I finally found the answer I was looking for, on a mac if you do ? + option + F it will bring up a Find-Replace bar at the bottom of your editor which is local to the file you have open.

There is an icon option which when hovered over says "In Selection" that you can select to find and replace within a selection. I've pointed to the correct icon in the screenshot below.

enter image description here

Hit replace all, and voila, all instances of '0' will be replaced with '255'.

Note: this feature is ONLY available when you use ? + option + F.

It does NOT appear when you use ? + shift + F.

Note: this will replace all instances of '0' with '255'. If you wanted to replace 0 (without the quotes) with 255, then just put 0 (without quotes) and 255 in the Find What: and Replace With: fields respectively.

Note:

option key is also labeled as the alt key.

? key is also labeled as the command key.

Getting the thread ID from a thread

From managed code you have access to instances of the Thread type for each managed thread. Thread encapsulates the concept of an OS thread and as of the current CLR there's a one-to-one correspondance with managed threads and OS threads. However, this is an implementation detail, that may change in the future.

The ID displayed by Visual Studio is actually the OS thread ID. This is not the same as the managed thread ID as suggested by several replies.

The Thread type does include a private IntPtr member field called DONT_USE_InternalThread, which points to the underlying OS structure. However, as this is really an implementation detail it is not advisable to pursue this IMO. And the name sort of indicates that you shouldn't rely on this.

Unlink of file Failed. Should I try again?

I ran into this issue running git Bash and Eclipse EGit at the same time. Solution: close Eclipse. Also wouldn't hurt to run git gc as @khilo mentioned.

How to set a variable inside a loop for /F

Try this:

setlocal EnableDelayedExpansion

...

for /F "tokens=*" %%a in ('type %FileName%') do (
    set z=%%a
    echo !z!
    echo %%a
)

How to disable Google asking permission to regularly check installed apps on my phone?

On Android prior to 4.2, go to Google Settings, tap Verify apps and uncheck the option Verify apps.

On Android 4.2+, uncheck the option Settings > Security > Verify apps and/or Settings > Developer options > Verify apps over USB.

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

jQuery addClass onClick

Try to make your css more specific so that the new (green) style is more specific than the previous one, so that it worked for me!

For example, you might use in css:

button:active {/*your style here*/}

Instead of (probably not working):

.active {/*style*/} (.active is not a pseudo-class)

Hope it helps!

How to solve SyntaxError on autogenerated manage.py?

just you describe your python version

=> python3.5 manage.py runserver

(my python version=3.5)

VB.net: Date without time

FormatDateTime(Now, DateFormat.ShortDate)

How to maintain state after a page refresh in React.js?

So my solution was to also set localStorage when setting my state and then get the value from localStorage again inside of the getInitialState callback like so:

getInitialState: function() {
    var selectedOption = localStorage.getItem( 'SelectedOption' ) || 1;

    return {
        selectedOption: selectedOption
    };
},

setSelectedOption: function( option ) {
    localStorage.setItem( 'SelectedOption', option );
    this.setState( { selectedOption: option } );
}

I'm not sure if this can be considered an Anti-Pattern but it works unless there is a better solution.

Border Height on CSS

I have another possibility. This is of course a "newer" technique, but for my projects works sufficient.

It only works if you need one or two borders. I've never done it with 4 borders... and to be honest, I don't know the answer for that yet.

.your-item {
  position: relative;
}

.your-item:after {
  content: '';
  height: 100%; //You can change this if you want smaller/bigger borders
  width: 1px;

  position: absolute;
  right: 0;
  top: 0; // If you want to set a smaller height and center it, change this value

  background-color: #000000; // The color of your border
}

I hope this helps you too, as for me, this is an easy workaround.

Correct way to use Modernizr to detect IE?

I needed to detect IE vs most everything else and I didn't want to depend on the UA string. I found that using es6number with Modernizr did exactly what I wanted. I don't have much concern with this changing as I don't expect IE to ever support ES6 Number. So now I know the difference between any version of IE vs Edge/Chrome/Firefox/Opera/Safari.

More details here: http://caniuse.com/#feat=es6-number

Note that I'm not really concerned about Opera Mini false negatives. You might be.

In a unix shell, how to get yesterday's date into a variable?

Though all good answers, unfortunately none of them worked for me. So I had to write something old school. ( I was on a bare minimal Linux OS )

$ date -d @$( echo $(( $(date +%s)-$((60*60*24)) )) )

You can combine this with date's usual formatting. Eg.

$ date -d @$( echo $(( $(date +%s)-$((60*60*24)) )) ) +%Y-%m-%d

Explanation : Take date input in terms of epoc seconds ( the -d option ), from which you would have subtracted one day equivalent seconds. This will give the date precisely one day back.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

You need to enable CORS in your Web Api. The easier and preferred way to enable CORS globally is to add the following into web.config

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

Please note that the Methods are all individually specified, instead of using *. This is because there is a bug occurring when using *.

You can also enable CORS by code.

Update
The following NuGet package is required: Microsoft.AspNet.WebApi.Cors.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

        // ...
    }
}

Then you can use the [EnableCors] attribute on Actions or Controllers like this

[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]

Or you can register it globally

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("http://www.example.com", "*", "*");
        config.EnableCors(cors);

        // ...
    }
}

You also need to handle the preflight Options requests with HTTP OPTIONS requests.

Web API needs to respond to the Options request in order to confirm that it is indeed configured to support CORS.

To handle this, all you need to do is send an empty response back. You can do this inside your actions, or you can do it globally like this:

# Global.asax.cs
protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}

This extra check was added to ensure that old APIs that were designed to accept only GET and POST requests will not be exploited. Imagine sending a DELETE request to an API designed when this verb didn't exist. The outcome is unpredictable and the results might be dangerous.

jQuery DataTable overflow and text-wrapping issues

I settled for the limitation (to some people a benefit) of having my rows only one line of text high. The CSS to contain long strings then becomes:

.datatable td {
  overflow: hidden; /* this is what fixes the expansion */
  text-overflow: ellipsis; /* not supported in all browsers, but I accepted the tradeoff */
  white-space: nowrap;
}

[edit to add:] After using my own code and initially failing, I recognized a second requirement that might help people. The table itself needs to have a fixed layout or the cells will just keep trying to expand to accomodate contents no matter what. If DataTables styles or your own styles don't already do so, you need to set it:

table.someTableClass {
  table-layout: fixed
}

Now that text is truncated with ellipses, to actually "see" the text that is potentially hidden you can implement a tooltip plugin or a details button or something. But a quick and dirty solution is to use JavaScript to set each cell's title to be identical to its contents. I used jQuery, but you don't have to:

  $('.datatable tbody td').each(function(index){
    $this = $(this);
    var titleVal = $this.text();
    if (typeof titleVal === "string" && titleVal !== '') {
      $this.attr('title', titleVal);
    }
  });

DataTables also provides callbacks at the row and cell rendering levels, so you could provide logic to set the titles at that point instead of with a jQuery.each iterator. But if you have other listeners that modify cell text, you might just be better off hitting them with the jQuery.each at the end.

This entire truncation method will ALSO have a limitation you've indicated you're not a fan of: by default columns will have the same width. I identify columns that are going to be consistently wide or consistently narrow, and explicitly set a percentage-based width on them (you could do it in your markup or with sWidth). Any columns without an explicit width get even distribution of the remaining space.

That might seem like a lot of compromises, but the end result was worth it for me.

List files with certain extensions with ls and grep

In case you are still looking for an alternate solution:

ls | grep -i -e '\\.tcl$' -e '\\.exe$' -e '\\.mp4$'

Feel free to add more -e flags if needed.

How can I encode a string to Base64 in Swift?

You could just do a simple extension like:

import UIKit

// MARK: - Mixed string utils and helpers
extension String {


    /**
    Encode a String to Base64

    :returns: 
    */
    func toBase64()->String{

        let data = self.dataUsingEncoding(NSUTF8StringEncoding)

        return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

    }

}

iOS 7 and up

use jQuery's find() on JSON object

This works for me on [{"id":"data"},{"id":"data"}]

function getObjects(obj, key, val) 
{
    var newObj = false; 
    $.each(obj, function()
    {
        var testObject = this; 
        $.each(testObject, function(k,v)
        {
            //alert(k);
            if(val == v && k == key)
            {
                newObj = testObject;
            }
        });
    });

    return newObj;
}

Python: Converting from ISO-8859-1/latin1 to UTF-8

Try decoding it first, then encoding:

apple.decode('iso-8859-1').encode('utf8')

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

You can match those three groups separately, and make sure that they all present. Also, [^\w] seems a bit too broad, but if that's what you want you might want to replace it with \W.

How to remove specific session in asp.net?

you can use Session.Remove() method; Session.Remove

Session.Remove("yourSessionName");

How to get unique values in an array

You only need vanilla JS to find uniques with Array.some and Array.reduce. With ES2015 syntax it's only 62 characters.

a.reduce((c, v) => b.some(w => w === v) ? c : c.concat(v)), b)

Array.some and Array.reduce are supported in IE9+ and other browsers. Just change the fat arrow functions for regular functions to support in browsers that don't support ES2015 syntax.

var a = [1,2,3];
var b = [4,5,6];
// .reduce can return a subset or superset
var uniques = a.reduce(function(c, v){
    // .some stops on the first time the function returns true                
    return (b.some(function(w){ return w === v; }) ?  
      // if there's a match, return the array "c"
      c :     
      // if there's no match, then add to the end and return the entire array                                        
      c.concat(v)}),                                  
  // the second param in .reduce is the starting variable. This is will be "c" the first time it runs.
  b);                                                 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

How to mock static methods in c# using MOQ framework?

Moq (and other DynamicProxy-based mocking frameworks) are unable to mock anything that is not a virtual or abstract method.

Sealed/static classes/methods can only be faked with Profiler API based tools, like Typemock (commercial) or Microsoft Moles (free, known as Fakes in Visual Studio 2012 Ultimate /2013 /2015).

Alternatively, you could refactor your design to abstract calls to static methods, and provide this abstraction to your class via dependency injection. Then you'd not only have a better design, it will be testable with free tools, like Moq.

A common pattern to allow testability can be applied without using any tools altogether. Consider the following method:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = FileUtil.ReadDataFromFile(fileName);
        return data;
    }
}

Instead of trying to mock FileUtil.ReadDataFromFile, you could wrap it in a protected virtual method, like this:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = GetDataFromFile(fileName);
        return data;
    }

    protected virtual string[] GetDataFromFile(string fileName)
    {
        return FileUtil.ReadDataFromFile(fileName);
    }
}

Then, in your unit test, derive from MyClass and call it TestableMyClass. Then you can override the GetDataFromFile method to return your own test data.

Hope that helps.

How do I perform query filtering in django templates

I run into this problem on a regular basis and often use the "add a method" solution. However, there are definitely cases where "add a method" or "compute it in the view" don't work (or don't work well). E.g. when you are caching template fragments and need some non-trivial DB computation to produce it. You don't want to do the DB work unless you need to, but you won't know if you need to until you are deep in the template logic.

Some other possible solutions:

  1. Use the {% expr <expression> as <var_name> %} template tag found at http://www.djangosnippets.org/snippets/9/ The expression is any legal Python expression with your template's Context as your local scope.

  2. Change your template processor. Jinja2 (http://jinja.pocoo.org/2/) has syntax that is almost identical to the Django template language, but with full Python power available. It's also faster. You can do this wholesale, or you might limit its use to templates that you are working on, but use Django's "safer" templates for designer-maintained pages.

Build tree array from flat array in javascript

a more simple function list-to-tree-lite

npm install list-to-tree-lite

listToTree(list)

source:

function listToTree(data, options) {
    options = options || {};
    var ID_KEY = options.idKey || 'id';
    var PARENT_KEY = options.parentKey || 'parent';
    var CHILDREN_KEY = options.childrenKey || 'children';

    var tree = [],
        childrenOf = {};
    var item, id, parentId;

    for (var i = 0, length = data.length; i < length; i++) {
        item = data[i];
        id = item[ID_KEY];
        parentId = item[PARENT_KEY] || 0;
        // every item may have children
        childrenOf[id] = childrenOf[id] || [];
        // init its children
        item[CHILDREN_KEY] = childrenOf[id];
        if (parentId != 0) {
            // init its parent's children object
            childrenOf[parentId] = childrenOf[parentId] || [];
            // push it into its parent's children object
            childrenOf[parentId].push(item);
        } else {
            tree.push(item);
        }
    };

    return tree;
}

jsfiddle

Select statement to find duplicates on certain fields

To see duplicate values:

with MYCTE  as (
    select row_number() over ( partition by name  order by name) rown, *
    from tmptest  
    ) 
select * from MYCTE where rown <=1

height style property doesn't work in div elements

Position absolute fixes it for me. I suggest also adding a semi-colon if you haven't already.

.container {
    width: 22.5%;
    size: 22.5% 22.5%;
    margin-top: 0%;
    border-radius: 10px;
    background-color: floralwhite;
    display:inline-block;
    min-height: 20%;
    position: absolute;
    height: 50%;
}

how to refresh Select2 dropdown menu after ajax loading different content?

Got the same problem in 11 11 19, so sorry for possible necroposting. The only what helped was next solution:

var drop = $('#product_1');   // get our element, **must be unique**;
var settings = drop.attr('data-krajee-select2');  pick krajee attrs of our elem;
var drop_id = drop.attr('id');  // take id 
settings = window[settings];  // take previous settings from window;
drop.select2(settings);  // initialize select2 element with it;
$('.kv-plugin-loading').remove(); // remove loading animation;

It's, maybe, not so good, nice and precise solution, and maybe I still did not clearly understood, how it works and why, but this was the only, what keeps my select2 dropdowns, gotten by ajax, alive. Hope, this solution will be usefull or may push you in right decision in problem fixing

How to embed an autoplaying YouTube video in an iframe?

The embedded code of youtube has autoplay off by default. Simply add autoplay=1at the end of "src" attribute. For example:

<iframe src="http://www.youtube.com/embed/xzvScRnF6MU?autoplay=1" width="960" height="447" frameborder="0" allowfullscreen></iframe>

How to specify new GCC path for CMake

An alternative solution is to configure your project through cmake-gui, starting from a clean build directory. Among the options you have available at the beginning, there's the possibility to choose the exact path to the compilers

Bootstrap 3 Align Text To Bottom of Div

You can do this:

CSS:

#container {
    height:175px;
}

#container h3{
    position:absolute;
    bottom:0;
    left:0;
}

Then in HTML:

<div class="row">
    <div class="col-sm-6">
        <img src="//placehold.it/600x300" alt="Logo" />
    </div>
    <div id="container" class="col-sm-6">
        <h3>Some Text</h3>
    </div>
</div>

EDIT: add the <

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

So while this is answered and accepted it still came up as a top search result and the answers though laid out (after lots of research) left me scratching my head and digging a lot further. So here's a quick layout of how I resolved the issue.

Assuming my server is myserver.myhome.com and my static IP address is 192.168.1.150:

  1. Edit the hosts file

    $ sudo nano -w /etc/hosts
    
    127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
    
    127.0.0.1 myserver.myhome.com myserver
    
    192.168.1.150 myserver.myhome.com myserver
    
    ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
    ::1 myserver.myhome.com myserver
    
  2. Edit httpd.conf

    $ sudo nano -w /etc/apache2/httpd.conf
    
    ServerName myserver.myhome.com
    
  3. Edit network

    $ sudo nano -w /etc/sysconfig/network HOSTNAME=myserver.myhome.com
    
  4. Verify

    $ hostname
    
    (output) myserver.myhome.com
    
    $ hostname -f
    
    (output) myserver.myhome.com
    
  5. Restart Apache

    $ sudo /etc/init.d/apache2 restart
    

It appeared the difference was including myserver.myhome.com to both the 127.0.0.1 as well as the static IP address 192.168.1.150 in the hosts file. The same on Ubuntu Server and CentOS.

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

When you declare

var a=[];

you are declaring a empty array.

But when you are declaring

var a={};

you are declaring a Object .

Although Array is also Object in Javascript but it is numeric key paired values. Which have all the functionality of object but Added some few method of Array like Push,Splice,Length and so on.

So if you want Some values where you need to use numeric keys use Array. else use object. you can Create object like:

var a={name:"abc",age:"14"}; 

And can access values like

console.log(a.name);

Playing Sound In Hidden Tag

<audio id="audio" style="display:none;" src="mp3/Fans-Mi-tooXclusive_com.mp3" controls autoplay loop onloadeddata="setHalfVolume()">

This auto-plays, hides the music and reduces the music even if system volume is high to avoid noise. Place this in script:

<script>
    function setHalfVolume() {
        var myAudio = document.getElementById("audio");
        myAudio.volume = 0.2;
    }
</script>

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

The server directive has to be in the http directive. It should not be outside of it.

Incase if you need detailed information, refer this.

Versioning SQL Server database

With VS 2010, use the Database project.

  1. Script out your database
  2. Make changes to scripts or directly on your db server
  3. Sync up using Data > Schema Compare

Makes a perfect DB versioning solution, and makes syncing DB's a breeze.

Module not found: Error: Can't resolve 'core-js/es6'

If you use @babel/preset-env and useBuiltIns, then you just have to add corejs: 3 beside the useBuiltIns option, to specify which version to use, default is corejs: 2.

presets: [
  [
    "@babel/preset-env", {
      "useBuiltIns": "usage",
      "corejs": 3
    }
  ]
],

For further details see: https://github.com/zloirock/core-js/blob/master/docs/2019-03-19-core-js-3-babel-and-a-look-into-the-future.md#babelpreset-env

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

Solved this by adding following

RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^ - [L]

catching stdout in realtime from subprocess

To avoid caching of output you might wanna try pexpect,

child = pexpect.spawn(launchcmd,args,timeout=None)
while True:
    try:
        child.expect('\n')
        print(child.before)
    except pexpect.EOF:
        break

PS : I know this question is pretty old, still providing the solution which worked for me.

PPS: got this answer from another question

Detect iPhone/iPad purely by css

You might want to try the solution from this O'Reilly article.

The important part are these CSS media queries:

<link rel="stylesheet" media="all and (max-device-width: 480px)" href="iphone.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)" href="ipad-portrait.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)" href="ipad-landscape.css"> 
<link rel="stylesheet" media="all and (min-device-width: 1025px)" href="ipad-landscape.css"> 

Node.js version on the command line? (not the REPL)

One cool tip if you are using the Atom editor.

$ apm -v
apm  1.12.5
npm  3.10.5
node 4.4.5
python 2.7.12
git 2.7.4

It will return you not only the node version but also few other things.

How to use PHP string in mySQL LIKE query?

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

Trigger insert old values- values that was updated

Here's an example update trigger:

create table Employees (id int identity, Name varchar(50), Password varchar(50))
create table Log (id int identity, EmployeeId int, LogDate datetime, 
    OldName varchar(50))
go
create trigger Employees_Trigger_Update on Employees
after update
as
insert into Log (EmployeeId, LogDate, OldName) 
select id, getdate(), name
from deleted
go
insert into Employees (Name, Password) values ('Zaphoid', '6')
insert into Employees (Name, Password) values ('Beeblebox', '7')
update Employees set Name = 'Ford' where id = 1
select * from Log

This will print:

id   EmployeeId   LogDate                   OldName
1    1            2010-07-05 20:11:54.127   Zaphoid

How to remove origin from git repository

Remove existing origin and add new origin to your project directory

>$ git remote show origin

>$ git remote rm origin

>$ git add .

>$ git commit -m "First commit"

>$ git remote add origin Copied_origin_url

>$ git remote show origin

>$ git push origin master

Best way to read a large file into a byte array in C#?

I would recommend trying the Response.TransferFile() method then a Response.Flush() and Response.End() for serving your large files.

Date minus 1 year?

Use strtotime() function:

  $time = strtotime("-1 year", time());
  $date = date("Y-m-d", $time);

Finding a substring within a list in Python

print [s for s in list if sub in s]

If you want them separated by newlines:

print "\n".join(s for s in list if sub in s)

Full example, with case insensitivity:

mylist = ['abc123', 'def456', 'ghi789', 'ABC987', 'aBc654']
sub = 'abc'

print "\n".join(s for s in mylist if sub.lower() in s.lower())

Regular expression matching a multiline block of text

This will work:

>>> import re
>>> rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE)
>>> rx_blanks=re.compile(r"\W+") # to remove blanks and newlines
>>> text="""Some varying text1
...
... AAABBBBBBCCCCCCDDDDDDD
... EEEEEEEFFFFFFFFGGGGGGG
... HHHHHHIIIIIJJJJJJJKKKK
...
... Some varying text 2
...
... LLLLLMMMMMMNNNNNNNOOOO
... PPPPPPPQQQQQQRRRRRRSSS
... TTTTTUUUUUVVVVVVWWWWWW
... """
>>> for match in rx_sequence.finditer(text):
...   title, sequence = match.groups()
...   title = title.strip()
...   sequence = rx_blanks.sub("",sequence)
...   print "Title:",title
...   print "Sequence:",sequence
...   print
...
Title: Some varying text1
Sequence: AAABBBBBBCCCCCCDDDDDDDEEEEEEEFFFFFFFFGGGGGGGHHHHHHIIIIIJJJJJJJKKKK

Title: Some varying text 2
Sequence: LLLLLMMMMMMNNNNNNNOOOOPPPPPPPQQQQQQRRRRRRSSSTTTTTUUUUUVVVVVVWWWWWW

Some explanation about this regular expression might be useful: ^(.+?)\n\n((?:[A-Z]+\n)+)

  • The first character (^) means "starting at the beginning of a line". Be aware that it does not match the newline itself (same for $: it means "just before a newline", but it does not match the newline itself).
  • Then (.+?)\n\n means "match as few characters as possible (all characters are allowed) until you reach two newlines". The result (without the newlines) is put in the first group.
  • [A-Z]+\n means "match as many upper case letters as possible until you reach a newline. This defines what I will call a textline.
  • ((?:textline)+) means match one or more textlines but do not put each line in a group. Instead, put all the textlines in one group.
  • You could add a final \n in the regular expression if you want to enforce a double newline at the end.
  • Also, if you are not sure about what type of newline you will get (\n or \r or \r\n) then just fix the regular expression by replacing every occurrence of \n by (?:\n|\r\n?).

Python SQL query string formatting

You can use inspect.cleandoc to nicely format your printed SQL statement.

This works very well with your option 2.

Note: the print("-"*40) is only to demonstrate the superflous blank lines if you do not use cleandoc.

from inspect import cleandoc
def query():
    sql = """
        select field1, field2, field3, field4
        from table
        where condition1=1
        and condition2=2
    """

    print("-"*40)
    print(sql)
    print("-"*40)
    print(cleandoc(sql))
    print("-"*40)

query()

Output:

----------------------------------------

        select field1, field2, field3, field4
        from table
        where condition1=1
        and condition2=2

----------------------------------------
select field1, field2, field3, field4
from table
where condition1=1
and condition2=2
----------------------------------------

From the docs:

inspect.cleandoc(doc)

Clean up indentation from docstrings that are indented to line up with blocks of code.

All leading whitespace is removed from the first line. Any leading whitespace that can be uniformly removed from the second line onwards is removed. Empty lines at the beginning and end are subsequently removed. Also, all tabs are expanded to spaces.

This declaration has no storage class or type specifier in C++

Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.

Create web service proxy in Visual Studio from a WSDL file

Using WSDL.exe didn't work for me (gave me an error about a missing type), but I was able to right-click on my project in VS and select "Add Service Reference." I entered the path to the wsdl file in the Address field and hit "Go." That seemed to be able to find all the proper types and added the classes directly to my project.

How do I create a nice-looking DMG for Mac OS X using command-line tools?

I've just written a new (friendly) command line utility to do this. It doesn’t rely on Finder/AppleScript, or on any of the (deprecated) Alias Manager APIs, and it’s easy to configure and use.

Anyway, anyone who is interested can find it on PyPi; the documentation is available on Read The Docs.

Jquery change <p> text programmatically

"saving" is something wholly different from changing paragraph content with jquery.

If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").

Judging by your question, this is a topic on which you will have to do MUCH more research.

Input page (input.html):

<form action="/saveMyParagraph.php">
    <input name="pContent" type="text"></input>
</form>

Saving page (saveMyParagraph.php) and Ouput page (output.php):

Inserting Data Into a MySQL Database using PHP

How to iterate over the keys and values with ng-repeat in AngularJS?

Here's a working example:

<div class="item item-text-wrap" ng-repeat="(key,value) in form_list">
  <b>{{key}}</b> : {{value}}
</div>

edited

How to remove padding around buttons in Android?

A workaround may be to try to use -ve values for margins like following:

<Button
    android:id="@+id/button_back"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:onClick="CloseActivity"
    android:padding="0dp"
    android:layout_marginLeft="-5dip"
    android:layout_marginRight="-5dip"
    android:layout_marginTop="-5dip"
    android:layout_marginBottom="-5dip"
    android:text="@string/back" />

It will make that space vanish. I mean you can choose the appropriate dip value, which makes it go away. It worked for me. Hope it works for you.

How to finish current activity in Android

Just call the finish() method:

context.finish();

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

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

import Router from 'vue-router'

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

In your component:

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

Comparing boxed Long values 127 and 128

Comparing non-primitives (aka Objects) in Java with == compares their reference instead of their values. Long is a class and thus Long values are Objects.

The problem is that the Java Developers wanted people to use Long like they used long to provide compatibility, which led to the concept of autoboxing, which is essentially the feature, that long-values will be changed to Long-Objects and vice versa as needed. The behaviour of autoboxing is not exactly predictable all the time though, as it is not completely specified.

So to be safe and to have predictable results always use .equals() to compare objects and do not rely on autoboxing in this case:

Long num1 = 127, num2 = 127;
if(num1.equals(num2)) { iWillBeExecutedAlways(); }

Consistency of hashCode() on a Java string

I can see that documentation as far back as Java 1.2.

While it's true that in general you shouldn't rely on a hash code implementation remaining the same, it's now documented behaviour for java.lang.String, so changing it would count as breaking existing contracts.

Wherever possible, you shouldn't rely on hash codes staying the same across versions etc - but in my mind java.lang.String is a special case simply because the algorithm has been specified... so long as you're willing to abandon compatibility with releases before the algorithm was specified, of course.

JavaScript getElementByID() not working

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = function(){
           var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('I am clicked!');
            }
        };
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
    </form>
</body>
</html>

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

After upgrading Fedora 26 to 28 I faced same issue. And following logs were missing

/var/log/secure
/var/log/messages

ISSUE:

antop@localmachine ? ~ ? ssh [email protected]
sign_and_send_pubkey: signing failed: agent refused operation
[email protected]'s password:

error message is not pointing actual issue. Issue resolved by

chmod 700 ~/.ssh
chmod 600 ~/.ssh/*

Mipmap drawables for icons

One thing I mentioned in another thread that is worth pointing out -- if you are building different versions of your app for different densities, you should know about the "mipmap" resource directory. This is exactly like "drawable" resources, except it does not participate in density stripping when creating the different apk targets.

https://plus.google.com/105051985738280261832/posts/QTA9McYan1L

How to create PDF files in Python

fpdf works well for me. Much simpler than ReportLab and really free. Works with UTF-8.

What is the difference between syntax and semantics in programming languages?

  • You need correct syntax to compile.
  • You need correct semantics to make it work.

Create Log File in Powershell

You might just want to use the new TUN.Logging PowerShell module, this can also send a log mail. Just use the Start-Log and/or Start-MailLog cmdlets to start logging and then just use Write-HostLog, Write-WarningLog, Write-VerboseLog, Write-ErrorLog etc. to write to console and log file/mail. Then call Send-Log and/or Stop-Log at the end and voila, you got your logging. Just install it from the PowerShell Gallery via

Install-Module -Name TUN.Logging

Or just follow the link: https://www.powershellgallery.com/packages/TUN.Logging

Documentation of the module can be found here: https://github.com/echalone/TUN/blob/master/PowerShell/Modules/TUN.Logging/TUN.Logging.md

ng-if, not equal to?

Here is a nifty solution with a filter:

app.filter('status', function() {

  var statusDict = {
    0: "No payment",
    1: "Late",
    2: "Late",
    3: "Some payment made",
    4: "Some payment made",
    5: "Some payment made",
    6: "Late and further taken out"
  };

  return function(status) {
    return statusDict[status] || 'Error';
  };
});

Markup:

<div ng-repeat="details in myDataSet">
  <p>{{ details.Name }}</p>
  <p>{{ details.DOB  }}</p>
  <p>{{ details.Payment[0].Status | status }}</p>
  <p>{{ details.Gender}}</p>
</div>

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

You can use the getClass() method, or you can use instanceof. For example

for (Object obj : list) {
  if (obj instanceof String) {
   ...
  }
}

or

for (Object obj : list) {
 if (obj.getClass().equals(String.class)) {
   ...
 }
}

Note that instanceof will match subclasses. For instance, of C is a subclass of A, then the following will be true:

C c = new C();
assert c instanceof A;

However, the following will be false:

C c = new C();
assert !c.getClass().equals(A.class)

Accessing MP3 metadata with Python

The first answer that uses eyed3 is outdated so here is an updated version of it.

Reading tags from an mp3 file:

 import eyed3

 audiofile = eyed3.load("some/file.mp3")
 print(audiofile.tag.artist)
 print(audiofile.tag.album)
 print(audiofile.tag.album_artist)
 print(audiofile.tag.title)
 print(audiofile.tag.track_num)

An example from the website to modify tags:

 import eyed3

 audiofile = eyed3.load("some/file.mp3")
 audiofile.tag.artist = u"Integrity"
 audiofile.tag.album = u"Humanity Is The Devil"
 audiofile.tag.album_artist = u"Integrity"
 audiofile.tag.title = u"Hollow"
 audiofile.tag.track_num = 2

An issue I encountered while trying to use eyed3 for the first time had to do with an import error of libmagic even though it was installed. To fix this install the magic-bin whl from here

C# getting its own class name

this can be omitted. All you need to get the current class name is:

GetType().Name

Sorting int array in descending order

Guava has a method Ints.asList() for creating a List<Integer> backed by an int[] array. You can use this with Collections.sort to apply the Comparator to the underlying array.

List<Integer> integersList = Ints.asList(arr);
Collections.sort(integersList, Collections.reverseOrder());

Note that the latter is a live list backed by the actual array, so it should be pretty efficient.

What does "export default" do in JSX?

Simplest Understanding for default export is

Export is ES6's feature which is used to Export a module(file) and use it in some other module(file).

Default Export:

  1. default export is the convention if you want to export only one object(variable, function, class) from the file(module).
  2. There could be only one default export per file, but not restricted to only one export.
  3. When importing default exported object we can rename it as well.

Export or Named Export:

  1. It is used to export the object(variable, function, calss) with the same name.

  2. It is used to export multiple objects from one file.

  3. It cannot be renamed when importing in another file, it must have the same name that was used to export it, but we can create its alias by using as operator.

In React, Vue and many other frameworks the Export is mostly used to export reusable components to make modular based applications.

SQL - Select first 10 rows only?

SELECT* from <table name> WHERE rownum <= 10;

How do I bind a WPF DataGrid to a variable number of columns?

There is a sample of the way I do programmatically:

public partial class UserControlWithComboBoxColumnDataGrid : UserControl
{
    private Dictionary<int, string> _Dictionary;
    private ObservableCollection<MyItem> _MyItems;
    public UserControlWithComboBoxColumnDataGrid() {
      _Dictionary = new Dictionary<int, string>();
      _Dictionary.Add(1,"A");
      _Dictionary.Add(2,"B");
      _MyItems = new ObservableCollection<MyItem>();
      dataGridMyItems.AutoGeneratingColumn += DataGridMyItems_AutoGeneratingColumn;
      dataGridMyItems.ItemsSource = _MyItems;

    }
private void DataGridMyItems_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            var desc = e.PropertyDescriptor as PropertyDescriptor;
            var att = desc.Attributes[typeof(ColumnNameAttribute)] as ColumnNameAttribute;
            if (att != null)
            {
                if (att.Name == "My Combobox Item") {
                    var comboBoxColumn =  new DataGridComboBoxColumn {
                        DisplayMemberPath = "Value",
                        SelectedValuePath = "Key",
                        ItemsSource = _ApprovalTypes,
                        SelectedValueBinding =  new Binding( "Bazinga"),   
                    };
                    e.Column = comboBoxColumn;
                }

            }
        }

}
public class MyItem {
    public string Name{get;set;}
    [ColumnName("My Combobox Item")]
    public int Bazinga {get;set;}
}

  public class ColumnNameAttribute : Attribute
    {
        public string Name { get; set; }
        public ColumnNameAttribute(string name) { Name = name; }
}

set initial viewcontroller in appdelegate - swift

Disable Main.storyboard

General -> Deployment Info -> Main Interface -> remove `Main` 
Info.plist -> remove Key/Value for `UISceneStoryboardFile` and  `UIMainStoryboardFile`

Add Storyboard ID

Main.storyboard -> Select View Controller -> Inspectors -> Identity inspector -> Storyboard ID -> e.g. customVCStoryboardId

Swift 5 and Xcode 11

Extend UIWindow

class CustomWindow : UIWindow {
    //...
}

Edit generated by Xcode SceneDelegate.swift

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: CustomWindow!

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        guard let windowScene = (scene as? UIWindowScene) else { return }

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "customVCStoryboardId")

        window = CustomWindow(windowScene: windowScene)
        window.rootViewController = initialViewController
        window.makeKeyAndVisible()
    }

    //...
}

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

There are 3 things I can think of off the top of my head:

  1. Just used named urls, it's more robust and maintainable anyway
  2. Try using django.core.urlresolvers.reverse at the command line for a (possibly) better error

    >>> from django.core.urlresolvers import reverse
    >>> reverse('products.views.filter_by_led')
    
  3. Check to see if you have more than one url that points to that view

Unmount the directory which is mounted by sshfs in Mac

Just as reference let me quote the osxfuse FAQ

4.8. How should I unmount my "FUSE for OS X" file system? I cannot find the fusermount program anywhere.

Just use the standard umount command in OS X. You do not need the Linux-specific fusermount with "FUSE for OS X".

As mentioned above, either diskutil unmount or umount should work

Functions are not valid as a React child. This may happen if you return a Component instead of from render

I was getting this from webpack lazy loading like this

import Loader from 'some-loader-component';
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
  fallback: Loader, // warning
});
render() {
    return <WishlistPageComponent />;
}


// changed to this then it's suddenly fine
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
  fallback: '', // all good
});    

How to check if a file exists before creating a new file

I just saw this test:

bool getFileExists(const TCHAR *file)
{ 
  return (GetFileAttributes(file) != 0xFFFFFFFF);
}

Why do I need to configure the SQL dialect of a data source?

The dialect in the Hibernate context, will take care of database data type, like in orace it is integer however in SQL it is int, so this will by known in hibernate by this property, how to map the fields internally.

How do I scroll the UIScrollView when the keyboard appears?

The only thing I would update in Apple code is the keyboardWillBeHidden: method, to provide smooth transition.

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;

    [UIView animateWithDuration:0.4 animations:^{
        self.scrollView.contentInset = contentInsets;
    }];
    self.scrollView.scrollIndicatorInsets = contentInsets;

}

Delete files in subfolder using batch script

I had to complete the same task and I used a "for" loop and a "del" command as follows:

@ECHO OFF

set dir=%cd%

FOR /d /r %dir% %%x in (archive\) do (
    if exist "%%x" del %%x\*.txt /f /q
)

You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.

These are the options for "for" command:

  • /d For directories
  • /r For recursive

These are the options for "del" command:

  • /f Force deletes read-only files
  • /q Quiet mode; suppresses prompts for delete confirmations.

How do I configure different environments in Angular.js?

One cool solution might be separating all environment-specific values into some separate angular module, that all other modules depend on:

angular.module('configuration', [])
       .constant('API_END_POINT','123456')
       .constant('HOST','localhost');

Then your modules that need those entries can declare a dependency on it:

angular.module('services',['configuration'])
       .factory('User',['$resource','API_END_POINT'],function($resource,API_END_POINT){
           return $resource(API_END_POINT + 'user');
       });

Now you could think about further cool stuff:

The module, that contains the configuration can be separated into configuration.js, that will be included at your page.

This script can be easily edited by each of you, as long as you don’t check this separate file into git. But it's easier to not check in the configuration if it is in a separate file. Also, you could branch it locally.

Now, if you have a build-system, like ANT or Maven, your further steps could be implementing some placeholders for the values API_END_POINT, that will be replaced during build-time, with your specific values.

Or you have your configuration_a.js and configuration_b.js and decide at the backend which to include.

How to split a string, but also keep the delimiters?

I don't think it is possible with String#split, but you can use a StringTokenizer, though that won't allow you to define your delimiter as a regex, but only as a class of single-digit characters:

new StringTokenizer("Hello, world. Hi!", ",.!", true); // true for returnDelims

What is the difference between "long", "long long", "long int", and "long long int" in C++?

While in Java a long is always 64 bits, in C++ this depends on computer architecture and operating system. For example, a long is 64 bits on Linux and 32 bits on Windows (this was done to keep backwards-compatability, allowing 32-bit programs to compile on 64-bit Windows without any changes).

It is considered good C++ style to avoid short int long ... and instead use:

std::int8_t   # exactly  8 bits
std::int16_t  # exactly 16 bits
std::int32_t  # exactly 32 bits
std::int64_t  # exactly 64 bits

std::size_t   # can hold all possible object sizes, used for indexing

These (int*_t) can be used after including the <cstdint> header. size_t is in <stdlib.h>.

How much does it cost to develop an iPhone application?

The Barack Obama app took 22 days to develop from first code to release. Three developers (although not all of them were full time). 10 people total. Figure 500-1000 man hours. Contracting rates are $100-150/hr. Figure $50000-$150000. Compare your app to Obama.app and scale accordingly.

What is Scala's yield?

It is used in sequence comprehensions (like Python's list-comprehensions and generators, where you may use yield too).

It is applied in combination with for and writes a new element into the resulting sequence.

Simple example (from scala-lang)

/** Turn command line arguments to uppercase */
object Main {
  def main(args: Array[String]) {
    val res = for (a <- args) yield a.toUpperCase
    println("Arguments: " + res.toString)
  }
}

The corresponding expression in F# would be

[ for a in args -> a.toUpperCase ]

or

from a in args select a.toUpperCase 

in Linq.

Ruby's yield has a different effect.

How to click a browser button with JavaScript automatically?

You can use

setInterval(function(){ 
    document.getElementById("yourbutton").click();
}, 1000);

Passing a String by Reference in Java?

String is a special class in Java. It is Thread Safe which means "Once a String instance is created, the content of the String instance will never changed ".

Here is what is going on for

 zText += "foo";

First, Java compiler will get the value of zText String instance, then create a new String instance whose value is zText appending "foo". So you know why the instance that zText point to does not changed. It is totally a new instance. In fact, even String "foo" is a new String instance. So, for this statement, Java will create two String instance, one is "foo", another is the value of zText append "foo". The rule is simple: The value of String instance will never be changed.

For method fillString, you can use a StringBuffer as parameter, or you can change it like this:

String fillString(String zText) {
    return zText += "foo";
}

How can I use SUM() OVER()

if you are using SQL 2012 you should try

SELECT  ID, 
        AccountID, 
        Quantity, 
        SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY AccountID rows between unbounded preceding and current row ) AS TopBorcT, 
FROM tCariH

if available, better order by date column.

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:

@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);

Can't find System.Windows.Media namespace?

The System.Windows.Media.Imaging namespace is part of PresentationCore.dll (if you are using Visual Studio 2008 then the WPF application template will automatically add this reference). Note that this namespace is not a direct wrapping of the WIC library, although a large proportion of the more common uses are still available and it is relatively obvious how these map to the WIC versions. For more information on the classes in this namespace check out

http://msdn2.microsoft.com/en-us/library/system.windows.media.imaging.aspx

VBA: How to display an error message just like the standard error message which has a "Debug" button?

This answer does not address the Debug button (you'd have to design a form and use the buttons on that to do something like the method in your next question). But it does address this part:

now I don't want to lose the comfortableness of the default handler which also point me to the exact line where the error has occured.

First, I'll assume you don't want this in production code - you want it either for debugging or for code you personally will be using. I use a compiler flag to indicate debugging; then if I'm troubleshooting a program, I can easily find the line that's causing the problem.

# Const IsDebug = True

Sub ProcA()
On Error Goto ErrorHandler
' Main code of proc

ExitHere:
    On Error Resume Next
    ' Close objects and stuff here
    Exit Sub

ErrorHandler:
    MsgBox Err.Number & ": " & Err.Description, , ThisWorkbook.Name & ": ProcA"
    #If IsDebug Then
        Stop            ' Used for troubleshooting - Then press F8 to step thru code 
        Resume          ' Resume will take you to the line that errored out
    #Else
        Resume ExitHere ' Exit procedure during normal running
    #End If
End Sub

Note: the exception to Resume is if the error occurs in a sub-procedure without an error handling routine, then Resume will take you to the line in this proc that called the sub-procedure with the error. But you can still step into and through the sub-procedure, using F8 until it errors out again. If the sub-procedure's too long to make even that tedious, then your sub-procedure should probably have its own error handling routine.

There are multiple ways to do this. Sometimes for smaller programs where I know I'm gonna be stepping through it anyway when troubleshooting, I just put these lines right after the MsgBox statement:

    Resume ExitHere         ' Normally exits during production
    Resume                  ' Never will get here
Exit Sub

It will never get to the Resume statement, unless you're stepping through and set it as the next line to be executed, either by dragging the next statement pointer to that line, or by pressing CtrlF9 with the cursor on that line.

Here's an article that expands on these concepts: Five tips for handling errors in VBA. Finally, if you're using VBA and haven't discovered Chip Pearson's awesome site yet, he has a page explaining Error Handling In VBA.

How to set UITextField height?

An update for iOS 6 : using auto-layout, even though you still can't set the UITextField's height from the Size Inspector in the Interface Builder (as of Xcode 4.5 DP4 at least), it is now possible to set a Height constraint on it, which you can edit from the Interface Builder.

Also, if you're setting the frame's height by code, auto-layout may reset it depending on the other constraints your view may have.

How do you determine the ideal buffer size when using FileInputStream?

As already mentioned in other answers, use BufferedInputStreams.

After that, I guess the buffer size does not really matter. Either the program is I/O bound, and growing buffer size over BIS default, will not make any big impact on performance.

Or the program is CPU bound inside the MessageDigest.update(), and majority of the time is not spent in the application code, so tweaking it will not help.

(Hmm... with multiple cores, threads might help.)

Can I target all <H> tags with a single selector?

You can also use PostCSS and the custom selectors plugin

@custom-selector :--headings h1, h2, h3, h4, h5, h6;

article :--headings {
  margin-top: 0;
}

Output:

article h1,
article h2,
article h3,
article h4,
article h5,
article h6 {
  margin-top: 0;
}

Print line numbers starting at zero using awk

Another option besides awk is nl which allows for options -v for setting starting value and -n <lf,rf,rz> for left, right and right with leading zeros justified. You can also include -s for a field separator such as -s "," for comma separation between line numbers and your data.

In a Unix environment, this can be done as

cat <infile> | ...other stuff... | nl -v 0 -n rz

or simply

nl -v 0 -n rz <infile>

Example:

echo "Here 
are
some 
words" > words.txt

cat words.txt | nl -v 0 -n rz

Out:

000000      Here
000001      are
000002      some
000003      words

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

How to detect the swipe left or Right in Android?

This is a cute class I use (in cases I want to catch event on a View, if it is a ViewGroup, I use the second implementation):

import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class SwipeDetector implements View.OnTouchListener{

    private int min_distance = 100;
    private float downX, downY, upX, upY;
    private View v;

    private onSwipeEvent swipeEventListener;



    public SwipeDetector(View v){
        this.v=v;
        v.setOnTouchListener(this);
    }

    public void setOnSwipeListener(onSwipeEvent listener)
    {
        try{
            swipeEventListener=listener;
        }
        catch(ClassCastException e)
        {
            Log.e("ClassCastException","please pass SwipeDetector.onSwipeEvent Interface instance",e);
        }
    }


    public void onRightToLeftSwipe(){
        if(swipeEventListener!=null)
            swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.RIGHT_TO_LEFT);
        else
            Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
    }

    public void onLeftToRightSwipe(){
        if(swipeEventListener!=null)
            swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.LEFT_TO_RIGHT);
        else
            Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
    }

    public void onTopToBottomSwipe(){
        if(swipeEventListener!=null)
            swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.TOP_TO_BOTTOM);
        else
            Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
    }

    public void onBottomToTopSwipe(){
        if(swipeEventListener!=null)
            swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.BOTTOM_TO_TOP);
        else
            Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
    }

    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN: {
            downX = event.getX();
            downY = event.getY();
            return true;
        }
        case MotionEvent.ACTION_UP: {
            upX = event.getX();
            upY = event.getY();

            float deltaX = downX - upX;
            float deltaY = downY - upY;

            //HORIZONTAL SCROLL
            if(Math.abs(deltaX) > Math.abs(deltaY))
            {
                if(Math.abs(deltaX) > min_distance){
                    // left or right
                    if(deltaX < 0) 
                    {
                        this.onLeftToRightSwipe();
                        return true;
                    }
                    if(deltaX > 0) {
                        this.onRightToLeftSwipe();
                        return true; 
                    }
                }
                else {
                    //not long enough swipe...
                    return false; 
                }
            }
            //VERTICAL SCROLL
            else 
            {
                if(Math.abs(deltaY) > min_distance){
                    // top or down
                    if(deltaY < 0) 
                    { this.onTopToBottomSwipe();
                    return true; 
                    }
                    if(deltaY > 0)
                    { this.onBottomToTopSwipe(); 
                    return true;
                    }
                }
                else {
                    //not long enough swipe...
                    return false;
                }
            }

            return true;
        }
        }
        return false;
    }
    public interface onSwipeEvent
    {
        public void SwipeEventDetected(View v, SwipeTypeEnum SwipeType);
    }

    public SwipeDetector setMinDistanceInPixels(int min_distance)
{
    this.min_distance=min_distance;
    return this;
}

    public enum SwipeTypeEnum
    {
        RIGHT_TO_LEFT,LEFT_TO_RIGHT,TOP_TO_BOTTOM,BOTTOM_TO_TOP
    }

}

and this is a use example:

filters_container=(RelativeLayout)root.findViewById(R.id.filters_container);
    new SwipeDetector(filters_container).setOnSwipeListener(new SwipeDetector.onSwipeEvent() {
        @Override
        public void SwipeEventDetected(View v, SwipeDetector.SwipeTypeEnum swipeType) {
            if(swipeType==SwipeDetector.SwipeTypeEnum.LEFT_TO_RIGHT)
                getActivity().onBackPressed();
        }
    });

In some cases you would like to detect the swipe gestures on a container and pass down the touch Events to the childs so in that case you can create a Custom View group, lets say RelativeLayout and override onInterceptTouchEvent , and there you can detect the swipe event without blocking the pass of Touch Event to your child views,for Example:

    import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;


public class SwipeDetectRelativeLayout extends RelativeLayout {


    private float x1,x2;
    static final int MIN_DISTANCE=150;
    private onSwipeEventDetected mSwipeDetectedListener;


    public SwipeDetectRelativeLayout(Context context) {
        super(context);
    }

    public SwipeDetectRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SwipeDetectRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        switch(ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                x1 = ev.getX();
                break;
            case MotionEvent.ACTION_UP:
                x2 = ev.getX();
                float deltaX = x2 - x1;
                if (Math.abs(deltaX) > MIN_DISTANCE)
                {
                        //swiping right to left
                        if(deltaX<0)
                        {
                            if(mSwipeDetectedListener!=null)
                                mSwipeDetectedListener.swipeEventDetected();
                        }
                }
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    public interface onSwipeEventDetected
    {
        public void swipeEventDetected();
    }

    public void registerToSwipeEvents(onSwipeEventDetected listener)
    {
        this.mSwipeDetectedListener=listener;
    }
}

Angular 4 checkbox change value

Another approach is to use ngModelChange:

Template:

<input type="checkbox" ngModel (ngModelChange)="onChecked(obj, $event)" />

Controller:

onChecked(obj: any, isChecked: boolean){
  console.log(obj, isChecked); // {}, true || false
}

I prefer this method because here you get the relevant object and true/false values of a checkbox.

Why can't I push to this bare repository?

git push --all

is the canonical way to push everything to a new bare repository.

Another way to do the same thing is to create your new, non-bare repository and then make a bare clone with

git clone --bare

then use

git remote add origin <new-remote-repo>

in the original (non-bare) repository.

How can I String.Format a TimeSpan object with a custom format in .NET?

This is a pain in VS 2010, here's my workaround solution.

 public string DurationString
        {
            get 
            {
                if (this.Duration.TotalHours < 24)
                    return new DateTime(this.Duration.Ticks).ToString("HH:mm");
                else //If duration is more than 24 hours
                {
                    double totalminutes = this.Duration.TotalMinutes;
                    double hours = totalminutes / 60;
                    double minutes = this.Duration.TotalMinutes - (Math.Floor(hours) * 60);
                    string result = string.Format("{0}:{1}", Math.Floor(hours).ToString("00"), Math.Floor(minutes).ToString("00"));
                    return result;
                }
            } 
        }

"Sources directory is already netbeans project" error when opening a project from existing sources

Click File >> Recent Projects > and you should be able to use edit it again. Hope it helps :)

Difference between .dll and .exe?

There are a few more differences regarding the structure you could mention.

  1. Both DLL and EXE share the same file structure - Portable Executable, or PE. To differentiate between the two, one can look in the Characteristics member of IMAGE_FILE_HEADER inside IMAGE_NT_HEADERS. For a DLL, it has the IMAGE_FILE_DLL (0x2000) flag turned on. For a EXE it's the IMAGE_FILE_EXECUTABLE_IMAGE (0x2) flag.
  2. PE files consist of some headers and a number of sections. There's usually a section for code, a section for data, a section listing imported functions and a section for resources. Some sections may contain more than one thing. The header also describes a list of data directories that are located in the sections. Those data directories are what enables Windows to find what it needs in the PE. But one type of data directory that an EXE will never have (unless you're building a frankenstein EXE) is the export directory. This is where DLL files have a list of functions they export and can be used by other EXE or DLL files. On the other side, each DLL and EXE has an import directory where it lists the functions and DLL files it requires to run.
  3. Also in the PE headers (IMAGE_OPTIONAL_HEADER) is the ImageBase member. It specifies the virtual address at which the PE assumes it will be loaded. If it is loaded at another address, some pointers could point to the wrong memory. As EXE files are amongst the first to be loaded into their new address space, the Windows loader can assure a constant load address and that's usually 0x00400000. That luxury doesn't exist for a DLL. Two DLL files loaded into the same process can request the same address. This is why a DLL has another data directory called Base Relocation Directory that usually resides in its own section - .reloc. This directory contains a list of places in the DLL that need to be rebased/patched so they'll point to the right memory. Most EXE files don't have this directory, but some old compilers do generate them.

You can read more on this topic @ MSDN.

Select Last Row in the Table

Use the latest scope provided by Laravel out of the box.

Model::latest()->first();

That way you're not retrieving all the records. A nicer shortcut to orderBy.

What is the (best) way to manage permissions for Docker shared volumes?

This is arguably not the best way for most circumstances, but it's not been mentioned yet so perhaps it will help someone.

  1. Bind mount host volume

    Host folder FOOBAR is mounted in container /volume/FOOBAR

  2. Modify your container's startup script to find GID of the volume you're interested in

    $ TARGET_GID=$(stat -c "%g" /volume/FOOBAR)

  3. Ensure your user belongs to a group with this GID (you may have to create a new group). For this example I'll pretend my software runs as the nobody user when inside the container, so I want to ensure nobody belongs to a group with a group id equal to TARGET_GID

  EXISTS=$(cat /etc/group | grep $TARGET_GID | wc -l)

  # Create new group using target GID and add nobody user
  if [ $EXISTS == "0" ]; then
    groupadd -g $TARGET_GID tempgroup
    usermod -a -G tempgroup nobody
  else
    # GID exists, find group name and add
    GROUP=$(getent group $TARGET_GID | cut -d: -f1)
    usermod -a -G $GROUP nobody
  fi

I like this because I can easily modify group permissions on my host volumes and know that those updated permissions apply inside the docker container. This happens without any permission or ownership modifications to my host folders/files, which makes me happy.

I don't like this because it assumes there's no danger in adding yourself to an arbitrary groups inside the container that happen to be using a GID you want. It cannot be used with a USER clause in a Dockerfile (unless that user has root privileges I suppose). Also, it screams hack job ;-)

If you want to be hardcore you can obviously extend this in many ways - e.g. search for all groups on any subfiles, multiple volumes, etc.

Asynchronously load images with jQuery

$(function () {

    if ($('#hdnFromGLMS')[0].value == 'MB9262') {
        $('.clr').append('<img src="~/Images/CDAB_london.jpg">');
    }
    else
    {
        $('.clr').css("display", "none");
        $('#imgIreland').css("display", "block");
        $('.clrIrland').append('<img src="~/Images/Ireland-v1.jpg">');
    }
});

Java: Difference between the setPreferredSize() and setSize() methods in components

IIRC ...

setSize sets the size of the component.

setPreferredSize sets the preferred size. The Layoutmanager will try to arrange that much space for your component.

It depends on whether you're using a layout manager or not ...

EC2 instance types's exact network performance?

Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.

If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.

%i or %d to print integer in C using printf()?

They are completely equivalent when used with printf(). Personally, I prefer %d, it's used more often (should I say "it's the idiomatic conversion specifier for int"?).

(One difference between %i and %d is that when used with scanf(), then %d always expects a decimal integer, whereas %i recognizes the 0 and 0x prefixes as octal and hexadecimal, but no sane programmer uses scanf() anyway so this should not be a concern.)

What is recursion and when should I use it?

Here's a simple example: how many elements in a set. (there are better ways to count things, but this is a nice simple recursive example.)

First, we need two rules:

  1. if the set is empty, the count of items in the set is zero (duh!).
  2. if the set is not empty, the count is one plus the number of items in the set after one item is removed.

Suppose you have a set like this: [x x x]. let's count how many items there are.

  1. the set is [x x x] which is not empty, so we apply rule 2. the number of items is one plus the number of items in [x x] (i.e. we removed an item).
  2. the set is [x x], so we apply rule 2 again: one + number of items in [x].
  3. the set is [x], which still matches rule 2: one + number of items in [].
  4. Now the set is [], which matches rule 1: the count is zero!
  5. Now that we know the answer in step 4 (0), we can solve step 3 (1 + 0)
  6. Likewise, now that we know the answer in step 3 (1), we can solve step 2 (1 + 1)
  7. And finally now that we know the answer in step 2 (2), we can solve step 1 (1 + 2) and get the count of items in [x x x], which is 3. Hooray!

We can represent this as:

count of [x x x] = 1 + count of [x x]
                 = 1 + (1 + count of [x])
                 = 1 + (1 + (1 + count of []))
                 = 1 + (1 + (1 + 0)))
                 = 1 + (1 + (1))
                 = 1 + (2)
                 = 3

When applying a recursive solution, you usually have at least 2 rules:

  • the basis, the simple case which states what happens when you have "used up" all of your data. This is usually some variation of "if you are out of data to process, your answer is X"
  • the recursive rule, which states what happens if you still have data. This is usually some kind of rule that says "do something to make your data set smaller, and reapply your rules to the smaller data set."

If we translate the above to pseudocode, we get:

numberOfItems(set)
    if set is empty
        return 0
    else
        remove 1 item from set
        return 1 + numberOfItems(set)

There's a lot more useful examples (traversing a tree, for example) which I'm sure other people will cover.

node.js require() cache - possible to invalidate?

If you always want to reload your module, you could add this function:

function requireUncached(module) {
    delete require.cache[require.resolve(module)];
    return require(module);
}

and then use requireUncached('./myModule') instead of require.

What is an idempotent operation?

retry-safe.

Is usually the easiest way to understand its meaning in computer science.

How can the Euclidean distance be calculated with NumPy?

A nice one-liner:

dist = numpy.linalg.norm(a-b)

However, if speed is a concern I would recommend experimenting on your machine. I've found that using math library's sqrt with the ** operator for the square is much faster on my machine than the one-liner NumPy solution.

I ran my tests using this simple program:

#!/usr/bin/python
import math
import numpy
from random import uniform

def fastest_calc_dist(p1,p2):
    return math.sqrt((p2[0] - p1[0]) ** 2 +
                     (p2[1] - p1[1]) ** 2 +
                     (p2[2] - p1[2]) ** 2)

def math_calc_dist(p1,p2):
    return math.sqrt(math.pow((p2[0] - p1[0]), 2) +
                     math.pow((p2[1] - p1[1]), 2) +
                     math.pow((p2[2] - p1[2]), 2))

def numpy_calc_dist(p1,p2):
    return numpy.linalg.norm(numpy.array(p1)-numpy.array(p2))

TOTAL_LOCATIONS = 1000

p1 = dict()
p2 = dict()
for i in range(0, TOTAL_LOCATIONS):
    p1[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))
    p2[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))

total_dist = 0
for i in range(0, TOTAL_LOCATIONS):
    for j in range(0, TOTAL_LOCATIONS):
        dist = fastest_calc_dist(p1[i], p2[j]) #change this line for testing
        total_dist += dist

print total_dist

On my machine, math_calc_dist runs much faster than numpy_calc_dist: 1.5 seconds versus 23.5 seconds.

To get a measurable difference between fastest_calc_dist and math_calc_dist I had to up TOTAL_LOCATIONS to 6000. Then fastest_calc_dist takes ~50 seconds while math_calc_dist takes ~60 seconds.

You can also experiment with numpy.sqrt and numpy.square though both were slower than the math alternatives on my machine.

My tests were run with Python 2.6.6.

Pointers in JavaScript?

It might be impossible since JavaScript doesn't have Perl's "\" operator to get a primitive by reference, but there is a way to create an "effectively a pointer" object for a primitive using this pattern.

This solution makes the most sense for when you already have the primitive(so you can't put it into an object anymore without needing to modify other code), but still need to pass a pointer to it for other parts of your code to tinker with its state; so you can still tinker with its state using the seamless proxy which behaves like a pointer.

var proxyContainer = {};

// | attaches a pointer-lookalike getter/setter pair
// | to the container object.
var connect = function(container) {
    // | primitive, can't create a reference to it anymore
    var cant_touch_this = 1337;

    // | we know where to bind our accessor/mutator
    // | so we can bind the pair to effectively behave
    // | like a pointer in most common use cases.
    Object.defineProperty(container, 'cant_touch_this', {
        'get': function() {
            return cant_touch_this;
        },                
        'set': function(val) {
            cant_touch_this = val;
        }
    });
};

// | not quite direct, but still "touchable"
var f = function(x) {
    x.cant_touch_this += 1;
};

connect(proxyContainer);

// | looks like we're just getting cant_touch_this
// | but we're actually calling the accessor.
console.log(proxyContainer.cant_touch_this);

// | looks like we're touching cant_touch_this
// | but we're actually calling the mutator.
proxyContainer.cant_touch_this = 90;

// | looks like we touched cant_touch_this
// | but we actually called a mutator which touched it for us.
console.log(proxyContainer.cant_touch_this);

f(proxyContainer);

// | we kinda did it! :)
console.log(proxyContainer.cant_touch_this);

What is SYSNAME data type in SQL Server?

Is there use case you can provide?

Anywhere you want to store an object name for use by database maintenance scripts. For example, a script purges old rows from certain tables that have a date column. It's configured with a table that gives table name, column name to filter on, and how many days of history to keep. Another script dumps certain tables to CSV files, and again is configured with a table listing the tables to dump. These configuration tables can use the sysname type to store table and column names.

How to switch databases in psql?

Use below statement to switch to different databases residing inside your postgreSQL RDMS

\c databaseName