Programs & Examples On #.sbr

Technology to enhance audio or speech codecs, especially at low bit rates and is based on harmonic redundancy in the frequency domain.

How to do a recursive find/replace of a string with awk or sed?

I just needed this and was not happy with the speed of the available examples. So I came up with my own:

cd /var/www && ack-grep -l --print0 subdomainA.example.com | xargs -0 perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g'

Ack-grep is very efficient on finding relevant files. This command replaced ~145 000 files with a breeze whereas others took so long I couldn't wait until they finish.

Returning http status code from Web Api controller

Another option:

return new NotModified();

public class NotModified : IHttpActionResult
{
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.NotModified);
        return Task.FromResult(response);
    }
}

What's the best way to parse command line arguments?

I prefer Click. It abstracts managing options and allows "(...) creating beautiful command line interfaces in a composable way with as little code as necessary".

Here's example usage:

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
              help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()

It also automatically generates nicely formatted help pages:

$ python hello.py --help
Usage: hello.py [OPTIONS]

  Simple program that greets NAME for a total of COUNT times.

Options:
  --count INTEGER  Number of greetings.
  --name TEXT      The person to greet.
  --help           Show this message and exit.

Export query result to .csv file in SQL Server 2008

One more method worth to mention here:

SQLCMD -S SEVERNAME -E -Q "SELECT COLUMN FROM TABLE" -s "," -o "c:\test.csv"

NOTE: I don't see any network admin let you run powershell scripts

What is a classpath and how do I set it?

Static member of a class can be called directly without creating object instance. Since the main method is static Java virtual Machine can call it without creating any instance of a class which contains the main method, which is start point of program.

Programmatically change UITextField Keyboard type

It's worth noting that if you want a currently-focused field to update the keyboard type immediately, there's one extra step:

// textField is set to a UIKeyboardType other than UIKeyboardTypeEmailAddress

[textField setKeyboardType:UIKeyboardTypeEmailAddress];
[textField reloadInputViews];

Without the call to reloadInputViews, the keyboard will not change until the selected field (the first responder) loses and regains focus.

A full list of the UIKeyboardType values can be found here, or:

typedef enum : NSInteger {
    UIKeyboardTypeDefault,
    UIKeyboardTypeASCIICapable,
    UIKeyboardTypeNumbersAndPunctuation,
    UIKeyboardTypeURL,
    UIKeyboardTypeNumberPad,
    UIKeyboardTypePhonePad,
    UIKeyboardTypeNamePhonePad,
    UIKeyboardTypeEmailAddress,
    UIKeyboardTypeDecimalPad,
    UIKeyboardTypeTwitter,
    UIKeyboardTypeWebSearch,
    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable
} UIKeyboardType;

Javascript negative number

How about something as simple as:

function negative(number){
    return number < 0;
}

The * 1 part is to convert strings to numbers.

Removing elements from array Ruby

a = [1,1,1,2,2,3]
a.slice!(0) # remove first index
a.slice!(-1) # remove last index
# a = [1,1,2,2] as desired

Upgrading Node.js to latest version

For Ubuntu

Install the nvm (Node Version Manager) using the below command

To install or update nvm, one can use the install script using cURL:

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

or Wget:

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

check if nvm is already installed

nvm --version

To install or update node, run below command:

nvm install 10.14.1(the version of node one want to install)

To check the list of node version available to the system or currently running for the system, run the below command:

nvm list

It will list all the available node version present in the system

check the node version:

node -v

'Property does not exist on type 'never'

Because you are assigning instance to null. The compiler infers that it can never be anything other than null. So it assumes that the else block should never be executed so instance is typed as never in the else block.

Now if you don't declare it as the literal value null, and get it by any other means (ex: let instance: Foo | null = getFoo();), you will see that instance will be null inside the if block and Foo inside the else block.

Never type documentation: https://www.typescriptlang.org/docs/handbook/basic-types.html#never

Edit:

The issue in the updated example is actually an open issue with the compiler. See:

https://github.com/Microsoft/TypeScript/issues/11498 https://github.com/Microsoft/TypeScript/issues/12176

Call a python function from jinja2

is there any way to import a whole set of python functions and have them accessible from jinja2 ?

Yes there is, In addition to the other answers above, this works for me.

Create a class and populate it with the associated methods e.g

class Test_jinja_object:

    def __init__(self):
        self.myvar = 'sample_var'

    def clever_function (self):
        return 'hello' 

Then create an instance of your class in your view function and pass the resultant object to your template as a parameter for the render_template function

my_obj = Test_jinja_object()

Now in your template, you can call the class methods in jinja like so

{{ my_obj.clever_function () }}

How do I remove lines between ListViews on Android?

You can try the following. It worked for me...

android:divider="@android:color/transparent"
android:dividerHeight="0dp" 

How do I get length of list of lists in Java?

Just use

int listCount = data.size();

That tells you how many lists there are (assuming none are null). If you want to find out how many strings there are, you'll need to iterate:

int total = 0;
for (List<String> sublist : data) {
    // TODO: Null checking
    total += sublist.size();
}
// total is now the total number of strings

How to get/generate the create statement for an existing hive table?

Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later:

step 1)
create a .sh file with the below content, say hive_table_ddl.sh

#!/bin/bash
rm -f tableNames.txt
rm -f HiveTableDDL.txt
hive -e "use $1; show tables;" > tableNames.txt  
wait
cat tableNames.txt |while read LINE
   do
   hive -e "use $1;show create table $LINE;" >>HiveTableDDL.txt
   echo  -e "\n" >> HiveTableDDL.txt
   done
rm -f tableNames.txt
echo "Table DDL generated"

step 2)

Run the above shell script by passing 'db name' as paramanter

>bash hive_table_dd.sh <<databasename>>

output :

All the create table statements of your DB will be written into the HiveTableDDL.txt

WindowsError: [Error 126] The specified module could not be found

There is a promising answer at Problem updating bokeh: [WinError 126] The specified module could not be found.

It hints at https://github.com/conda/conda/issues/9313.

There, you find:

It's a library load issue. More details at github.com/conda/conda/issues/8836 You probably have a broken conda right now. You can use a standalone conda from repo.anaconda.com/pkgs/misc/conda-execs to repair it: standalone-conda.exe update -p C:\ProgramData\Anaconda3 conda-package-handling You should get version 1.6.0, and the problems should go away.

Thus, it might simply be a conda issue. Reinstalling standalone conda might repair the error. Please comment whoever can confirm this.

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

By using collation or casting to binary, like this:

SELECT *
FROM Users
WHERE   
    Username = @Username COLLATE SQL_Latin1_General_CP1_CS_AS
    AND Password = @Password COLLATE SQL_Latin1_General_CP1_CS_AS
    AND Username = @Username 
    AND Password = @Password 

The duplication of username/password exists to give the engine the possibility of using indexes. The collation above is a Case Sensitive collation, change to the one you need if necessary.

The second, casting to binary, could be done like this:

SELECT *
FROM Users
WHERE   
    CAST(Username as varbinary(100)) = CAST(@Username as varbinary))
    AND CAST(Password as varbinary(100)) = CAST(@Password as varbinary(100))
    AND Username = @Username 
    AND Password = @Password 

How to implement onBackPressed() in Fragments?

According to the AndroidX release notes, androidx.activity 1.0.0-alpha01 is released and introduces ComponentActivity, a new base class of the existing FragmentActivity and AppCompatActivity. And this release brings us a new feature:

You can now register an OnBackPressedCallback via addOnBackPressedCallback to receive onBackPressed() callbacks without needing to override the method in your activity.

Function or sub to add new row and data to table

Minor variation on Geoff's answer.

New Data in Array:

Sub AddDataRow(tableName As String, NewData As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
    Next col
End Sub

New Data in Horizontal Range:

Sub AddDataRow(tableName As String, NewData As Range)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last table row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Copy NewData to new table record
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    lastRow.Value = NewData.Value
End Sub

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

How to stop INFO messages displaying on spark console?

You set disable the Logs by setting its level to OFF as follows:

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

or edit log file and set log level to off by just changing the following property:

log4j.rootCategory=OFF, console

How do I write a RGB color value in JavaScript?

Here's a simple function that creates a CSS color string from RGB values ranging from 0 to 255:

function rgb(r, g, b){
  return "rgb("+r+","+g+","+b+")";
}

Alternatively (to create fewer string objects), you could use array join():

function rgb(r, g, b){
  return ["rgb(",r,",",g,",",b,")"].join("");
}

The above functions will only work properly if (r, g, and b) are integers between 0 and 255. If they are not integers, the color system will treat them as in the range from 0 to 1. To account for non-integer numbers, use the following:

function rgb(r, g, b){
  r = Math.floor(r);
  g = Math.floor(g);
  b = Math.floor(b);
  return ["rgb(",r,",",g,",",b,")"].join("");
}

You could also use ES6 language features:

const rgb = (r, g, b) => 
  `rgb(${Math.floor(r)},${Math.floor(g)},${Math.floor(b)})`;

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

How can I override the OnBeforeUnload dialog and replace it with my own?

1) Use onbeforeunload, not onunload.

2) The important thing is to avoid executing a return statement. I don't mean, by this, to avoid returning from your handler. You return all right, but you do it by ensuring that you reach the end of the function and DO NOT execute a return statement. Under these conditions the built-in standard dialog does not occur.

3) You can, if you use onbeforeunload, run an ajax call in your unbeforeunload handler to tidy up on the server, but it must be a synchronous one, and you have to wait for and handle the reply in your onbeforeunload handler (still respecting condition (2) above). I do this and it works fine. If you do a synchronous ajax call, everything is held up until the response comes back. If you do an asynchronous one, thinking that you don't care about the reply from the server, the page unload continues and your ajax call is aborted by this process - including a remote script if it's running.

Remove rows not .isin('X')

All you have to do is create a subset of your dataframe where the isin method evaluates to False:

df = df[df['Column Name'].isin(['Value']) == False]

Can jQuery get all CSS styles associated with an element?

@marknadal's solution wasn't grabbing hyphenated properties for me (e.g. max-width), but changing the first for loop in css2json() made it work, and I suspect performs fewer iterations:

for (var i = 0; i < css.length; i += 1) {
    s[css[i]] = css.getPropertyValue(css[i]);
}

Loops via length rather than in, retrieves via getPropertyValue() rather than toLowerCase().

Get user's non-truncated Active Directory groups from command line

A little stale post, but I figured what the heck. Does "whoami" meet your needs?

I just found out about it today (from the same Google search that brought me here, in fact). Windows has had a whoami tool since XP (part of an add on toolkit) and has been built-in since Vista.

whoami /groups

Lists all the AD groups for the currently logged-on user. I believe it does require you to be logged on AS that user, though, so this won't help if your use case requires the ability to run the command to look at another user.

Group names only:

whoami /groups /fo list |findstr /c:"Group Name:"

Changing default encoding of Python?

Here is a simpler method (hack) that gives you back the setdefaultencoding() function that was deleted from sys:

import sys
# sys.setdefaultencoding() does not exist, here!
reload(sys)  # Reload does the trick!
sys.setdefaultencoding('UTF8')

(Note for Python 3.4+: reload() is in the importlib library.)

This is not a safe thing to do, though: this is obviously a hack, since sys.setdefaultencoding() is purposely removed from sys when Python starts. Reenabling it and changing the default encoding can break code that relies on ASCII being the default (this code can be third-party, which would generally make fixing it impossible or dangerous).

phpinfo() is not working on my CentOS server

This happened to me as well. The fix was wrapping it in HTML tags. Then I saved the file as /var/www/html/info.php and ran http://localhost/info.php in the browser. That's it.

<html>
    <body>
        <?php
            phpinfo();
        ?>
    </body>
</html>

Find and replace in file and overwrite file doesn't work, it empties the file

When the shell sees > index.html in the command line it opens the file index.html for writing, wiping off all its previous contents.

To fix this you need to pass the -i option to sed to make the changes inline and create a backup of the original file before it does the changes in-place:

sed -i.bak s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html

Without the .bak the command will fail on some platforms, such as Mac OSX.

How to animate button in android?


Class.Java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_with_the_button);

    final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.milkshake);
    Button myButton = (Button) findViewById(R.id.new_game_btn);
    myButton.setAnimation(myAnim);
}

For onClick of the Button

myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        v.startAnimation(myAnim);
    }
});

Create the anim folder in res directory

Right click on, res -> New -> Directory

Name the new Directory anim

create a new xml file name it milkshake


milkshake.xml

<?xml version="1.0" encoding="utf-8"?>
    <rotate xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="100"
        android:fromDegrees="-5"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatCount="10"
        android:repeatMode="reverse"
        android:toDegrees="5" />

multiple figure in latex with captions

Look at the Subfloats section of http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions.

\begin{figure}[htp]
  \centering
  \label{figur}\caption{equation...}

  \subfloat[Subcaption 1]{\label{figur:1}\includegraphics[width=60mm]{explicit3185.eps}}
  \subfloat[Subcaption 2]{\label{figur:2}\includegraphics[width=60mm]{explicit3183.eps}}
  \\
  \subfloat[Subcaption 3]{\label{figur:3}\includegraphics[width=60mm]{explicit1501.eps}}
  \subfloat[Subcaption 4]{\label{figur:4}\includegraphics[width=60mm]{explicit23185.eps}}
  \\
  \subfloat[Subcaption 5]{\label{figur:5}\includegraphics[width=60mm]{explicit23183.eps}}
  \subfloat[Subcaption 6]{\label{figur:6}\includegraphics[width=60mm]{explicit21501.eps}}

\end{figure}

Initializing data.frames()

I always just convert a matrix:

x <- as.data.frame(matrix(nrow = 100, ncol = 10))

no overload for matches delegate 'system.eventhandler'

You need to wrap button click handler to match the pattern

public void klik(object sender, EventArgs e)

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

def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
    return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])

ref: http://code.activestate.com/recipes/65212/

Please be aware that this may lead to

RuntimeError: maximum recursion depth exceeded in cmp

for very big integers.

Convert pandas DataFrame into list of lists

EDIT: as_matrix is deprecated since version 0.23.0

You can use the built in values or to_numpy (recommended option) method on the dataframe:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist():

df.to_numpy().tolist()

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

How can I send an HTTP POST request to a server from Excel using VBA?

To complete the response of the other users:

For this I have created an "WinHttp.WinHttpRequest.5.1" object.

Send a post request with some data from Excel using VBA:

Dim LoginRequest As Object
Set LoginRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
LoginRequest.Open "POST", "http://...", False
LoginRequest.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
LoginRequest.send ("key1=value1&key2=value2")

Send a get request with token authentication from Excel using VBA:

Dim TCRequestItem As Object
Set TCRequestItem = CreateObject("WinHttp.WinHttpRequest.5.1")
TCRequestItem.Open "GET", "http://...", False
TCRequestItem.setRequestHeader "Content-Type", "application/xml"
TCRequestItem.setRequestHeader "Accept", "application/xml"
TCRequestItem.setRequestHeader "Authorization", "Bearer " & token
TCRequestItem.send

pip not working in Python Installation in Windows 10

It's a really weird issue and I am posting this after wasting my 2 hours.

You installed Python and added it to PATH. You've checked it too(like 64-bit etc). Everything should work but it is not.

what you didn't do is a terminal/cmd restart

restart your terminal and everything would work like a charm.

I Hope, it helped/might help others.

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

Just as an FYI - "best" questions aren't the norm at SO, but I will give you a list of options, just as a service.

OK then. These two are the ones I used:

Komodo Edit

Aptana Studio 3

and then there is always Eclipse.

*UPDATE 20 March 2013 *

Well, Sublime Text 2 is the one to heavily consider. Heavily.

Java sending and receiving file (byte[]) over sockets

Adding up on EJP's answer; use this for more fluidity. Make sure you don't put his code inside a bigger try catch with more code between the .read and the catch block, it may return an exception and jump all the way to the outer catch block, safest bet is to place EJPS's while loop inside a try catch, and then continue the code after it, like:

int count;
byte[] bytes = new byte[4096];
try {
    while ((count = is.read(bytes)) > 0) {
        System.out.println(count);
        bos.write(bytes, 0, count);
    }
} catch ( Exception e )
{
    //It will land here....
}
// Then continue from here

EDIT: ^This happened to me cuz I didn't realize you need to put socket.shutDownOutput() if it's a client-to-server stream!

Hope this post solves any of your issues

Checkbox Check Event Listener

Since I don't see the jQuery tag in the OP, here is a javascript only option :

document.addEventListener("DOMContentLoaded", function (event) {
    var _selector = document.querySelector('input[name=myCheckbox]');
    _selector.addEventListener('change', function (event) {
        if (_selector.checked) {
            // do something if checked
        } else {
            // do something else otherwise
        }
    });
});

See JSFIDDLE

JOIN two SELECT statement results

Try something like this:

SELECT 
* 
FROM
(SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1 
INNER JOIN
(SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON t1.ks = t2.ks

How to sort an ArrayList in Java

Use a Comparator like this:

List<Fruit> fruits= new ArrayList<Fruit>();

Fruit fruit;
for(int i = 0; i < 100; i++)
{
  fruit = new Fruit();
  fruit.setname(...);
  fruits.add(fruit);
}

// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
        @Override
        public int compare(Fruit fruit2, Fruit fruit1)
        {

            return  fruit1.fruitName.compareTo(fruit2.fruitName);
        }
    });

Now your fruits list is sorted based on fruitName.

Loop through all nested dictionary values?

Here's a modified version of Fred Foo's answer for Python 2. In the original response, only the deepest level of nesting is output. If you output the keys as lists, you can keep the keys for all levels, although to reference them you need to reference a list of lists.

Here's the function:

def NestIter(nested):
    for key, value in nested.iteritems():
        if isinstance(value, collections.Mapping):
            for inner_key, inner_value in NestIter(value):
                yield [key, inner_key], inner_value
        else:
            yield [key],value

To reference the keys:

for keys, vals in mynested: 
    print(mynested[keys[0]][keys[1][0]][keys[1][1][0]])

for a three-level dictionary.

You need to know the number of levels before to access multiple keys and the number of levels should be constant (it may be possible to add a small bit of script to check the number of nesting levels when iterating through values, but I haven't yet looked at this).

Using Cookie in Asp.Net Mvc 4

Try using Response.SetCookie(), because Response.Cookies.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.

Android Intent Cannot resolve constructor

You may use this:

Intent intent = new Intent(getApplicationContext(), ClassName.class);

Create folder in Android

If you are trying to make more than just one folder on the root of the sdcard, ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"

then instead of folder.mkdir() you would use folder.mkdirs()

I've made this mistake in the past & I took forever to figure it out.

ExecuteNonQuery: Connection property has not been initialized.

just try this..

you need to open the connection using connection.open() on the SqlCommand.Connection object before executing ExecuteNonQuery()

Convert a matrix to a 1 dimensional array

Simple and fast since a 1d array is essentially a vector

vector <- array[1:length(array)]

Update .NET web service to use TLS 1.2

Add the following code before you instantiate your web service client:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Or for backward compatibility with TLS 1.1 and prior:

System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; 

How do I mock an autowired @Value field in Spring with Mockito?

I'd like to suggest a related solution, which is to pass the @Value-annotated fields as parameters to the constructor, instead of using the ReflectionTestUtils class.

Instead of this:

public class Foo {

    @Value("${foo}")
    private String foo;
}

and

public class FooTest {

    @InjectMocks
    private Foo foo;

    @Before
    public void setUp() {
        ReflectionTestUtils.setField(Foo.class, "foo", "foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Do this:

public class Foo {

    private String foo;

    public Foo(@Value("${foo}") String foo) {
        this.foo = foo;
    }
}

and

public class FooTest {

    private Foo foo;

    @Before
    public void setUp() {
        foo = new Foo("foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Benefits of this approach: 1) we can instantiate the Foo class without a dependency container (it's just a constructor), and 2) we're not coupling our test to our implementation details (reflection ties us to the field name using a string, which could cause a problem if we change the field name).

How do I use HTML as the view engine in Express?

To make the render engine accept html instead of jade you can follow the following steps;

Install consolidate and swig to your directory.

 npm install consolidate
 npm install swig

add following lines to your app.js file

var cons = require('consolidate');

// view engine setup
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

add your view templates as .html inside “views” folder. Restart you node server and start the app in the browser.

This should work

Setting an environment variable before a command in Bash is not working for the second command in a pipe

You can also use eval:

FOO=bar eval 'somecommand someargs | somecommand2'

Since this answer with eval doesn't seem to please everyone, let me clarify something: when used as written, with the single quotes, it is perfectly safe. It is good as it will not launch an external process (like the accepted answer) nor will it execute the commands in an extra subshell (like the other answer).

As we get a few regular views, it's probably good to give an alternative to eval that will please everyone, and has all the benefits (and perhaps even more!) of this quick eval “trick”. Just use a function! Define a function with all your commands:

mypipe() {
    somecommand someargs | somecommand2
}

and execute it with your environment variables like this:

FOO=bar mypipe

What does the NS prefix mean?

When NeXT were defining the NextStep API (as opposed to the NEXTSTEP operating system), they used the prefix NX, as in NXConstantString. When they were writing the OpenStep specification with Sun (not to be confused with the OPENSTEP operating system) they used the NS prefix, as in NSObject.

Error TF30063: You are not authorized to access ... \DefaultCollection

Make sure that Windows Authentication hasn't been disabled for the Website / Application within IIS.

I'm not sure HOW this happened, but I did uninstall Hyper-V today to be able to install VMWare Player and then re-install Hyper-V

Reenabling this allowed everything to work again.

enter image description here

Testing javascript with Mocha - how can I use console.log to debug a test?

If you are testing asynchronous code, you need to make sure to place done() in the callback of that asynchronous code. I had that issue when testing http requests to a REST API.

Load vs. Stress testing

Load testing :- Load testing is meant to test the system by constantly and steadily increasing the load on the system till the time it reaches the threshold limit.

Stress Testing :- Under stress testing, various activities to overload the existing resources with excess jobs are carried out in an attempt to break the system down.

The basic difference is as under

click here to see the exact difference

Difference between angle bracket < > and double quotes " " while including header files in C++?

When you use angle brackets, the compiler searches for the file in the include path list. When you use double quotes, it first searches the current directory (i.e. the directory where the module being compiled is) and only then it'll search the include path list.

So, by convention, you use the angle brackets for standard includes and the double quotes for everything else. This ensures that in the (not recommended) case in which you have a local header with the same name as a standard header, the right one will be chosen in each case.

Learning Regular Expressions

The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.

If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.

Start simple

Conceptually, the simplest regular expressions are literal characters. The pattern N matches the character 'N'.

Regular expressions next to each other match sequences. For example, the pattern Nick matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.

If you've ever used grep on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re in grep refers to regular expressions.)

Order from the menu

Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c] matches either 'a' or 'b' or 'c'.

The pattern . is special: rather than matching a literal dot only, it matches any character. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...].

Think of character classes as menus: pick just one.

Helpful shortcuts

Using . can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]. Digits are a frequent match target, so you could instead use the shortcut \d. Others are \s (whitespace) and \w (word characters: alphanumerics or underscore).

The uppercased variants are their complements, so \S matches any non-whitespace character, for example.

Once is not enough

From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c matches 'abc' or 'ac' because the ? quantifier makes the subpattern it modifies optional. Other quantifiers are

  • * (zero or more times)
  • + (one or more times)
  • {n} (exactly n times)
  • {n,} (at least n times)
  • {n,m} (at least n times but no more than m times)

Putting some of these blocks together, the pattern [Nn]*ick matches all of

  • ick
  • Nick
  • nick
  • Nnick
  • nNick
  • nnick
  • (and so on)

The first match demonstrates an important lesson: * always succeeds! Any pattern can match zero times.

A few other useful examples:

  • [0-9]+ (and its equivalent \d+) matches any non-negative integer
  • \d{4}-\d{2}-\d{2} matches dates formatted like 2019-01-01

Grouping

A quantifier modifies the pattern to its immediate left. You might expect 0abc+0 to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c. This means 0abc+0 matches '0abc0', '0abcc0', '0abccc0', and so on.

To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr.

Alternation

Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |, e.g., (Nick|nick).

For another example, you could equivalently write [a-c] as a|b|c, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.

Escaping

Although some characters match themselves, others have special meanings. The pattern \d+ doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+. A backslash removes the special meaning from the following character.

Greediness

Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.

For example, say the input is

"Hello," she said, "How are you?"

You might expect ".+" to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.

To switch from greedy to what you might think of as cautious, add an extra ? to the quantifier. Now you understand how \((.+?)\), the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.

If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.

(As to your confusion, I don't know of any regular-expression dialect where ((.+?)) would do the same thing. I suspect something got lost in transmission somewhere along the way.)

Anchors

Use the special pattern ^ to match only at the beginning of your input and $ to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.

Say you want to match comments of the form

-- This is a comment --

you'd write ^--\s+(.+)\s+--$.

Build your own

Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.

Tools for writing and debugging regexes:

Books

Free resources

Footnote

†: The statement above that . matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n", but in practice you rarely expect a pattern such as .+ to cross a newline boundary. Perl regexes have a /s switch and Java Pattern.DOTALL, for example, to make . match any character at all. For languages that don't have such a feature, you can use something like [\s\S] to match "any whitespace or any non-whitespace", in other words anything.

Resource from src/main/resources not found after building with maven

Once after we build the jar will have the resource files under BOOT-INF/classes or target/classes folder, which is in classpath, use the below method and pass the file under the src/main/resources as method call getAbsolutePath("certs/uat_staging_private.ppk"), even we can place this method in Utility class and the calling Thread instance will be taken to load the ClassLoader to get the resource from class path.

 public String getAbsolutePath(String fileName) throws IOException {
      return Thread.currentThread().getContextClassLoader().getResource(fileName).getFile();
  }

enter image description here enter image description here

we can add the below tag to tag in pom.xml to include these resource files to build target/classes folder

<resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.ppk</include>
            </includes>
        </resource>
</resources>

Convert DataTable to List<T>

Assuming your DataRows inherit from your own type, say MyDataRowType, this should work:

List<MyDataRowType> list = new List<MyDataRowType>();

foreach(DataRow row in dataTable.Rows)
{
    list.Add((MyDataRowType)row);
}

This is assuming, as you said in a comment, that you're using .NET 2.0 and don't have access to the LINQ extension methods.

How to save a figure in MATLAB from the command line?

These days (May 2017), MATLAB still suffer from a robust method to export figures, especially in GNU/Linux systems when exporting figures in batch mode. The best option is to use the extension export_fig

Just download the source code from Github and use it:

plot(cos(linspace(0, 7, 1000)));
set(gcf, 'Position', [100 100 150 150]);
export_fig test2.png

Set transparent background using ImageMagick and commandline prompt

This works for me:

convert original.png -fuzz 10% -transparent white transparent.png

where the smaller the fuzz %, the closer to true white or conversely, the larger the %, the more variation from white is allowed to become transparent

Fatal error: [] operator not supported for strings

You have probably defined $name, $date, $text or $date2 to be a string, like:

$name = 'String';

Then if you treat it like an array it will give that fatal error:

$name[] = 'new value'; // fatal error

To solve your problem just add the following code at the beginning of the loop:

$name = array();
$date = array();
$text = array();
$date2 = array();

This will reset their value to array and then you'll able to use them as arrays.

apache server reached MaxClients setting, consider raising the MaxClients setting

When you use Apache with mod_php apache is enforced in prefork mode, and not worker. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).

So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :

StartServers       20
MinSpareServers    5
MaxSpareServers    10
MaxClients         1024
MaxRequestsPerChild  0

This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.

See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.

Now you set 1024 MaxClients. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.

So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:

<IfModule prefork.c>
  StartServers       12
  MinSpareServers    12
  MaxSpareServers    12
  MaxClients         12
  MaxRequestsPerChild  300
</IfModule>

That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300 means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the ListenBacklog queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).

And yes, that means you cannot handle more than 12 parallel requests.

If you want to handle more requests:

  • buy some more RAM
  • try to use apache in worker mode, but remove mod_php and use php as a parallel daemon with his own pooler settings (this is called php-fpm), connect it with fastcgi. Note that you will certainly need to buy some RAM to allow a big number of parallel php-fpm process, but maybe less than with mod_php
  • Reduce the time spent in your php process. From your cacti graphs you have to potential problems: a real traffic peak around 11:25-11:30 or some php code getting very slow. Fast requests will reduce the number of parallel requests.

If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?

And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.

Update: About internal dummy connections (if it's your problem, but maybe not).

Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.

If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:

  RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
  RewriteRule .* - [F,L]

Update:

Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.

Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l or apache2 -l on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:

<IfModule worker.c>
  StartServers           3
  MaxClients           500
  MinSpareThreads       75
  MaxSpareThreads      250 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:

<IfModule worker.c>
  StartServers           2
  MaxClients           250
  MinSpareThreads       50
  MaxSpareThreads      150 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

Remove non-ASCII characters from CSV

I appreciate the tips I found on this site.

But, on my Windows 10, I had to use double quotes for this to work ...

sed -i "s/[\d128-\d255]//g" FILENAME

Noticed these things ...

  1. For FILENAME the entire path\name needs to be quoted This didn't work -- %TEMP%\"FILENAME" This did -- %TEMP%\FILENAME"

  2. sed leaves behind temp files in the current directory, named sed*

TokenMismatchException in VerifyCsrfToken.php Line 67

Have you checked your hidden input field where the token is generated?

If it is null then your token is not returned by csrf_token function.You have to write your route that renders the form inside the middleware group provide by laravel as follows:

  Route::group(['middleware' => 'web'], function () {
Route::get('/', function () {
    return view('welcome');
});

Here root route contains my sign up page which requires csrf token. This token is managed by laravel 5.2.7 inside 'web' middleware in kernel.php.

Do not forget to insert {!! csrf_field() !!} inside the form..

.htaccess not working on localhost with XAMPP

Try

<IfModule mod_rewrite.so>
...
...
...
</IfModule>

instead of <IfModule mod_rewrite.c>

SQL Server SELECT LAST N Rows

DECLARE @MYVAR  NVARCHAR(100)
DECLARE @step  int
SET @step = 0;


DECLARE MYTESTCURSOR CURSOR
DYNAMIC 
FOR
SELECT col FROM [dbo].[table]
OPEN MYTESTCURSOR
FETCH LAST FROM MYTESTCURSOR INTO @MYVAR
print @MYVAR;


WHILE @step < 10
BEGIN   
    FETCH PRIOR FROM MYTESTCURSOR INTO @MYVAR
        print @MYVAR;
        SET @step = @step + 1;
END   
CLOSE MYTESTCURSOR
DEALLOCATE MYTESTCURSOR

Can't concat bytes to str

f.write(plaintext)
f.write("\n".encode("utf-8"))

Is it possible in Java to access private fields via reflection

Yes it is possible.

You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:

Field privateField = Test.class.getDeclaredField("str");

Additionally, you need to set this Field to be accessible, if you want to access a private field:

privateField.setAccessible(true);

Once that's done, you can use the get method on the Field instance, to access the value of the str field.

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

_x000D_
_x000D_
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
        </div>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Array copy values to keys in PHP

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So I solved it like this:

foreach($array as $key => $val) {
    $new_array[$val]=$val;
}

Postgresql GROUP_CONCAT equivalent?

Try like this:

select field1, array_to_string(array_agg(field2), ',')
from table1
group by field1;

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

For windows I found that when i loaded the filles(jd2xsx.dll calls & ftd2xx.dll) into the windowws/system32 folder this resolved the issues. I then had an issue with my newer fd2xx.dll having to do with parameters which is why I had to load the older version of this dll. I will have to ferrit this out later.

Note: the jd2xsx.dll calls the ftd2xx.dll so just setting the path for the jd2xx.dll might not work.

Capturing window.onbeforeunload

Yes what everybody says above.

For your immediate situation, instead of onChange, you can use onInput, new in html5. The input event is the same, but it'll fire upon every keystroke, regardless of the focus. Also works on selects and all the rest just like onChange.

How do you configure HttpOnly cookies in tomcat / java webapps?

I Found in OWASP

<session-config>
  <cookie-config>
    <http-only>true</http-only>
  </cookie-config>
</session-config>

this is also fix for "httponlycookies in config" security issue

Contain an image within a div?

You have to style the image like this

#container img{width:100%;}

and the container with hidden overflow:

#container{width:250px; height:250px; overflow:hidden; border:1px solid #000;} 

How to enable C++11 in Qt Creator?

According to this site add

CONFIG += c++11

to your .pro file (see at the bottom of that web page). It requires Qt 5.


The other answers, suggesting

QMAKE_CXXFLAGS += -std=c++11 (or QMAKE_CXXFLAGS += -std=c++0x)

also work with Qt 4.8 and gcc / clang.

How to copy file from HDFS to the local file system

bin/hadoop fs -put /localfs/destination/path /hdfs/source/path 

What's the yield keyword in JavaScript?

Yeild keyword in javaScript function makes it generator,

what is generator in javaScript?

A generator is a function that produces a sequence of results instead of a single value, i.e you generate ?a series of values

Meaning generators helps us work asynchronously with the help iterators, Oh now what the hack iterators are? really?

Iterators are mean through which we are able to access items one at a time

from where iterator help us accessing item one at a time? it help us accessing items through generator functions,

generator functions are those in which we use yeild keyword, yield keyword help us in pausing and resuming execution of function

here is quick example

function *getMeDrink() {

    let question1 = yield 'soda or beer' // execution will pause here because of yield

 if (question1 == 'soda') {

            return 'here you get your soda'

    }

    if (question1 == 'beer') {

        let question2 = yield 'Whats your age' // execution will pause here because of yield

        if (question2 > 18) {

            return "ok you are eligible for it"

        } else {

            return 'Shhhh!!!!'

        }
    }
}


let _getMeDrink = getMeDrink() // initialize it

_getMeDrink.next().value  // "soda or beer"

_getMeDrink.next('beer').value  // "Whats your age"

_getMeDrink.next('20').value  // "ok you are eligible for it"

_getMeDrink.next().value // undefined

let me brifly explain what is going on

you noticed execution is being paused at each yeild keyword and we are able to access first yield with help of iterator .next()

this iterates to all yield keywords one at a time and then returns undefined when there is no more yield keywords left in simple words you can say yield keyword is break point where function each time pauses and only resume when call it using iterator

for our case: _getMeDrink.next() this is example of iterator that is helping us accessing each break point in function

Example of Generators: async/await

if you see implementation of async/await you will see generator functions & promises are used to make async/await work

please point out any suggestions is welcomed

How do I convert datetime.timedelta to minutes, hours in Python?

There is no need for custom helper functions if all we need is to print the string of the form [D day[s], ][H]H:MM:SS[.UUUUUU]. timedelta object supports str() operation that will do this. It works even in Python 2.6.

>>> from datetime import timedelta
>>> timedelta(seconds=90136)
datetime.timedelta(1, 3736)
>>> str(timedelta(seconds=90136))
'1 day, 1:02:16'

Xcode process launch failed: Security

Hey so the accepted answer works, except if you need to debug the initial launch of the app. However I think that answer is more of a work around, and not an actual solution. From my understanding this message occurs when you have some weirdness in your provisioning profile / cert setup so make extra sure everything is in tip-top shape in that dept. before ramming your head against the wall repeatedly.

What worked for me was as follows from the apple docs:

Provisioning Profiles Known Issue If you have upgraded to the GM seed from other betas you may see your apps crashing due to provisioning profile issues.

Workaround:

  1. Connect the device via USB to your Mac

  2. Launch Xcode Choose Window ->Devices

  3. Right click on the device in left column, choose "Show Provisioning Profiles"

  4. Click on the provisioning profile in question

  5. Press the "-" button Continue to removing all affected profiles.

  6. Re-install the app

Make sure you right click on the image of the device not the name of the device or you won't see the provisioning profiles option. I restored my new phone from an old backup and there was a lot of cruft hanging around, i also had 2 different dev. certs active (not sure why) but i deleted one, made a new profile got rid of all the profiles on device and it worked.

Hope this helps someone else.

How are "mvn clean package" and "mvn clean install" different?

package will generate Jar/war as per POM file. install will install generated jar file to the local repository for other dependencies if any.

install phase comes after package phase

Oracle DB : java.sql.SQLException: Closed Connection

You have to validate the connection.

If you use Oracle it is likely that you use Oracle´s Universal Connection Pool. The following assumes that you do so.

The easiest way to validate the connection is to tell Oracle that the connection must be validated while borrowing it. This can be done with

pool.setValidateConnectionOnBorrow(true);

But it works only if you hold the connection for a short period. If you borrow the connection for a longer time, it is likely that the connection gets broken while you hold it. In that case you have to validate the connection explicitly with

if (connection == null || !((ValidConnection) connection).isValid())

See the Oracle documentation for further details.

How to condense if/else into one line in Python?

Only for using as a value:

x = 3 if a==2 else 0

or

return 3 if a==2 else 0

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Format Date output in JSF

If you use OmniFaces you can also use it's EL functions like of:formatDate() to format Date objects. You would use it like this:

<h:outputText value="#{of:formatDate(someBean.dateField, 'dd.MM.yyyy HH:mm')}" />

This way you can not only use it for output but also to pass it on to other JSF components.

What is the .idea folder?

There is no problem in deleting this. It's not only the WebStorm IDE creating this file, but also PhpStorm and all other of JetBrains' IDEs.

It is safe to delete it but if your project is from GitLab or GitHub then you will see a warning.

CSS styling in Django forms

Didn't see this one really...

https://docs.djangoproject.com/en/1.8/ref/forms/api/#more-granular-output

More granular output

The as_p(), as_ul() and as_table() methods are simply shortcuts for lazy developers – they’re not the only way a form object can be displayed.

class BoundField Used to display HTML or access attributes for a single field of a Form instance.

The str() (unicode on Python 2) method of this object displays the HTML for this field.

To retrieve a single BoundField, use dictionary lookup syntax on your form using the field’s name as the key:

>>> form = ContactForm()
>>> print(form['subject'])
<input id="id_subject" type="text" name="subject" maxlength="100" />

To retrieve all BoundField objects, iterate the form:

>>> form = ContactForm()
>>> for boundfield in form: print(boundfield)
<input id="id_subject" type="text" name="subject" maxlength="100" />
<input type="text" name="message" id="id_message" />
<input type="email" name="sender" id="id_sender" />
<input type="checkbox" name="cc_myself" id="id_cc_myself" />

The field-specific output honors the form object’s auto_id setting:

>>> f = ContactForm(auto_id=False)
>>> print(f['message'])
<input type="text" name="message" />
>>> f = ContactForm(auto_id='id_%s')
>>> print(f['message'])
<input type="text" name="message" id="id_message" />

Change the Arrow buttons in Slick slider

Content property of pseudo element :before accepts images too. In slick-theme.css change:

_x000D_
_x000D_
// change_x000D_
$slick-prev-character: "?" !default; _x000D_
_x000D_
// to_x000D_
$slick-prev-character: url('image-prev.png');_x000D_
_x000D_
// and _x000D_
$slick-next-character: "?" !default;_x000D_
_x000D_
// to _x000D_
$slick-next-character: url('image-next.jpg');
_x000D_
_x000D_
_x000D_

or directly change the content property on slick-prev:before and slick-next:before

_x000D_
_x000D_
.slick-prev {_x000D_
    left: -25px;_x000D_
    [dir="rtl"] & {_x000D_
        left: auto;_x000D_
        right: -25px;_x000D_
    }_x000D_
    &:before {_x000D_
        content: url('image-prev.jpg'); // <<<<<<<<_x000D_
        [dir="rtl"] & {_x000D_
            content: url('image-next.jpg'); // <<<<<<<<_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
.slick-next {_x000D_
    right: -25px;_x000D_
    [dir="rtl"] & {_x000D_
        left: -25px;_x000D_
        right: auto;_x000D_
    }_x000D_
    &:before {_x000D_
        content: url('image-next.jpg'); // <<<<<<<<_x000D_
        [dir="rtl"] & {_x000D_
            content: url('image-prev.jpg'); // <<<<<<<<_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How do you post to the wall on a facebook page (not profile)

If your blog outputs an RSS feed you can use Facebook's "RSS Graffiti" application to post that feed to your wall in Facebook. There are other RSS Facebook apps as well; just search "Facebook for RSS apps"...

Allow scroll but hide scrollbar

Try this:

HTML:

<div id="container">
    <div id="content">
        // Content here
    </div>
</div>

CSS:

#container{
    height: 100%;
    width: 100%;
    overflow: hidden;
}

#content{
    width: 100%;
    height: 99%;
    overflow: auto;
    padding-right: 15px;
}

html, body{
    height: 99%;
    overflow:hidden;
}

JSFiddle Demo

Tested on FF and Safari.

How do I add space between items in an ASP.NET RadioButtonList

Even easier...

ASP.NET

<asp:RadioButtonList runat="server" ID="MyRadioButtonList" RepeatDirection="Horizontal" CssClass="FormatRadioButtonList"> ...

CSS

.FormatRadioButtonList label
{
  margin-right: 15px;
}

Strange Jackson exception being thrown when serializing Hibernate object

I tried @JsonDetect and

@JsonIgnoreProperties(value = { "handler", "hibernateLazyInitializer" })

Neither of them worked for me. Using a third-party module seemed like a lot of work to me. So I just tried making a get call on any property of the lazy object before passing to jackson for serlization. The working code snippet looked something like this :

@RequestMapping(value = "/authenticate", produces = "application/json; charset=utf-8")
    @ResponseBody
    @Transactional
    public Account authenticate(Principal principal) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) principal;
        LoggedInUserDetails loggedInUserDetails = (LoggedInUserDetails) usernamePasswordAuthenticationToken.getPrincipal();
        User user = userRepository.findOne(loggedInUserDetails.getUserId());
        Account account = user.getAccount();
        account.getFullName();      //Since, account is lazy giving it directly to jackson for serlization didn't worked & hence, this quick-fix.
        return account;
    }

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

You can try to bypass the SSL error by using http instead of https. Of course this is not optimal in terms of security, but if you are in a hurry it should do the trick:

pip install --index-url=http://pypi.python.org/simple/ linkchecker

Change Button color onClick

There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.

Your code could look like this:

<script>
    var count = 1;
    function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
            property.style.backgroundColor = "#FFFFFF"
            count = 1;        
        }
        else {
            property.style.backgroundColor = "#7FFF00"
            count = 0;
        }
    }
</script>

Hope this helps.

Convert NSData to String?

A simple way to convert arbitrary NSData to NSString is to base64 encode it.

NSString *base64EncodedKey = [keydata base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];

You can then store it into your database for reuse later. Just decode it back to NSData.

Convert IEnumerable to DataTable

There is nothing built in afaik, but building it yourself should be easy. I would do as you suggest and use reflection to obtain the properties and use them to create the columns of the table. Then I would step through each item in the IEnumerable and create a row for each. The only caveat is if your collection contains items of several types (say Person and Animal) then they may not have the same properties. But if you need to check for it depends on your use.

Android Device Chooser -- device not showing up

One possible reason is to check Android SDK Manager and install Google USB Driver in Extras folder if you have not installed it.

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this

SELECT IF(
      count(*) > 15,
      'good',
      IF(
          count(*) > 10,
          'average',
          'poor'
        ) 
      ) as data_count 
      FROM companies

Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.

How to print a string in C++

You can't call "printf" with a std::string in parameter. The "%s" is designed for C-style string : char* or char []. In C++ you can do like that :

#include <iostream>
std::cout << YourString << std::endl;

If you absolutely want to use printf, you can use the "c_str()" method that give a char* representation of your string.

printf("%s\n",YourString.c_str())

Converting a generic list to a CSV string

You can create an extension method that you can call on any IEnumerable:

public static string JoinStrings<T>(
    this IEnumerable<T> values, string separator)
{
    var stringValues = values.Select(item =>
        (item == null ? string.Empty : item.ToString()));
    return string.Join(separator, stringValues.ToArray());
}

Then you can just call the method on the original list:

string commaSeparated = myList.JoinStrings(", ");

How do I link to part of a page? (hash?)

You use an anchor and a hash. For example:

Target of the Link:

 <a name="name_of_target">Content</a>

Link to the Target:

 <a href="#name_of_target">Link Text</a>

Or, if linking from a different page:

 <a href="http://path/to/page/#name_of_target">Link Text</a>

Is SMTP based on TCP or UDP?

In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.

As defined in RFC 821, RFC 2821, and RFC 5321:

SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.

In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.

In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.


The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.

Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.

Add new column with foreign key constraint in one command

You can do it like below in SQL Server

ALTER TABLE one
ADD two_id int foreign key
REFERENCES two(id)

Best way to work with dates in Android SQLite

1 -Exactly like StErMi said.

2 - Please read this: http://www.vogella.de/articles/AndroidSQLite/article.html

3 -

Cursor cursor = db.query(TABLE_NAME, new String[] {"_id", "title", "title_raw", "timestamp"}, 
                "//** YOUR REQUEST**//", null, null, "timestamp", null);

see here:

Query() in SQLiteDatabase

4 - see answer 3

UICollectionView auto scroll to cell at IndexPath

I totally agree with the above answer. The only thing is that for me the solution was set the code in viewDidAppear

viewDidAppear 
{
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];
}

When I used the viewWillAppear the scrolling didn't work.

Calculate distance between two latitude-longitude points? (Haversine formula)

I've created this small Javascript LatLng object, might be useful for somebody.

var latLng1 = new LatLng(5, 3);
var latLng2 = new LatLng(6, 7);
var distance = latLng1.distanceTo(latLng2); 

Code:

/**
 * latLng point
 * @param {Number} lat
 * @param {Number} lng
 * @returns {LatLng}
 * @constructor
 */
function LatLng(lat,lng) {
    this.lat = parseFloat(lat);
    this.lng = parseFloat(lng);

    this.__cache = {};
}

LatLng.prototype = {
    toString: function() {
        return [this.lat, this.lng].join(",");
    },

    /**
     * calculate distance in km to another latLng, with caching
     * @param {LatLng} latLng
     * @returns {Number} distance in km
     */
    distanceTo: function(latLng) {
        var cacheKey = latLng.toString();
        if(cacheKey in this.__cache) {
            return this.__cache[cacheKey];
        }

        // the fastest way to calculate the distance, according to this jsperf test;
        // http://jsperf.com/haversine-salvador/8
        // http://stackoverflow.com/questions/27928
        var deg2rad = 0.017453292519943295; // === Math.PI / 180
        var lat1 = this.lat * deg2rad;
        var lng1 = this.lng * deg2rad;
        var lat2 = latLng.lat * deg2rad;
        var lng2 = latLng.lng * deg2rad;
        var a = (
            (1 - Math.cos(lat2 - lat1)) +
            (1 - Math.cos(lng2 - lng1)) * Math.cos(lat1) * Math.cos(lat2)
            ) / 2;
        var distance = 12742 * Math.asin(Math.sqrt(a)); // Diameter of the earth in km (2 * 6371)

        // cache the distance
        this.__cache[cacheKey] = distance;

        return distance;
    }
};

Ruby convert Object to Hash

To do this without Rails, a clean way is to store attributes on a constant.

class Gift
  ATTRIBUTES = [:name, :price]
  attr_accessor(*ATTRIBUTES)
end

And then, to convert an instance of Gift to a Hash, you can:

class Gift
  ...
  def to_h
    ATTRIBUTES.each_with_object({}) do |attribute_name, memo|
      memo[attribute_name] = send(attribute_name)
    end
  end
end

This is a good way to do this because it will only include what you define on attr_accessor, and not every instance variable.

class Gift
  ATTRIBUTES = [:name, :price]
  attr_accessor(*ATTRIBUTES)

  def create_random_instance_variable
    @xyz = 123
  end

  def to_h
    ATTRIBUTES.each_with_object({}) do |attribute_name, memo|
      memo[attribute_name] = send(attribute_name)
    end
  end
end

g = Gift.new
g.name = "Foo"
g.price = 5.25
g.to_h
#=> {:name=>"Foo", :price=>5.25}

g.create_random_instance_variable
g.to_h
#=> {:name=>"Foo", :price=>5.25}

HTML/JavaScript: Simple form validation on submit

You have several errors there.

First, you have to return a value from the function in the HTML markup: <form name="ff1" method="post" onsubmit="return validateForm();">

Second, in the JSFiddle, you place the code inside onLoad which and then the form won't recognize it - and last you have to return true from the function if all validation is a success - I fixed some issues in the update:

https://jsfiddle.net/mj68cq0b/

function validateURL(url) {
    var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    return reurl.test(url);
}

function validateForm()
{
    // Validate URL
    var url = $("#frurl").val();
    if (validateURL(url)) { } else {
        alert("Please enter a valid URL, remember including http://");
        return false;
    }

    // Validate Title
    var title = $("#frtitle").val();
    if (title=="" || title==null) {
        alert("Please enter only alphanumeric values for your advertisement title");
        return false;
    }

    // Validate Email
    var email = $("#fremail").val();
    if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
        alert("Please enter a valid email");
        return false;
    }
  return true;
}

MIME types missing in IIS 7 for ASP.NET - 404.17

There are two reasons you might get this message:

  1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
  2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

Print Pdf in C#

It is possible to use Ghostscript to read PDF files and print them to a named printer.

BigDecimal to string

The BigDecimal can not be a double. you can use Int number. if you want to display exactly own number, you can use the String constructor of BigDecimal .

like this:

BigDecimal bd1 = new BigDecimal("10.0001");

now, you can display bd1 as 10.0001

So simple. GOOD LUCK.

What are advantages of Artificial Neural Networks over Support Vector Machines?

We should also consider that the SVM system can be applied directly to non-metric spaces, such as the set of labeled graphs or strings. In fact, the internal kernel function can be generalized properly to virtually any kind of input, provided that the positive definiteness requirement of the kernel is satisfied. On the other hand, to be able to use an ANN on a set of labeled graphs, explicit embedding procedures must be considered.

Set an environment variable in git bash

Creating a .bashrc file in your home directory also works. That way you don't have to copy your .bash_profile every time you install a new version of git bash.

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

Add custom headers to WebView resource requests - android

Maybe my response quite late, but it covers API below and above 21 level.

To add headers we should intercept every request and create new one with required headers.

So we need to override shouldInterceptRequest method called in both cases: 1. for API until level 21; 2. for API level 21+

    webView.setWebViewClient(new WebViewClient() {

        // Handle API until level 21
        @SuppressWarnings("deprecation")
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

            return getNewResponse(url);
        }

        // Handle API 21+
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

            String url = request.getUrl().toString();

            return getNewResponse(url);
        }

        private WebResourceResponse getNewResponse(String url) {

            try {
                OkHttpClient httpClient = new OkHttpClient();

                Request request = new Request.Builder()
                        .url(url.trim())
                        .addHeader("Authorization", "YOU_AUTH_KEY") // Example header
                        .addHeader("api-key", "YOUR_API_KEY") // Example header
                        .build();

                Response response = httpClient.newCall(request).execute();

                return new WebResourceResponse(
                        null,
                        response.header("content-encoding", "utf-8"),
                        response.body().byteStream()
                );

            } catch (Exception e) {
                return null;
            }

        }
   });

If response type should be processed you could change

        return new WebResourceResponse(
                null, // <- Change here
                response.header("content-encoding", "utf-8"),
                response.body().byteStream()
        );

to

        return new WebResourceResponse(
                getMimeType(url), // <- Change here
                response.header("content-encoding", "utf-8"),
                response.body().byteStream()
        );

and add method

        private String getMimeType(String url) {
            String type = null;
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);

            if (extension != null) {

                switch (extension) {
                    case "js":
                        return "text/javascript";
                    case "woff":
                        return "application/font-woff";
                    case "woff2":
                        return "application/font-woff2";
                    case "ttf":
                        return "application/x-font-ttf";
                    case "eot":
                        return "application/vnd.ms-fontobject";
                    case "svg":
                        return "image/svg+xml";
                }

                type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            }

            return type;
        }

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I had this exact issue running the simple .py code below:

import sys
print 'version is:', sys.version

DSM's code above provided the following:

1 'print \xe2\x80\x98version is\xe2\x80\x99, sys.version'

So the issue was that my text editor used SMART QUOTES, as John Y suggested. After changing the text editor settings and re-opening/saving the file, it works just fine.

What is the difference between varchar and varchar2 in Oracle?

Currently VARCHAR behaves exactly the same as VARCHAR2. However, the type VARCHAR should not be used as it is reserved for future usage.

Taken from: Difference Between CHAR, VARCHAR, VARCHAR2

generate random string for div id

I really like this function:

function guidGenerator() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

From Create GUID / UUID in JavaScript?

What's a "static method" in C#?

The static keyword, when applied to a class, tells the compiler to create a single instance of that class. It is not then possible to 'new' one or more instance of the class. All methods in a static class must themselves be declared static.

It is possible, And often desirable, to have static methods of a non-static class. For example a factory method when creates an instance of another class is often declared static as this means that a particular instance of the class containing the factor method is not required.

For a good explanation of how, when and where see MSDN

How to check if a radiobutton is checked in a radiogroup in Android?

I used the following and it worked for me. I used a boolean validation function where if any Radio Button in a Radio Group is checked, the validation function returns true and a submission is made. if returned false, no submission is made and a toast to "Select Gender" is shown:

  1. MainActivity.java

    public class MainActivity extends AppCompatActivity {
        private RadioGroup genderRadioGroup;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        //Initialize Radio Group And Submit Button
        genderRadioGroup=findViewById(R.id.gender_radiogroup);
        AppCompatButton submit = findViewById(R.id.btnSubmit);
    
        //Submit Radio Group using Submit Button
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Check Gender radio Group For Selected Radio Button
                if(genderRadioGroup.getCheckedRadioButtonId()==-1){//No Radio Button Is Checked
                    Toast.makeText(getApplicationContext(), "Please Select Gender", Toast.LENGTH_LONG).show();
                }else{//Radio Button Is Checked
                    RadioButton selectedRadioButton = findViewById(genderRadioGroup.getCheckedRadioButtonId());
                    gender = selectedRadioButton == null ? "" : selectedRadioButton.getText().toString().trim();
                }
                //Validate
                if (validateInputs()) {
                    //code to proceed when Radio button is checked
                }
            }
        }
        //Validation - No process is initialized if no Radio button is checked
        private boolean validateInputs() {
            if (genderRadioGroup.getCheckedRadioButtonId()==-1) {
                return false;
            }
            return true;
        }
    }
    
  2. In activity_main.xml:

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
    
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/gender"/>
    
        <RadioGroup
                android:id="@+id/gender_radiogroup"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
    
            <RadioButton
                    android:id="@+id/male"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/male"/>
    
            <RadioButton
                    android:id="@+id/female"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/female""/>
    
        </RadioGroup>
    
        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btnSubmit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/submit"/>
    
    </LinearLayout>
    

If no gender radio button is selected, then the code to proceed will not run.

I hope this helps.

C# how to wait for a webpage to finish loading before continuing

Check out the WatiN project:

Inspired by Watir development of WatiN started in December 2005 to make a similar kind of Web Application Testing possible for the .Net languages. Since then WatiN has grown into an easy to use, feature rich and stable framework. WatiN is developed in C# and aims to bring you an easy way to automate your tests with Internet Explorer and FireFox using .Net...

How to pass objects to functions in C++?

There are three methods of passing an object to a function as a parameter:

  1. Pass by reference
  2. pass by value
  3. adding constant in parameter

Go through the following example:

class Sample
{
public:
    int *ptr;
    int mVar;

    Sample(int i)
    {
        mVar = 4;
        ptr = new int(i);
    }

    ~Sample()
    {
        delete ptr;
    }

    void PrintVal()
    {
        cout << "The value of the pointer is " << *ptr << endl
             << "The value of the variable is " << mVar;
   }
};

void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}


int main()
{

  Sample s1= 10;
  SomeFunc(s1);
  s1.PrintVal();
  char ch;
  cin >> ch;
}

Output:

Say i am in someFunc
The value of the pointer is -17891602
The value of the variable is 4

How do I get class name in PHP?

To get class name you can use ReflectionClass

class MyClass {
    public function myNameIs(){
        return (new \ReflectionClass($this))->getShortName();
    }
}

Get program path in VB.NET?

For a console application you can use System.Reflection.Assembly.GetExecutingAssembly().Location as long as the call is made within the code of the console app itself, if you call this from within another dll or plugin this will return the location of that DLL and not the executable.

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

Assuming you have a module file called Dummy-Name.psm1 which has a method called Function-Dumb()

Import-Module "Dummy-Name.psm1";
Get-Command -Module "Function-Dumb";
#
#
Function-Dumb;

MySQL: @variable vs. variable. What's the difference?

@variable is very useful if calling stored procedures from an application written in Java , Python etc. There are ocassions where variable values are created in the first call and needed in functions of subsequent calls.

Side-note on PL/SQL (Oracle)

The advantage can be seen in Oracle PL/SQL where these variables have 3 different scopes:

  • Function variable for which the scope ends when function exits.
  • Package body variables defined at the top of package and outside all functions whose scope is the session and visibility is package.
  • Package variable whose variable is session and visibility is global.

My Experience in PL/SQL

I have developed an architecture in which the complete code is written in PL/SQL. These are called from a middle-ware written in Java. There are two types of middle-ware. One to cater calls from a client which is also written in Java. The other other one to cater for calls from a browser. The client facility is implemented 100 percent in JavaScript. A command set is used instead of HTML and JavaScript for writing application in PL/SQL.

I have been looking for the same facility to port the codes written in PL/SQL to another database. The nearest one I have found is Postgres. But all the variables have function scope.

Opinion towards @ in MySQL

I am happy to see that at least this @ facility is there in MySQL. I don't think Oracle will build same facility available in PL/SQL to MySQL stored procedures since it may affect the sales of Oracle database.

Fatal error: Maximum execution time of 300 seconds exceeded

On wamp in my configuration where I have multiple phpmyadmins, the values in config files were overwritten in wamp/alias/phpmyadmin.conf. I set up two lines there:

1. php_admin_value max_execution_time 3600

2. php_admin_value max_input_time 3600

... it finally worked!

Convert string to symbol-able in ruby

intern ? symbol Returns the Symbol corresponding to str, creating the symbol if it did not previously exist

"edition".intern # :edition

http://ruby-doc.org/core-2.1.0/String.html#method-i-intern

If statement with String comparison fails

If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals() or equalsIgnoreCase() for that.

Row Offset in SQL Server

I would avoid using SELECT *. Specify columns you actually want even though it may be all of them.

SQL Server 2005+

SELECT col1, col2 
FROM (
    SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
    FROM MyTable
) AS MyDerivedTable
WHERE MyDerivedTable.RowNum BETWEEN @startRow AND @endRow

SQL Server 2000

Efficiently Paging Through Large Result Sets in SQL Server 2000

A More Efficient Method for Paging Through Large Result Sets

Conditional operator in Python?

From Python 2.5 onwards you can do:

value = b if a > 10 else c

Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:

value = [c, b][a > 10]

There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.

JavaScript onclick redirect

Doing this fixed my issue

<script type="text/javascript">
    function SubmitFrm(){
        var Searchtxt = document.getElementById("txtSearch").value;
        window.location = "http://www.mysite.com/search/?Query=" + Searchtxt;
    }
</script>

I changed .value(); to .value; taking out the ()

I did not change anything in my text field or submit button

<input name="txtSearch" type="text" id="txtSearch" class="field" />            
<input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" />

Works like a charm.

CMD what does /im (taskkill)?

it allows you to kill a task based on the image name like taskkill /im iexplore.exe or taskkill /im notepad.exe

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Short answer:

const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

You can do something like this :

<asp:Button ID="Button1" runat="server" Text="Button"
    onclick="Button1_Click" OnClientClick="document.forms[0].target = '_blank';" />

Changing default startup directory for command prompt in Windows 7

In the new Windows Terminal, you can click Settings and edit the line "startingDirectory" to achieve something similar.

Please note, however, that this changes the default startup directory only in Windows Terminal, and not for the command prompt globally.

android: how to use getApplication and getApplicationContext from non activity / service class

Either pass in a Context (so you can access resources), or make the helper methods static.

Function not defined javascript

The actual problem is with your

showList function.

There is an extra ')' after 'visible'.

Remove that and it will work fine.

function showList()
{
  if (document.getElementById("favSports").style.visibility == "hidden") 
    {
       // document.getElementById("favSports").style.visibility = "visible");  
       // your code
       document.getElementById("favSports").style.visibility = "visible";
       // corrected code
    }
}

'xmlParseEntityRef: no name' warnings while loading xml into a php file

PROBLEM

  • PHP function simplexml_load_file is throwing parsing error parser error : xmlParseEntityRef while trying to load the XML file from a URL.

CAUSE

  • XML returned by the URL is not a valid XML. It contains & value instead of &amp;. It is quite possible that there are other errors which aren't obvious at this point of time.

THINGS OUT OF OUR CONTROL

  • Ideally, we should make sure that a valid XML is feed into PHP simplexml_load_file function, but it looks like we don't have any control over how the XML is created.
  • It is also not possible to force simplexml_load_file to process an invalid XML file. It does not leave us with many options, other than fixing the XML file itself.

POSSIBLE SOLUTION

Convert Invalid XML to Valid XML. It can be done using PHP tidy extension. Further instructions can be found from http://php.net/manual/en/book.tidy.php

Once you are sure that the extension exists or is installed, please do the following.

/**
 * As per the question asked, the URL is loaded into a variable first, 
 * which we can assume to be $xml
 */
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<project orderno="6" campaign_name="International Relief & Development for under developed nations">
    <invalid-data>Some other data containing & in it</invalid-data>
    <unclosed-tag>
</project>
XML;

/**
 * Whenever we use tidy it is best to pass some configuration options 
 * similar to $tidyConfig. In this particular case we are making sure that
 * tidy understands that our input and output is XML.
 */
$tidyConfig = array (
    'indent' => true,
    'input-xml' => true, 
    'output-xml' => true,
    'wrap' => 200
);

/**
 * Now we can use tidy to parse the string and then repair it.
 */
$tidy = new tidy;
$tidy->parseString($xml, $tidyConfig, 'utf8');
$tidy->cleanRepair();

/**
 * If we try to output the repaired XML string by echoing $tidy it should look like. 

 <?xml version="1.0" encoding="utf-8"?>
 <project orderno="6" campaign_name="International Relief &amp; Development for under developed nations">
      <invalid-data>Some other data containing &amp; in it</invalid-data>
      <unclosed-tag></unclosed-tag>
 </project> 

 * As you can see that & is now fixed in campaign_name attribute 
 * and also with-in invalid-data element. You can also see that the   
 * <unclosed-tag> which didn't had a close tag, has been fixed too.
 */
echo $tidy;

/**
 * Now when we try to use simplexml_load_string to load the clean XML. When we
 * try to print_r it should look something like below.

 SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [orderno] => 6
            [campaign_name] => International Relief & Development for under developed nations
        )

    [invalid-data] => Some other data containing & in it
    [unclosed-tag] => SimpleXMLElement Object
        (
        )

)

 */
 $simpleXmlElement = simplexml_load_string($tidy);
 print_r($simpleXmlElement);

CAUTION

The developer should try to compare the invalid XML with a valid XML (generated by tidy), to see there are no adverse side effects after using tidy. Tidy does an extremely good job of doing it correctly, but it never hurts to see it visually and to be 100% sure. In our case it should be as simple as comparing $xml with $tidy.

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Add bean declaration in bean.xml file or in any other configuration file . It will resolve the error

<bean  class="com.demo.dao.RailwayDao"></bean>
<bean  class="com.demo.service.RailwayService"></bean>
<bean  class="com.demo.model.RailwayReservation"></bean>

Remove portion of a string after a certain character

preg_replace offers one way:

$newText = preg_replace('/\bBy.*$/', '', $text);

Android: How to get a custom View's height and width?

The difference between getHeight() and getMeasuredHeight() is that first method will return actual height of the View, the second one will return summary height of View's children. In ohter words, getHeight() returns view height, getMeasuredHeight() returns height which this view needs to show all it's elements

How do I read image data from a URL in Python?

Python 3

from urllib.request import urlopen
from PIL import Image

img = Image.open(urlopen(url))
img

Jupyter Notebook and IPython

import IPython
url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
IPython.display.Image(url, width = 250)

Unlike other methods, this method also works in a for loop!

Android - save/restore fragment state

When a fragment is moved to the backstack, it isn't destroyed. All the instance variables remain there. So this is the place to save your data. In onActivityCreated you check the following conditions:

  1. Is the bundle != null? If yes, that's where the data is saved (probably orientation change).
  2. Is there data saved in instance variables? If yes, restore your state from them (or maybe do nothing, because everything is as it should be).
  3. Otherwise your fragment is shown for the first time, create everything anew.

Edit: Here's an example

public class ExampleFragment extends Fragment {
    private List<String> myData;

    @Override
    public void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("list", (Serializable) myData);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (savedInstanceState != null) {
            //probably orientation change
            myData = (List<String>) savedInstanceState.getSerializable("list");
        } else {
            if (myData != null) {
                //returning from backstack, data is fine, do nothing
            } else {
                //newly created, compute data
                myData = computeData();
            }
        }
    }
}

how to create 100% vertical line in css

I use this css positioning for most of my vertical elements:

<div class="vertical-line" style="height: 250px;
width: 1px;
background-color: #81F781;
margin-left: 0px;
margin-top: -100px;
postion: absolute;
border-radius: 2px;">
</div>

Change the height and width to fit the page, or to make a horizontal line swap the height to width:

<div class="vertical-line" style="height: 250px;
width: 1px;

<div class="vertical-line" style="width: 250px;
height: 1px;   

instead of a standard html line.

Store images in a MongoDB database

http://blog.mongodb.org/post/183689081/storing-large-objects-and-files-in-mongodb

There is a Mongoose plugin available on NPM called mongoose-file. It lets you add a file field to a Mongoose Schema for file upload. I have never used it but it might prove useful. If the images are very small you could Base64 encode them and save the string to the database.

Storing some small (under 1MB) files with MongoDB in NodeJS WITHOUT GridFS

change text of button and disable button in iOS

SWIFT 4 with extension

set:

// set button label for all states
extension UIButton {
    public func setAllStatesTitle(_ newTitle: String){
        self.setTitle(newTitle, for: .normal)
        self.setTitle(newTitle, for: .selected)
        self.setTitle(newTitle, for: .disabled)
    }
}

and use:

yourBtn.setAllStatesTitle("btn title")

How to check certificate name and alias in keystore files?

You can run from Java code.

try {

        File file = new File(keystore location);
        InputStream is = new FileInputStream(file);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        String password = "password";
        keystore.load(is, password.toCharArray());


        Enumeration<String> enumeration = keystore.aliases();
        while(enumeration.hasMoreElements()) {
            String alias = enumeration.nextElement();
            System.out.println("alias name: " + alias);
            Certificate certificate = keystore.getCertificate(alias);
            System.out.println(certificate.toString());

        }

    } catch (java.security.cert.CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(null != is)
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

Certificate class holds all information about the keystore.

UPDATE- OBTAIN PRIVATE KEY

Key key = keyStore.getKey(alias, password.toCharArray());
String encodedKey = new Base64Encoder().encode(key.getEncoded());
System.out.println("key ? " + encodedKey);

@prateek Hope this is what you looking for!

npm install hangs

This method is working for me when npm blocks in installation Package for IONIC installation and ReactNative and another package npm.

You can change temporary:

npm config set prefix C:\Users\[username]\AppData\Roaming\npm\node_modules2

  • Change the path in environment variables. Set:

    C:\Users[username]\AppData\Roaming\npm\node_modules2

  • Run the command to install your package.

  • Open file explorer, copy the link:

    C:\Users[username]\AppData\Roaming\npm\node_modules

    ok file yourpackage.CMD created another folder Created "node_modules2" in node_modules and contain your package folder.

  • Copy your package file CMD to parent folder "npm".

  • Copy your package folder to parent folder "node_modules".

  • Now run:

    npm config set prefix C:\Users\[username]\AppData\Roaming\npm

  • Change the path in environment variables. Set:

    C:\Users[username]\AppData\Roaming\npm

Now the package is working correctly with the command line.

AngularJS view not updating on model change

As Ajay beniwal mentioned above you need to use Apply to start digestion.

var app = angular.module('test', []);

app.controller('TestCtrl', function ($scope) {
   $scope.testValue = 0;

    setInterval(function() {
        console.log($scope.testValue++);
        $scope.$apply() 
    }, 500);
});

Add or change a value of JSON key with jquery or javascript

var y_axis_name=[];

 for(var point in jsonData[0].data)
              { 
                y_axis_name.push(point);

              }

y_axis_name is having all the key name

try on jsfiddle

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

This is a recurring subject in Stackoverflow and since I was unable to find a relevant implementation I decided to accept the challenge.

I made some modifications to the squares demo present in OpenCV and the resulting C++ code below is able to detect a sheet of paper in the image:

void find_squares(Mat& image, vector<vector<Point> >& squares)
{
    // blur will enhance edge detection
    Mat blurred(image);
    medianBlur(image, blurred, 9);

    Mat gray0(blurred.size(), CV_8U), gray;
    vector<vector<Point> > contours;

    // find squares in every color plane of the image
    for (int c = 0; c < 3; c++)
    {
        int ch[] = {c, 0};
        mixChannels(&blurred, 1, &gray0, 1, ch, 1);

        // try several threshold levels
        const int threshold_level = 2;
        for (int l = 0; l < threshold_level; l++)
        {
            // Use Canny instead of zero threshold level!
            // Canny helps to catch squares with gradient shading
            if (l == 0)
            {
                Canny(gray0, gray, 10, 20, 3); // 

                // Dilate helps to remove potential holes between edge segments
                dilate(gray, gray, Mat(), Point(-1,-1));
            }
            else
            {
                    gray = gray0 >= (l+1) * 255 / threshold_level;
            }

            // Find contours and store them in a list
            findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

            // Test contours
            vector<Point> approx;
            for (size_t i = 0; i < contours.size(); i++)
            {
                    // approximate contour with accuracy proportional
                    // to the contour perimeter
                    approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);

                    // Note: absolute value of an area is used because
                    // area may be positive or negative - in accordance with the
                    // contour orientation
                    if (approx.size() == 4 &&
                            fabs(contourArea(Mat(approx))) > 1000 &&
                            isContourConvex(Mat(approx)))
                    {
                            double maxCosine = 0;

                            for (int j = 2; j < 5; j++)
                            {
                                    double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                                    maxCosine = MAX(maxCosine, cosine);
                            }

                            if (maxCosine < 0.3)
                                    squares.push_back(approx);
                    }
            }
        }
    }
}

After this procedure is executed, the sheet of paper will be the largest square in vector<vector<Point> >:

opencv paper sheet detection

I'm letting you write the function to find the largest square. ;)

How do I get bit-by-bit data from an integer value in C?

Here's a very simple way to do it;

int main()
{
    int s=7,l=1;
    vector <bool> v;
    v.clear();
    while (l <= 4)
    {
        v.push_back(s%2);
        s /= 2;
        l++;
    }
    for (l=(v.size()-1); l >= 0; l--)
    {
        cout<<v[l]<<" ";
    }
    return 0;
}

disable Bootstrap's Collapse open/close animation

Bootstrap 2 CSS solution:

.collapse {  transition: height 0.01s; }  

NB: setting transition: none disables the collapse functionnality.


Bootstrap 4 solution:

.collapsing {
  transition: none !important;
}

Call apply-like function on each row of dataframe with multiple arguments from each row

A data.frame is a list, so ...

For vectorized functions do.call is usually a good bet. But the names of arguments come into play. Here your testFunc is called with args x and y in place of a and b. The ... allows irrelevant args to be passed without causing an error:

do.call( function(x,z,...) testFunc(x,z), df )

For non-vectorized functions, mapply will work, but you need to match the ordering of the args or explicitly name them:

mapply(testFunc, df$x, df$z)

Sometimes apply will work - as when all args are of the same type so coercing the data.frame to a matrix does not cause problems by changing data types. Your example was of this sort.

If your function is to be called within another function into which the arguments are all passed, there is a much slicker method than these. Study the first lines of the body of lm() if you want to go that route.

How do I create JavaScript array (JSON format) dynamically?

var student = [];
var obj = {
    'first_name': name,
    'last_name': name,
    'age': age,
}
student.push(obj);

Circle line-segment collision detection algorithm?

Maybe there is another way to solve this problem using rotation of coordinate system.

Normally, if one segment is horizontal or vertical, which means parallel to x or y axis, it's quite easy to solve the intersection point since we already know one coordinate of the intersection, if any. The rest is obviously finding the other coordinate using circle's equation.

Inspired by this idea, we could apply coordinates system rotation to make one axis's direction coincide with segment's direction.

Let's take an example of circle x^2+y^2=1 and segment P1-P2 with P1(-1.5,0.5) and P2(-0.5,-0.5) in x-y system. And the following equations to remind you of the rotation principles, where theta is the angle anticlockwise, x'-y' is the system after rotation :

x' = x * cos(theta) + y * sin(theta)

y' = - x * sin(theta) + y * cos(theta)

and inversely

x = x' * cos(theta) - y' * sin(theta)

y = x' * sin(theta) + y' * cos(theta)

Considering the segment P1-P2 direction (45° in terms of -x), we could take theta=45°. Taking the second equations of rotation into circle's equation in x-y system : x^2+y^2=1 and after simple operations we get the 'same' equation in x'-y' system : x'^2+y'^2=1.

Segment endpoints become in x'-y' system using the first equations of rotation => P1(-sqrt(2)/2, sqrt(2)), P2(-sqrt(2)/2, 0).

Assuming the intersection as P. We have in x'-y' Px = -sqrt(2)/2. Using the new equation of circle, we get Py = +sqrt(2)/2. Converting P into original x-y system, we get finally P(-1,0).

To implement this numerically, we could firstly have a look at segment's direction : horizontal, vertical or not. If it belongs to the two first cases, it's simple like I said. If the last case, apply the algorithms above.

To juge if there is intersection, we could compare the solution with the endpoints coordinates, to see whether there is one root between them.

I believe this method could be also applied to other curves as long as we have its equation. The only weakness is that we should solve the equation in x'-y' system for the other coordinate, which might be difficult.

ReactJS - Does render get called any time "setState" is called?

No, React doesn't render everything when the state changes.

  • Whenever a component is dirty (its state changed), that component and its children are re-rendered. This, to some extent, is to re-render as little as possible. The only time when render isn't called is when some branch is moved to another root, where theoretically we don't need to re-render anything. In your example, TimeInChild is a child component of Main, so it also gets re-rendered when the state of Main changes.

  • React doesn't compare state data. When setState is called, it marks the component as dirty (which means it needs to be re-rendered). The important thing to note is that although render method of the component is called, the real DOM is only updated if the output is different from the current DOM tree (a.k.a diffing between the Virtual DOM tree and document's DOM tree). In your example, even though the state data hasn't changed, the time of last change did, making Virtual DOM different from the document's DOM, hence why the HTML is updated.

How can I convert uppercase letters to lowercase in Notepad++

Ctrl+A , Ctrl+Shift+U

should do the trick!

Edit: Ctrl+U is the shortcut to be used to convert capital letters to lowercase (reverse scenario)

How do I generate a random int number?

The question looks very simple but the answer is bit complicated. If you see almost everyone has suggested to use the Random class and some have suggested to use the RNG crypto class. But then when to choose what.

For that we need to first understand the term RANDOMNESS and the philosophy behind it.

I would encourage you to watch this video which goes in depth in the philosophy of RANDOMNESS using C# https://www.youtube.com/watch?v=tCYxc-2-3fY

First thing let us understand the philosophy of RANDOMNESS. When we tell a person to choose between RED, GREEN and YELLOW what happens internally. What makes a person choose RED or YELLOW or GREEN?

c# Random

Some initial thought goes into the persons mind which decides his choice, it can be favorite color , lucky color and so on. In other words some initial trigger which we term in RANDOM as SEED.This SEED is the beginning point, the trigger which instigates him to select the RANDOM value.

Now if a SEED is easy to guess then those kind of random numbers are termed as PSEUDO and when a seed is difficult to guess those random numbers are termed SECURED random numbers.

For example a person chooses is color depending on weather and sound combination then it would be difficult to guess the initial seed.

c# Random

Now let me make an important statement:-

*“Random” class generates only PSEUDO random number and to generate SECURE random number we need to use “RNGCryptoServiceProvider” class.

c# Random

Random class takes seed values from your CPU clock which is very much predictable. So in other words RANDOM class of C# generates pseudo random numbers , below is the code for the same.

var random = new Random();
int randomnumber = random.Next()

While the RNGCryptoServiceProvider class uses OS entropy to generate seeds. OS entropy is a random value which is generated using sound, mouse click, and keyboard timings, thermal temp etc. Below goes the code for the same.

using (RNGCryptoServiceProvider rg = new RNGCryptoServiceProvider()) 
{ 
    byte[] rno = new byte[5];    
    rg.GetBytes(rno);    
    int randomvalue = BitConverter.ToInt32(rno, 0); 
}

To understand OS entropy see this video from 14:30 https://www.youtube.com/watch?v=tCYxc-2-3fY where the logic of OS entropy is explained. So putting in simple words RNG Crypto generates SECURE random numbers.

Simple Popup by using Angular JS

Built a modal popup example using syarul's jsFiddle link. Here is the updated fiddle.

Created an angular directive called modal and used in html. Explanation:-

HTML

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>

On button click toggleModal() function is called with the button message as parameter. This function toggles the visibility of popup. Any tags that you put inside will show up in the popup as content since ng-transclude is placed on modal-body in the directive template.

JS

var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

UPDATE

<!doctype html>
<html ng-app="mymodal">


<body>

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <!-- Scripts -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

    <!-- App -->
    <script>
        var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
          scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

    </script>
</body>
</html>

UPDATE 2 restrict : 'E' : directive to be used as an HTML tag (element). Example in our case is

<modal>

Other values are 'A' for attribute

<div modal>

'C' for class (not preferable in our case because modal is already a class in bootstrap.css)

<div class="modal">

using jQuery .animate to animate a div from right to left?

so the .animate method works only if you have given a position attribute to an element, if not it didn't move?

for example i've seen that if i declare the div but i declare nothing in the css, it does not assume his default position and it does not move it into the page, even if i declare property margin: x w y z;

Add Keypair to existing EC2 instance

Once an instance has been started, there is no way to change the keypair associated with the instance at a meta data level, but you can change what ssh key you use to connect to the instance.

stackoverflow.com/questions/7881469/change-key-pair-for-ec2-instance

Expected corresponding JSX closing tag for input Reactjs

All tags must have enclosing tags. In my case, the hr and input elements weren't closed properly.

Parent Error was: JSX element 'div' has no corresponding closing tag, due to code below:

<hr class="my-4">
<input
  type="password"
  id="inputPassword"
  class="form-control"
  placeholder="Password"
  required
 >

Fix:

<hr class="my-4"/>
<input
 type="password"
 id="inputPassword"
 class="form-control"
 placeholder="Password"
 required
/>

The parent elements will show errors due to child element errors. Therefore, start investigating from most inner elements up to the parent ones.

Enable vertical scrolling on textarea

Try this: http://jsfiddle.net/8fv6e/8/

It is another version of the answers.

HTML:

<label for="aboutDescription" id="aboutHeading">About</label>
<textarea rows="15" cols="50" id="aboutDescription"
    style="max-height:100px;min-height:100px; resize: none"></textarea>
<a  id="imageURLId" target="_blank">Go to
    HomePage</a>

CSS:

#imageURLId{
font-size: 14px;
font-weight: normal;
resize: none;
overflow-y: scroll;

}

Can't run Curl command inside my Docker Container

You don't need to install curl to download the file into Docker container, use ADD command, e.g.

ADD https://raw.githubusercontent.com/Homebrew/install/master/install /tmp
RUN ruby -e /tmp/install

Note: Add above lines to your Dockerfile file.


Another example which installs Azure CLI:

ADD https://aka.ms/InstallAzureCLIDeb /tmp
RUN bash /tmp/InstallAzureCLIDeb

Getters \ setters for dummies

You can define instance method for js class, via prototype of the constructor.

Following is the sample code:

// BaseClass

var BaseClass = function(name) {
    // instance property
    this.name = name;
};

// instance method
BaseClass.prototype.getName = function() {
    return this.name;
};
BaseClass.prototype.setName = function(name) {
    return this.name = name;
};


// test - start
function test() {
    var b1 = new BaseClass("b1");
    var b2 = new BaseClass("b2");
    console.log(b1.getName());
    console.log(b2.getName());

    b1.setName("b1_new");
    console.log(b1.getName());
    console.log(b2.getName());
}

test();
// test - end

And, this should work for any browser, you can also simply use nodejs to run this code.

How to check if element in groovy array/hash/collection/list?

For lists, use contains:

[1,2,3].contains(1) == true

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

The issue pointed in the comment is valid, so here is a different revision that's immune to that:

function show_alert() {
  if(!confirm("Do you really want to do this?")) {
    return false;
  }
  this.form.submit();
}

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Echo equivalent in PowerShell for script testing

Try Get-Content .\yourScript.PS1 and you will see the content of your script.

also you can insert this line in your scrip code:

get-content .\scriptname.PS1
script code
script code

....

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

I needed an example using React.Component so I am posting it:

import React from 'react';
import * as Redux from 'react-redux';

class NavigationHeader extends React.Component {

}

const mapStateToProps = function (store) {
    console.log(`mapStateToProps ${store}`);
    return {
        navigation: store.navigation
    };
};

export default Redux.connect(mapStateToProps)(NavigationHeader);

INSERT INTO from two different server database

The answer given by Simon works fine for me but you have to do it in the right sequence: First you have to be in the server that you want to insert data into which is [DATABASE.WINDOWS.NET].[basecampdev] in your case.

You can try to see if you can select some data out of the Invoice table to make sure you have access.

Select top 10 * from [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]

Secondly, execute the query given by Simon in order to link to a different server. This time use the other server:

EXEC sp_addlinkedserver [BC1-PC]; -- this will create a link tempdb that you can access from where you are
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR 
    [BC1-PC].testdabse.dbo.invoice; -- Make a copy of the table and data that you can use
GO

Now just do your insert statement.

INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
       ([InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks])
SELECT [InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks] FROM MyInvoice

Hope this helps!

jQuery returning "parsererror" for ajax request

incase of Get operation from web .net mvc/api, make sure you are allow get

     return Json(data,JsonRequestBehavior.AllowGet);

What is referencedColumnName used for in JPA?

It is there to specify another column as the default id column of the other table, e.g. consider the following

TableA
  id int identity
  tableb_key varchar


TableB
  id int identity
  key varchar unique

// in class for TableA
@JoinColumn(name="tableb_key", referencedColumnName="key")

Calling a JSON API with Node.js

Problems with other answers:

  • unsafe JSON.parse
  • no response code checking

All of the answers here use JSON.parse() in an unsafe way. You should always put all calls to JSON.parse() in a try/catch block especially when you parse JSON coming from an external source, like you do here.

You can use request to parse the JSON automatically which wasn't mentioned here in other answers. There is already an answer using request module but it uses JSON.parse() to manually parse JSON - which should always be run inside a try {} catch {} block to handle errors of incorrect JSON or otherwise the entire app will crash. And incorrect JSON happens, trust me.

Other answers that use http also use JSON.parse() without checking for exceptions that can happen and crash your application.

Below I'll show few ways to handle it safely.

All examples use a public GitHub API so everyone can try that code safely.

Example with request

Here's a working example with request that automatically parses JSON:

'use strict';
var request = require('request');

var url = 'https://api.github.com/users/rsp';

request.get({
    url: url,
    json: true,
    headers: {'User-Agent': 'request'}
  }, (err, res, data) => {
    if (err) {
      console.log('Error:', err);
    } else if (res.statusCode !== 200) {
      console.log('Status:', res.statusCode);
    } else {
      // data is already parsed as JSON:
      console.log(data.html_url);
    }
});

Example with http and try/catch

This uses https - just change https to http if you want HTTP connections:

'use strict';
var https = require('https');

var options = {
    host: 'api.github.com',
    path: '/users/rsp',
    headers: {'User-Agent': 'request'}
};

https.get(options, function (res) {
    var json = '';
    res.on('data', function (chunk) {
        json += chunk;
    });
    res.on('end', function () {
        if (res.statusCode === 200) {
            try {
                var data = JSON.parse(json);
                // data is available here:
                console.log(data.html_url);
            } catch (e) {
                console.log('Error parsing JSON!');
            }
        } else {
            console.log('Status:', res.statusCode);
        }
    });
}).on('error', function (err) {
      console.log('Error:', err);
});

Example with http and tryjson

This example is similar to the above but uses the tryjson module. (Disclaimer: I am the author of that module.)

'use strict';
var https = require('https');
var tryjson = require('tryjson');

var options = {
    host: 'api.github.com',
    path: '/users/rsp',
    headers: {'User-Agent': 'request'}
};

https.get(options, function (res) {
    var json = '';

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

    res.on('end', function () {
        if (res.statusCode === 200) {
            var data = tryjson.parse(json);
            console.log(data ? data.html_url : 'Error parsing JSON!');
        } else {
            console.log('Status:', res.statusCode);
        }
    });
}).on('error', function (err) {
      console.log('Error:', err);
});

Summary

The example that uses request is the simplest. But if for some reason you don't want to use it then remember to always check the response code and to parse JSON safely.

remove url parameters with javascript or jquery

What am I missing?

Why not:

url.split('?')[0] 

How to see the CREATE VIEW code for a view in PostgreSQL?

GoodNews from v.9.6 and above, View editing are now native from psql. Just invoke \ev command. View definitions will show in your configured editor.

julian@assange=# \ev {your_view_names}

Bonus. Some useful command to interact with query buffer.

Query Buffer
  \e [FILE] [LINE]       edit the query buffer (or file) with external editor
  \ef [FUNCNAME [LINE]]  edit function definition with external editor
  \ev [VIEWNAME [LINE]]  edit view definition with external editor
  \p                     show the contents of the query buffer
  \r                     reset (clear) the query buffer
  \s [FILE]              display history or save it to file
  \w FILE                write query buffer to file

Returning a promise in an async function in TypeScript

When you do new Promise((resolve)... the type inferred was Promise<{}> because you should have used new Promise<number>((resolve).

It is interesting that this issue was only highlighted when the async keyword was added. I would recommend reporting this issue to the TS team on GitHub.

There are many ways you can get around this issue. All the following functions have the same behavior:

const whatever1 = () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever2 = async () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever3 = async () => {
    return await new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever4 = async () => {
    return Promise.resolve(4);
};

const whatever5 = async () => {
    return await Promise.resolve(4);
};

const whatever6 = async () => Promise.resolve(4);

const whatever7 = async () => await Promise.resolve(4);

In your IDE you will be able to see that the inferred type for all these functions is () => Promise<number>.

How can I INSERT data into two tables simultaneously in SQL Server?

Keep a look out for SQL Server to support the 'INSERT ALL' Statement. Oracle has it already, it looks like this (SQL Cookbook):

insert all
  when loc in ('NEW YORK', 'BOSTON') THEN
   into dept_east(deptno, dname, loc) values(deptno, dname, loc)
  when loc in ('CHICAGO') THEN
   into dept_mid(deptno, dname, loc) values(deptno, dname, loc)
  else
   into dept_west(deptno, dname, loc) values(deptno, dname, loc)
select deptno, dname, loc
  from dept

Compare two objects' properties to find differences?

Sure you can with reflection. Here is the code to grab the properties off of a given type.

var info = typeof(SomeType).GetProperties();

If you can give more info on what you're comparing about the properties we can get together a basic diffing algorithmn. This code for intstance will diff on names

public bool AreDifferent(Type t1, Type t2) {
  var list1 = t1.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
  var list2 = t2.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
  return list1.SequenceEqual(list2);
}

How To Launch Git Bash from DOS Command Line?

I prefer to use git-bash.exe instead of sh.exe.

start "" "%ProgramFiles%\Git\git-bash.exe" -c "tail -f /c/Windows/win.ini"

You can stop closing the window when call /usr/bin/bash --login -i in the end;

start "" "%ProgramFiles%\Git\git-bash.exe" -c "echo 1 && echo 2 && /usr/bin/bash --login -i"

Note: I'm not sure this is a good way :)

How to get char from string by index?

I think this is more clear than describing it in words

s = 'python'
print(len(s))
6
print(s[5])
'n'
print(s[len(s) - 1])
'n'
print(s[-1])
'n'

Laravel: getting a a single value from a MySQL query

Edit:

Sorry i forgot about pluck() as many have commented : Easiest way is :

return DB::table('users')->where('username', $username)->pluck('groupName');

Which will directly return the only the first result for the requested row as a string.

Using the fluent query builder you will obtain an array anyway. I mean The Query Builder has no idea how many rows will come back from that query. Here is what you can do to do it a bit cleaner

$result = DB::table('users')->select('groupName')->where('username', $username)->first();

The first() tells the queryBuilder to return only one row so no array, so you can do :

return $result->groupName;

Hope it helps

How to assign execute permission to a .sh file in windows to be executed in linux

As far as I know the permission system in Linux is set up in such a way to prevent exactly what you are trying to accomplish.

I think the best you can do is to give your Linux user a custom unzip one-liner to run on the prompt:

unzip zip_name.zip && chmod +x script_name.sh

If there are multiple scripts that you need to give execute permission to, write a grant_perms.sh as follows:

#!/bin/bash
# file: grant_perms.sh

chmod +x script_1.sh
chmod +x script_2.sh
...
chmod +x script_n.sh

(You can put the scripts all on one line for chmod, but I found separate lines easier to work with in vim and with shell script commands.)

And now your unzip one-liner becomes:

unzip zip_name.zip && source grant_perms.sh

Note that since you are using source to run grant_perms.sh, it doesn't need execute permission

Difference between return and exit in Bash functions

From man bash on return [n];

Causes a function to stop executing and return the value specified by n to its caller. If n is omitted, the return status is that of the last command executed in the function body.

... on exit [n]:

Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell terminates.

EDIT:

As per your edit of the question, regarding exit codes, return has nothing to do with exit codes. Exit codes are intended for applications/scripts, not functions. So in this regard, the only keyword that sets the exit code of the script (the one that can be caught by the calling program using the $? shell variable) is exit.

EDIT 2:

My last statement referring exit is causing some comments. It was made to differentiate return and exit for the understanding of the OP, and in fact, at any given point of a program/shell script, exit is the only way of ending the script with an exit code to the calling process.

Every command executed in the shell produces a local "exit code": it sets the $? variable to that code, and can be used with if, && and other operators to conditionally execute other commands.

These exit codes (and the value of the $? variable) are reset by each command execution.

Incidentally, the exit code of the last command executed by the script is used as the exit code of the script itself as seen by the calling process.

Finally, functions, when called, act as shell commands with respect to exit codes. The exit code of the function (within the function) is set by using return. So when in a function return 0 is run, the function execution terminates, giving an exit code of 0.

Bold & Non-Bold Text In A Single UILabel?

Check out TTTAttributedLabel. It's a drop-in replacement for UILabel that allows you to have mixed font and colors in a single label by setting an NSAttributedString as the text for that label.

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

Opaque will cause less system strain since 'transparent' will still attempt to apply alpha. The reason you see transparent used instead is because most web authors don't pay attention to detail (ie, just copy-pasted some embed code they found).

BTW, you are correct about it being undocumented. The best I've ever seen is a blog by a guy who claims to have talked to a Macromedia developer about it. Unfortunaetly I can't find the link.

EDIT: I think it was this one: http://www.communitymx.com/content/article.cfm?cid=e5141

How to add custom html attributes in JSX

uniqueId is custom attribute.

<a {...{ "uniqueId": `${item.File.UniqueId}` }}  href={item.File.ServerRelativeUrl} target='_blank'>{item.File.Name}</a>

How to recursively download a folder via FTP on Linux

Use WGet instead. It supports HTTP and FTP protocols.

wget -r ftp://mydomain.com/mystuff

Good Luck!

reference: http://linux.about.com/od/commands/l/blcmdl1_wget.htm

How to handle calendar TimeZones using Java?

Method for converting from one timeZone to other(probably it works :) ).

/**
 * Adapt calendar to client time zone.
 * @param calendar - adapting calendar
 * @param timeZone - client time zone
 * @return adapt calendar to client time zone
 */
public static Calendar convertCalendar(final Calendar calendar, final TimeZone timeZone) {
    Calendar ret = new GregorianCalendar(timeZone);
    ret.setTimeInMillis(calendar.getTimeInMillis() +
            timeZone.getOffset(calendar.getTimeInMillis()) -
            TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));
    ret.getTime();
    return ret;
}

Write applications in C or C++ for Android?

This blog post may be a good start: http://benno.id.au/blog/2007/11/13/android-native-apps Unfortunately, lots of the important stuff is "left as an exercise to the reader".

How to move child element from one parent to another using jQuery

Detach is unnecessary.

The answer (as of 2013) is simple:

$('#parentNode').append($('#childNode'));

According to http://api.jquery.com/append/

You can also select an element on the page and insert it into another:

$('.container').append($('h2'));

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).