Programs & Examples On #Business process management

Business process management revolves around how organizations perform various tasks such as what tools are used and how they should be kept updated to maximize efficiency.

Incrementing a date in JavaScript

Via native JS, to add one day you may do following:

let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow

Another option is to use moment library:

const date = moment().add(14, "days").toDate()

Get input value from TextField in iOS alert in Swift

Swift 3/4

You can use the below extension for your convenience.

Usage inside a ViewController:

showInputDialog(title: "Add number",
                subtitle: "Please enter the new number below.",
                actionTitle: "Add",
                cancelTitle: "Cancel",
                inputPlaceholder: "New number",
                inputKeyboardType: .numberPad)
{ (input:String?) in
    print("The new number is \(input ?? "")")
}

The extension code:

extension UIViewController {
    func showInputDialog(title:String? = nil,
                         subtitle:String? = nil,
                         actionTitle:String? = "Add",
                         cancelTitle:String? = "Cancel",
                         inputPlaceholder:String? = nil,
                         inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
                         cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
                         actionHandler: ((_ text: String?) -> Void)? = nil) {

        let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
        alert.addTextField { (textField:UITextField) in
            textField.placeholder = inputPlaceholder
            textField.keyboardType = inputKeyboardType
        }
        alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
            guard let textField =  alert.textFields?.first else {
                actionHandler?(nil)
                return
            }
            actionHandler?(textField.text)
        }))
        alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))

        self.present(alert, animated: true, completion: nil)
    }
}

git ahead/behind info between master and branch?

With Git 2.5+, you now have another option to see ahead/behind for all branches which are configured to push to a branch.

git for-each-ref --format="%(push:track)" refs/heads

See more at "Viewing Unpushed Git Commits"

Performance of FOR vs FOREACH in PHP

It's 2020 and stuffs had greatly evolved with php 7.4 and opcache.

Here is the OP^ benchmark, ran as unix CLI, without the echo and html parts.

Test ran locally on a regular computer.

php -v

PHP 7.4.6 (cli) (built: May 14 2020 10:02:44) ( NTS )

Modified benchmark script:

<?php 
 ## preperations; just a simple environment state

  $test_iterations = 100;
  $test_arr_size = 1000;

  // a shared function that makes use of the loop; this should
  // ensure no funny business is happening to fool the test
  function test($input)
  {
    //echo '<!-- '.trim($input).' -->';
  }

  // for each test we create a array this should avoid any of the
  // arrays internal representation or optimizations from getting
  // in the way.

  // normal array
  $test_arr1 = array();
  $test_arr2 = array();
  $test_arr3 = array();
  // hash tables
  $test_arr4 = array();
  $test_arr5 = array();

  for ($i = 0; $i < $test_arr_size; ++$i)
  {
    mt_srand();
    $hash = md5(mt_rand());
    $key = substr($hash, 0, 5).$i;

    $test_arr1[$i] = $test_arr2[$i] = $test_arr3[$i] = $test_arr4[$key] = $test_arr5[$key]
      = $hash;
  }

  ## foreach

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    foreach ($test_arr1 as $k => $v)
    {
      test($v);
    }
  }
  echo 'foreach '.(microtime(true) - $start)."\n";  

  ## foreach (using reference)

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    foreach ($test_arr2 as &$value)
    {
      test($value);
    }
  }
  echo 'foreach (using reference) '.(microtime(true) - $start)."\n";

  ## for

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    $size = count($test_arr3);
    for ($i = 0; $i < $size; ++$i)
    {
      test($test_arr3[$i]);
    }
  }
  echo 'for '.(microtime(true) - $start)."\n";  

  ## foreach (hash table)

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    foreach ($test_arr4 as $k => $v)
    {
      test($v);
    }
  }
  echo 'foreach (hash table) '.(microtime(true) - $start)."\n";

  ## for (hash table)

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    $keys = array_keys($test_arr5);
    $size = sizeOf($test_arr5);
    for ($i = 0; $i < $size; ++$i)
    {
      test($test_arr5[$keys[$i]]);
    }
  }
  echo 'for (hash table) '.(microtime(true) - $start)."\n";

Output:

foreach 0.0032877922058105
foreach (using reference) 0.0029420852661133
for 0.0025191307067871
foreach (hash table) 0.0035080909729004
for (hash table) 0.0061779022216797

As you can see the evolution is insane, about 560 time faster than reported in 2012.

On my machines and servers, following my numerous experiments, basics for loops are the fastest. This is even clearer using nested loops ($i $j $k..)

It is also the most flexible in usage, and has a better readability from my view.

Visual Studio: LINK : fatal error LNK1181: cannot open input file

For me the problem was a wrong include directory. I have no idea why this caused the error with the seemingly missing lib as the include directory only contains the header files. And the library directory had the correct path set.

Insert if not exists Oracle

Coming late to the party, but...

With oracle 11.2.0.1 there is a semantic hint that can do this: IGNORE_ROW_ON_DUPKEY_INDEX

Example:

insert /*+ IGNORE_ROW_ON_DUPKEY_INDEX(customer_orders,pk_customer_orders) */
  into customer_orders
       (order_id, customer, product)
values (    1234,     9876,  'K598')
     ;

UPDATE: Although this hint works (if you spell it correctly), there are better approaches which don't require Oracle 11R2:

First approach—direct translation of above semantic hint:

begin
  insert into customer_orders
         (order_id, customer, product)
  values (    1234,     9876,  'K698')
  ;
  commit;
exception
  when DUP_VAL_ON_INDEX
  then ROLLBACK;
end;

Second aproach—a lot faster than both above hints when there's a lot of contention:

begin
    select count (*)
    into   l_is_matching_row
    from   customer_orders
    where  order_id = 1234
    ;

    if (l_is_matching_row = 0)
    then
      insert into customer_orders
             (order_id, customer, product)
      values (    1234,     9876,  'K698')
      ;
      commit;
    end if;
exception
  when DUP_VAL_ON_INDEX
  then ROLLBACK;
end;

What does 'low in coupling and high in cohesion' mean

An example might be helpful. Imagine a system which generates data and puts it into a data store, either a file on disk or a database.

High Cohesion can be achieved by separate the data store code from the data production code. (and in fact separating the disk storage from the database storage).

Low Coupling can be achieved by making sure that the data production doesn't have any unnecessary knowledge of the data store (e.g. doesn't ask the data store about filenames or db connections).

How to add multiple jar files in classpath in linux

The classpath is the place(s) where the java compiler (command: javac) and the JVM (command:java) look in order to find classes which your application reference. What does it mean for an application to reference another class ? In simple words it means to use that class somewhere in its code:

Example:

public class MyClass{
    private AnotherClass referenceToAnotherClass;
    .....
}

When you try to compile this (javac) the compiler will need the AnotherClass class. The same when you try to run your application: the JVM will need the AnotherClass class. In order to to find this class the javac and the JVM look in a particular (set of) place(s). Those places are specified by the classpath which on linux is a colon separated list of directories (directories where the javac/JVM should look in order to locate the AnotherClass when they need it).

So in order to compile your class and then to run it, you should make sure that the classpath contains the directory containing the AnotherClass class. Then you invoke it like this:

javac -classpath "dir1;dir2;path/to/AnotherClass;...;dirN" MyClass.java //to compile it
java -classpath "dir1;dir2;path/to/AnotherClass;...;dirN" MyClass //to run it

Usually classes come in the form of "bundles" called jar files/libraries. In this case you have to make sure that the jar containing the AnotherClass class is on your classpaht:

javac -classpath "dir1;dir2;path/to/jar/containing/AnotherClass;...;dirN" MyClass.java //to compile it
java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;...;dirN" MyClass //to run it

In the examples above you can see how to compile a class (MyClass.java) located in the working directory and then run the compiled class (Note the "." at the begining of the classpath which stands for current directory). This directory has to be added to the classpath too. Otherwise, the JVM won't be able to find it.

If you have your class in a jar file, as you specified in the question, then you have to make sure that jar is in the classpath too , together with the rest of the needed directories.

Example:

java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;path/to/MyClass/jar...;dirN" MyClass //to run it

or more general (assuming some package hierarchy):

java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;path/to/MyClass/jar...;dirN" package.subpackage.MyClass //to run it

In order to avoid setting the classpath everytime you want to run an application you can define an environment variable called CLASSPATH.

In linux, in command prompt:

export CLASSPATH="dir1;dir2;path/to/jar/containing/AnotherClass;...;dirN" 

or edit the ~/.bashrc and add this line somewhere at the end;

However, the class path is subject to frequent changes so, you might want to have the classpath set to a core set of dirs, which you need frequently and then extends the classpath each time you need for that session only. Like this:

export CLASSPATH=$CLASSPATH:"new directories according to your current needs" 

OrderBy pipe issue

In the current version of Angular2, orderBy and ArraySort pipes are not supported. You need to write/use some custom pipes for this.

Hiding user input on terminal in Linux script

for a solution that works without bash or certain features from read you can use stty to disable echo

stty_orig=$(stty -g)
stty -echo
read password
stty $stty_orig

how to remove the first two columns in a file using shell (awk, sed, whatever)

Using awk, and based in some of the options below, using a for loop makes a bit more flexible; sometimes I may want to delete the first 9 columns ( if I do an "ls -lrt" for example), so I change the 2 for a 9 and that's it:

awk '{ for(i=0;i++<2;){$i=""}; print $0 }' your_file.txt

Creating composite primary key in SQL Server

If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.

enter image description here

Command for this is,

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID)

Can I dispatch an action in reducer?

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

Sounds like your initialized AudioElement class and the event listener belong within a component rather than in state. Within the event listener you can dispatch an action, which will update progress in state.

You can either initialize the AudioElement class object in a new React component or just convert that class to a React component.

class MyAudioPlayer extends React.Component {
  constructor(props) {
    super(props);

    this.player = new AudioElement('test.mp3');

    this.player.audio.ontimeupdate = this.updateProgress;
  }

  updateProgress () {
    // Dispatch action to reducer with updated progress.
    // You might want to actually send the current time and do the
    // calculation from within the reducer.
    this.props.updateProgressAction();
  }

  render () {
    // Render the audio player controls, progress bar, whatever else
    return <p>Progress: {this.props.progress}</p>;
  }
}

class MyContainer extends React.Component {
   render() {
     return <MyAudioPlayer updateProgress={this.props.updateProgress} />
   }
}

function mapStateToProps (state) { return {}; }

return connect(mapStateToProps, {
  updateProgressAction
})(MyContainer);

Note that the updateProgressAction is automatically wrapped with dispatch so you don't need to call dispatch directly.

React Native absolute positioning horizontal centre

Wrap the child you want centered in a View and make the View absolute.

<View style={{position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'center', alignItems: 'center'}}>
  <Text>Centered text</Text>
</View>

Why do some functions have underscores "__" before and after the function name?

From the Python PEP 8 -- Style Guide for Python Code:

Descriptive: Naming Styles

The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')

  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

  • __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

The solution for me was to update guest additions

(click Devices -> Insert Guest Additions CD image)

Is it possible to Turn page programmatically in UIPageViewController?

For single page, I just edited the answer of @Jack Humphries

-(void)viewDidLoad
{
  counter = 0;
}
-(IBAction)buttonClick:(id)sender
{
  counter++;
  DataViewController *secondVC = [self.modelController viewControllerAtIndex:counter storyboard:self.storyboard];
  NSArray *viewControllers = nil;          
  viewControllers = [NSArray arrayWithObjects:secondVC, nil];          
  [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
}

How to read multiple Integer values from a single line of input in Java?

When we want to take Integer as inputs
For just 3 inputs as in your case:

import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();

For more number of inputs we can use a loop:

import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
    a[i] = scan.nextInt();    
}

How can I send and receive WebSocket messages on the server side?

Note: This is some explanation and pseudocode as to how to implement a very trivial server that can handle incoming and outcoming WebSocket messages as per the definitive framing format. It does not include the handshaking process. Furthermore, this answer has been made for educational purposes; it is not a full-featured implementation.

Specification (RFC 6455)


Sending messages

(In other words, server → browser)

The frames you're sending need to be formatted according to the WebSocket framing format. For sending messages, this format is as follows:

  • one byte which contains the type of data (and some additional info which is out of scope for a trivial server)
  • one byte which contains the length
  • either two or eight bytes if the length does not fit in the second byte (the second byte is then a code saying how many bytes are used for the length)
  • the actual (raw) data

The first byte will be 1000 0001 (or 129) for a text frame.

The second byte has its first bit set to 0 because we're not encoding the data (encoding from server to client is not mandatory).

It is necessary to determine the length of the raw data so as to send the length bytes correctly:

  • if 0 <= length <= 125, you don't need additional bytes
  • if 126 <= length <= 65535, you need two additional bytes and the second byte is 126
  • if length >= 65536, you need eight additional bytes, and the second byte is 127

The length has to be sliced into separate bytes, which means you'll need to bit-shift to the right (with an amount of eight bits), and then only retain the last eight bits by doing AND 1111 1111 (which is 255).

After the length byte(s) comes the raw data.

This leads to the following pseudocode:

bytesFormatted[0] = 129

indexStartRawData = -1 // it doesn't matter what value is
                       // set here - it will be set now:

if bytesRaw.length <= 125
    bytesFormatted[1] = bytesRaw.length

    indexStartRawData = 2

else if bytesRaw.length >= 126 and bytesRaw.length <= 65535
    bytesFormatted[1] = 126
    bytesFormatted[2] = ( bytesRaw.length >> 8 ) AND 255
    bytesFormatted[3] = ( bytesRaw.length      ) AND 255

    indexStartRawData = 4

else
    bytesFormatted[1] = 127
    bytesFormatted[2] = ( bytesRaw.length >> 56 ) AND 255
    bytesFormatted[3] = ( bytesRaw.length >> 48 ) AND 255
    bytesFormatted[4] = ( bytesRaw.length >> 40 ) AND 255
    bytesFormatted[5] = ( bytesRaw.length >> 32 ) AND 255
    bytesFormatted[6] = ( bytesRaw.length >> 24 ) AND 255
    bytesFormatted[7] = ( bytesRaw.length >> 16 ) AND 255
    bytesFormatted[8] = ( bytesRaw.length >>  8 ) AND 255
    bytesFormatted[9] = ( bytesRaw.length       ) AND 255

    indexStartRawData = 10

// put raw data at the correct index
bytesFormatted.put(bytesRaw, indexStartRawData)


// now send bytesFormatted (e.g. write it to the socket stream)

Receiving messages

(In other words, browser → server)

The frames you obtain are in the following format:

  • one byte which contains the type of data
  • one byte which contains the length
  • either two or eight additional bytes if the length did not fit in the second byte
  • four bytes which are the masks (= decoding keys)
  • the actual data

The first byte usually does not matter - if you're just sending text you are only using the text type. It will be 1000 0001 (or 129) in that case.

The second byte and the additional two or eight bytes need some parsing, because you need to know how many bytes are used for the length (you need to know where the real data starts). The length itself is usually not necessary since you have the data already.

The first bit of the second byte is always 1 which means the data is masked (= encoded). Messages from the client to the server are always masked. You need to remove that first bit by doing secondByte AND 0111 1111. There are two cases in which the resulting byte does not represent the length because it did not fit in the second byte:

  • a second byte of 0111 1110, or 126, means the following two bytes are used for the length
  • a second byte of 0111 1111, or 127, means the following eight bytes are used for the length

The four mask bytes are used for decoding the actual data that has been sent. The algorithm for decoding is as follows:

decodedByte = encodedByte XOR masks[encodedByteIndex MOD 4]

where encodedByte is the original byte in the data, encodedByteIndex is the index (offset) of the byte counting from the first byte of the real data, which has index 0. masks is an array containing of the four mask bytes.

This leads to the following pseudocode for decoding:

secondByte = bytes[1]

length = secondByte AND 127 // may not be the actual length in the two special cases

indexFirstMask = 2          // if not a special case

if length == 126            // if a special case, change indexFirstMask
    indexFirstMask = 4

else if length == 127       // ditto
    indexFirstMask = 10

masks = bytes.slice(indexFirstMask, 4) // four bytes starting from indexFirstMask

indexFirstDataByte = indexFirstMask + 4 // four bytes further

decoded = new array

decoded.length = bytes.length - indexFirstDataByte // length of real data

for i = indexFirstDataByte, j = 0; i < bytes.length; i++, j++
    decoded[j] = bytes[i] XOR masks[j MOD 4]


// now use "decoded" to interpret the received data

How do I pass named parameters with Invoke-Command?

I needed something to call scripts with named parameters. We have a policy of not using ordinal positioning of parameters and requiring the parameter name.

My approach is similar to the ones above but gets the content of the script file that you want to call and sends a parameter block containing the parameters and values.

One of the advantages of this is that you can optionally choose which parameters to send to the script file allowing for non-mandatory parameters with defaults.

Assuming there is a script called "MyScript.ps1" in the temporary path that has the following parameter block:

[CmdletBinding(PositionalBinding = $False)]
param
(
    [Parameter(Mandatory = $True)] [String] $MyNamedParameter1,
    [Parameter(Mandatory = $True)] [String] $MyNamedParameter2,
    [Parameter(Mandatory = $False)] [String] $MyNamedParameter3 = "some default value"
)

This is how I would call this script from another script:

$params = @{
    MyNamedParameter1 = $SomeValue
    MyNamedParameter2 = $SomeOtherValue
}

If ($SomeCondition)
{
    $params['MyNamedParameter3'] = $YetAnotherValue
}

$pathToScript = Join-Path -Path $env:Temp -ChildPath MyScript.ps1

$sb = [scriptblock]::create(".{$(Get-Content -Path $pathToScript -Raw)} $(&{
        $args
} @params)")
Invoke-Command -ScriptBlock $sb

I have used this in lots of scenarios and it works really well. One thing that you occasionally need to do is put quotes around the parameter value assignment block. This is always the case when there are spaces in the value.

e.g. This param block is used to call a script that copies various modules into the standard location used by PowerShell C:\Program Files\WindowsPowerShell\Modules which contains a space character.

$params = @{
        SourcePath      = "$WorkingDirectory\Modules"
        DestinationPath = "'$(Join-Path -Path $([System.Environment]::GetFolderPath('ProgramFiles')) -ChildPath 'WindowsPowershell\Modules')'"
    }

Hope this helps!

Differences between "BEGIN RSA PRIVATE KEY" and "BEGIN PRIVATE KEY"

See https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem (search the page for "BEGIN RSA PRIVATE KEY") (archive link for posterity, just in case).

BEGIN RSA PRIVATE KEY is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. BEGIN PRIVATE KEY is PKCS#8 and indicates that the key type is included in the key data itself. From the link:

The unencrypted PKCS#8 encoded data starts and ends with the tags:

-----BEGIN PRIVATE KEY-----
BASE64 ENCODED DATA
-----END PRIVATE KEY-----

Within the base64 encoded data the following DER structure is present:

PrivateKeyInfo ::= SEQUENCE {
  version         Version,
  algorithm       AlgorithmIdentifier,
  PrivateKey      BIT STRING
}

AlgorithmIdentifier ::= SEQUENCE {
  algorithm       OBJECT IDENTIFIER,
  parameters      ANY DEFINED BY algorithm OPTIONAL
}

So for an RSA private key, the OID is 1.2.840.113549.1.1.1 and there is a RSAPrivateKey as the PrivateKey key data bitstring.

As opposed to BEGIN RSA PRIVATE KEY, which always specifies an RSA key and therefore doesn't include a key type OID. BEGIN RSA PRIVATE KEY is PKCS#1:

RSA Private Key file (PKCS#1)

The RSA private key PEM file is specific for RSA keys.

It starts and ends with the tags:

-----BEGIN RSA PRIVATE KEY-----
BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----

Within the base64 encoded data the following DER structure is present:

RSAPrivateKey ::= SEQUENCE {
  version           Version,
  modulus           INTEGER,  -- n
  publicExponent    INTEGER,  -- e
  privateExponent   INTEGER,  -- d
  prime1            INTEGER,  -- p
  prime2            INTEGER,  -- q
  exponent1         INTEGER,  -- d mod (p-1)
  exponent2         INTEGER,  -- d mod (q-1)
  coefficient       INTEGER,  -- (inverse of q) mod p
  otherPrimeInfos   OtherPrimeInfos OPTIONAL
}

How to enter command with password for git pull?

This is not exactly what you asked for, but for http(s):

  • you can put the password in .netrc file (_netrc on windows). From there it would be picked up automatically. It would go to your home folder with 600 permissions.
  • you could also just clone the repo with https://user:pass@domain/repo but that's not really recommended as it would show your user/pass in a lot of places...
  • a new option is to use the credential helper. Note that credentials would be stored in clear text in your local config using standard credential helper. credential-helper with wincred can be also used on windows.

Usage examples for credential helper

  • git config credential.helper store - stores the credentials indefinitely.
  • git config credential.helper 'cache --timeout=3600'- stores for 60 minutes

For ssh-based access, you'd use ssh agent that will provide the ssh key when needed. This would require generating keys on your computer, storing the public key on the remote server and adding the private key to relevant keystore.

How to pause a vbscript execution?

You can use a WScript object and call the Sleep method on it:

Set WScript = CreateObject("WScript.Shell")
WScript.Sleep 2000 'Sleeps for 2 seconds

Another option is to import and use the WinAPI function directly (only works in VBA, thanks @Helen):

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sleep 2000

Java Loop every minute

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();

Programmatically shut down Spring Boot application

In the application you can use SpringApplication. This has a static exit() method that takes two arguments: the ApplicationContext and an ExitCodeGenerator:

i.e. you can declare this method:

@Autowired
public void shutDown(ExecutorServiceExitCodeGenerator exitCodeGenerator) {
    SpringApplication.exit(applicationContext, exitCodeGenerator);
}

Inside the Integration tests you can achieved it by adding @DirtiesContext annotation at class level:

  • @DirtiesContext(classMode=ClassMode.AFTER_CLASS) - The associated ApplicationContext will be marked as dirty after the test class.
  • @DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD) - The associated ApplicationContext will be marked as dirty after each test method in the class.

i.e.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class},
    webEnvironment= SpringBootTest.WebEnvironment.DEFINED_PORT, properties = {"server.port:0"})
@DirtiesContext(classMode= DirtiesContext.ClassMode.AFTER_CLASS)
public class ApplicationIT {
...

ArrayBuffer to base64 encoded string

Below are 2 simple functions for converting Uint8Array to Base64 String and back again

arrayToBase64String(a) {
    return btoa(String.fromCharCode(...a));
}

base64StringToArray(s) {
    let asciiString = atob(s);
    return new Uint8Array([...asciiString].map(char => char.charCodeAt(0)));
}

How can I push a specific commit to a remote, and not previous commits?

Cherry-pick works best compared to all other methods while pushing a specific commit.

The way to do that is:

Create a new branch -

git branch <new-branch>

Update your new-branch with your origin branch -

git fetch

git rebase

These actions will make sure that you exactly have the same stuff as your origin has.

Cherry-pick the sha id that you want to do push -

git cherry-pick <sha id of the commit>

You can get the sha id by running

git log

Push it to your origin -

git push

Run gitk to see that everything looks the same way you wanted.

What is the difference between a static and const variable?

const is equivalent to #define but only for value statements(e.g. #define myvalue = 2). The value declared replaces the name of the variable before compilation.

static is a variable. The value can change, but the variable will persist throughout the execution of the program even if the variable is declared in a function. It is equivalent to a global variable who's usage scope is the scope of the block they have been declared in, but their value's scope is global.

As such, static variables are only initialized once. This is especially important if the variable is declared in a function, since it guarantees the initialization will only take place at the first call to the function.

Another usage of statics involves objects. Declaring a static variable in an object has the effect that this value is the same for all instances of the object. As such, it cannot be called with the object's name, but only with the class's name.

public class Test 
{ 
    public static int test;
}
Test myTestObject=new Test();
myTestObject.test=2;//ERROR
Test.test=2;//Correct

In languages like C and C++, it is meaningless to declare static global variables, but they are very useful in functions and classes. In managed languages, the only way to have the effect of a global variable is to declare it as static.

Pythonic way to check if a list is sorted or not

SapphireSun is quite right. You can just use lst.sort(). Python's sort implementation (TimSort) check if the list is already sorted. If so sort() will completed in linear time. Sounds like a Pythonic way to ensure a list is sorted ;)

AttributeError: 'list' object has no attribute 'encode'

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]

How to detect online/offline event cross-browser?

well, you can try the javascript plugin which can monitor the browser connection in real time and notifies the user if internet or the browsers connection with the internet went down.

Wiremonkey Javascript plugin and the demo you can find here

http://ryvan-js.github.io/

Split data frame string column into multiple columns

Since R version 3.4.0 you can use strcapture() from the utils package (included with base R installs), binding the output onto the other column(s).

out <- strcapture(
    "(.*)_and_(.*)",
    as.character(before$type),
    data.frame(type_1 = character(), type_2 = character())
)

cbind(before["attr"], out)
#   attr type_1 type_2
# 1    1    foo    bar
# 2   30    foo  bar_2
# 3    4    foo    bar
# 4    6    foo  bar_2

String comparison in bash. [[: not found

[[ is a bash-builtin. Your /bin/bash doesn't seem to be an actual bash.

From a comment:

Add #!/bin/bash at the top of file

Can we pass parameters to a view in SQL?

A hacky way to do it without stored procedures or functions would be to create a settings table in your database, with columns Id, Param1, Param2, etc. Insert a row into that table containing the values Id=1,Param1=0,Param2=0, etc. Then you can add a join to that table in your view to create the desired effect, and update the settings table before running the view. If you have multiple users updating the settings table and running the view concurrently things could go wrong, but otherwise it should work OK. Something like:

CREATE VIEW v_emp 
AS 
SELECT      * 
FROM        emp E
INNER JOIN  settings S
ON          S.Id = 1 AND E.emp_id = S.Param1

How to find the minimum value of a column in R?

If you prefer using column names, you could do something like this as an alternative:

min(data$column_name)

Struct Constructor in C++?

Note that there is one interesting difference (at least with the MS C++ compiler):


If you have a plain vanilla struct like this

struct MyStruct {
   int id;
   double x;
   double y;
} MYSTRUCT;

then somewhere else you might initialize an array of such objects like this:

MYSTRUCT _pointList[] = { 
   { 1, 1.0, 1.0 }, 
   { 2, 1.0, 2.0 }, 
   { 3, 2.0, 1.0 }
};

however, as soon as you add a user-defined constructor to MyStruct such as the ones discussed above, you'd get an error like this:

    'MyStruct' : Types with user defined constructors are not aggregate
     <file and line> : error C2552: '_pointList' : non-aggregates cannot 
     be initialized with initializer list.

So that's at least one other difference between a struct and a class. This kind of initialization may not be good OO practice, but it appears all over the place in the legacy WinSDK c++ code that I support. Just so you know...

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

I resorted to adding Analytics via cocoa pods again and disabled bit code for now.

Hopefully a future cocoa pods version will support it.

C++ vector's insert & push_back difference

Beside the fact, that push_back(x) does the same as insert(x, end()) (maybe with slightly better performance), there are several important thing to know about these functions:

  1. push_back exists only on BackInsertionSequence containers - so, for example, it doesn't exist on set. It couldn't because push_back() grants you that it will always add at the end.
  2. Some containers can also satisfy FrontInsertionSequence and they have push_front. This is satisfied by deque, but not by vector.
  3. The insert(x, ITERATOR) is from InsertionSequence, which is common for set and vector. This way you can use either set or vector as a target for multiple insertions. However, set has additionally insert(x), which does practically the same thing (this first insert in set means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).

Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x) and container.insert(x, container.end()) will do effectively the same thing. However this won't be true if you get this container.end() first and then use it in the whole loop.

For example, you could risk the following code:

auto pe = v.end();
for (auto& s: a)
    v.insert(pe, v);

This will effectively copy whole a into v vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve() first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.

If you do it this way:

copy(a.begin(), a.end(), back_inserter(v);

it will copy a at the end of v in the original order, and this doesn't carry a risk of iterator invalidation.

[EDIT] I made previously this code look this way, and it was a mistake because inserter actually maintains the validity and advancement of the iterator:

copy(a.begin(), a.end(), inserter(v, v.end());

So this code will also add all elements in the original order without any risk.

How to assign colors to categorical variables in ggplot2 that have stable mapping?

The easiest solution is to convert your categorical variable to a factor prior to the subsetting. Bottomline is that you need a factor variable with exact the same levels in all your subsets.

library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100), 
    x = rnorm(500, mean = rep(1:5, 100)), y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))

With a character variable

ggplot(dataset, aes(x = x, y = y, colour = category)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = category)) + geom_point()

With a factor variable

ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()

CSS table column autowidth

If you want to make sure that last row does not wrap and thus size the way you want it, have a look at

td {
 white-space: nowrap;
}

ImportError: No module named Crypto.Cipher

I found the solution. Issue is probably in case sensitivity (on Windows).

Just change the name of the folder:

  • C:\Python27\Lib\site-packages\crypto
  • to: C:\Python27\Lib\site-packages\Crypto

This is how folder was named after installation of pycrypto: enter image description here

I've changed it to: enter image description here

And now the following code works fine: enter image description here

HAProxy redirecting http to https (ssl)

A slight variation of user2966600's solution...

To redirect all except a single URL (In case of multiple frontend/backend):

redirect scheme https if !{ hdr(Host) -i www.mydomain.com } !{ ssl_fc }

How can I make an "are you sure" prompt in a Windows batchfile?

First, open the terminal.

Then, type

cd ~
touch .sure
chmod 700 .sure

Next, open .sure and paste this inside.

#!/bin/bash --init-file
PS1='> '
alias y='
    $1
    exit
'
alias n='Taskkill /IM %Terminal% /f'
echo ''
echo 'Are you sure? Answer y or n.'
echo ''

After that, close the file.

~/.sure ; ENTER COMMAND HERE

This will give you a prompt of are you sure before continuing the command.

Second line in li starts under the bullet after CSS-reset

The li tag has a property called list-style-position. This makes your bullets inside or outside the list. On default, it’s set to inside. That makes your text wrap around it. If you set it to outside, the text of your li tags will be aligned.

The downside of that is that your bullets won't be aligned with the text outside the ul. If you want to align it with the other text you can use a margin.

ul li {
    /*
     * We want the bullets outside of the list,
     * so the text is aligned. Now the actual bullet
     * is outside of the list’s container
     */
    list-style-position: outside;

    /*
     * Because the bullet is outside of the list’s
     * container, indent the list entirely
     */
    margin-left: 1em;
}

Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement

  • Changed the code block to provide just the solution
  • Changed the indentation unit to em’s
  • Each property is applied to the ul element
  • Good comments :)

Javascript: Load an Image from url and display

Add a div with ID imgDiv and make your script

 document.getElementById('imgDiv').innerHTML='<img src=\'http://webpage.com/images/'+document.getElementById('imagename').value +'.png\'>'

I tried to stay as close to your original as tp not overwhelm you with jQuery and such

UPDATE and REPLACE part of a string

You have one table where you have date Code which is seven character something like

"32-1000"

Now you want to replace all

"32-"

With

"14-"

The SQL query you have to run is

Update Products Set Code = replace(Code, '32-', '14-') Where ...(Put your where statement in here)

Converting A String To Hexadecimal In Java

Use DatatypeConverter.printHexBinary():

public static String toHexadecimal(String text) throws UnsupportedEncodingException
{
    byte[] myBytes = text.getBytes("UTF-8");

    return DatatypeConverter.printHexBinary(myBytes);
}

Example usage:

System.out.println(toHexadecimal("Hello StackOverflow"));

Prints:

48656C6C6F20537461636B4F766572666C6F77

Note: This causes a little extra trouble with Java 9 and newer since the API is not included by default. For reference e.g. see this GitHub issue.

Clone contents of a GitHub repository (without the folder itself)

this worker for me

git clone <repository> .

How to change current working directory using a batch file

Just use cd /d %root% to switch driver letters and change directories.

Alternatively, use pushd %root% to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd to switch back.

Note that pushd will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd for that directory.

How to capture multiple repeated groups?

I think you need something like this....

b="HELLO,THERE,WORLD"
re.findall('[\w]+',b)

Which in Python3 will return

['HELLO', 'THERE', 'WORLD']

Specify sudo password for Ansible

You can pass variable on the command line via --extra-vars "name=value". Sudo password variable is ansible_sudo_pass. So your command would look like:

ansible-playbook playbook.yml -i inventory.ini --user=username \
                              --extra-vars "ansible_sudo_pass=yourPassword"

Update 2017: Ansible 2.2.1.0 now uses var ansible_become_pass. Either seems to work.

Auto start node.js server on boot

Copied directly from this answer:

You could write a script in any language you want to automate this (even using nodejs) and then just install a shortcut to that script in the user's %appdata%\Microsoft\Windows\Start Menu\Programs\Startup folder

Check if the file exists using VBA

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function

How do I copy folder with files to another folder in Unix/Linux?

You are looking for the cp command. You need to change directories so that you are outside of the directory you are trying to copy.

If the directory you're copying is called dir1 and you want to copy it to your /home/Pictures folder:

cp -r dir1/ ~/Pictures/

Linux is case-sensitive and also needs the / after each directory to know that it isn't a file. ~ is a special character in the terminal that automatically evaluates to the current user's home directory. If you need to know what directory you are in, use the command pwd.

When you don't know how to use a Linux command, there is a manual page that you can refer to by typing:

man [insert command here]

at a terminal prompt.

Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you've started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.

Get the last day of the month in SQL

Take some base date which is the 31st of some month e.g. '20011231'. Then use the
following procedure (I have given 3 identical examples below, only the @dt value differs).

declare @dt datetime;

set @dt = '20140312'

SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');



set @dt = '20140208'

SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');



set @dt = '20140405'

SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');

How to copy and edit files in Android shell?

To copy dirs, it seems you can use adb pull <remote> <local> if you want to copy file/dir from device, and adb push <local> <remote> to copy file/dir to device. Alternatively, just to copy a file, you can use a simple trick: cat source_file > dest_file. Note that this does not work for user-inaccessible paths.

To edit files, I have not found a simple solution, just some possible workarounds. Try this, it seems you can (after the setup) use it to edit files like busybox vi <filename>. Nano seems to be possible to use too.

Context.startForegroundService() did not then call Service.startForeground()

I called ContextCompat.startForegroundService(this, intent) to start the service then

In service onCreate

 @Override
 public void onCreate() {
        super.onCreate();

        if (Build.VERSION.SDK_INT >= 26) {
            String CHANNEL_ID = "my_channel_01";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);

            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("")
                    .setContentText("").build();

            startForeground(1, notification);
        }
}

mysql datatype for telephone number and address

i would use a varchar for telephone numbers. that way you can also store + and (), which is sometimes seen in tel numbers (as you mentioned yourself). and you don't have to worry about using up all bits in integers.

How to skip "are you sure Y/N" when deleting files in batch files

Add /Q for quiet mode and it should remove the prompt.

How do I unlock a SQLite database?

If a process has a lock on an SQLite DB and crashes, the DB stays locked permanently. That's the problem. It's not that some other process has a lock.

How to send redirect to JSP page in Servlet

Look at the HttpServletResponse#sendRedirect(String location) method.

Use it as:

response.sendRedirect(request.getContextPath() + "/welcome.jsp")

Alternatively, look at HttpServletResponse#setHeader(String name, String value) method.

The redirection is set by adding the location header:

response.setHeader("Location", request.getContextPath() + "/welcome.jsp");

MySQL Trigger: Delete From Table AFTER DELETE

I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)

Try this as the new trigger:

CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
    WHERE patron_info.pid = old.id;
END

Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.

What is the time complexity of indexing, inserting and removing from common data structures?

Keep in mind that unless you're writing your own data structure (e.g. linked list in C), it can depend dramatically on the implementation of data structures in your language/framework of choice. As an example, take a look at the benchmarks of Apple's CFArray over at Ridiculous Fish. In this case, the data type, a CFArray from Apple's CoreFoundation framework, actually changes data structures depending on how many objects are actually in the array - changing from linear time to constant time at around 30,000 objects.

This is actually one of the beautiful things about object-oriented programming - you don't need to know how it works, just that it works, and the 'how it works' can change depending on requirements.

Iterating through struct fieldnames in MATLAB

Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.

fns{i}
teststruct.(fns{i})

Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.

name_as_char = 'a'
name_as_cellstr = {'a'}

How to run Gradle from the command line on Mac bash

./gradlew

Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. . means "current directory".

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

jQuery check if <input> exists and has a value

You can do something like this:

jQuery.fn.existsWithValue = function() { 
    return this.length && this.val().length; 
}

if ($(selector).existsWithValue()) {
        // Do something
}

Importing CSV data using PHP/MySQL

set_time_limit(10000);

$con = mysql_connect('127.0.0.1','root','password');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("db", $con);

$fp = fopen("file.csv", "r");

while( !feof($fp) ) {
  if( !$line = fgetcsv($fp, 1000, ';', '"')) {
     continue;
  }

    $importSQL = "INSERT INTO table_name VALUES('".$line[0]."','".$line[1]."','".$line[2]."')";

    mysql_query($importSQL) or die(mysql_error());  

}

fclose($fp);
mysql_close($con);

Cannot connect to SQL Server named instance from another SQL Server

Your test cases where you cannot connect with "ServerName\Instance" but ARE able to connect to the server via "ServerName,Port" is what happens when you VPN into a network with Microsoft VPN. (I had this issue). For my VPN Issue I simply use the static port numbers to get around it.

This is appearently due to VPN not forwarding UDP Packets, allowing only TCP Connections.

In your case your firewall or security settings or antivirus or whatever may be blocking UDP.

I would suggest you check your firewall setting to specifically allow for UDP.

Browser Artical

On startup, SQL Server Browser starts and claims UDP port 1434. SQL Server Browser reads the registry, identifies all SQL Server instances on the computer, and notes the ports and named pipes that they use. When a server has two or more network cards, SQL Server Browser will return all ports enabled for SQL Server. SQL Server 2005 and SQL Server Browser support ipv6 and ipv4.

When SQL Server 2000 and SQL Server 2005 clients request SQL Server resources, the client network library sends a UDP message to the server using port 1434. SQL Server Browser responds with the TCP/IP port or named pipe of the requested instance. The network library on the client application then completes the connection by sending a request to the server using the port or named pipe of the desired instance.

Using a Firewall

To communicate with the SQL Server Browser service on a server behind a firewall, open UDP port 1434 in addition to the TCP port used by SQL Server (for example, 1433).

Convert string to datetime

Keep it simple with new Date(string). This should do it...

const s = '01-01-1970 00:03:44';
const d = new Date(s);
console.log(d); // ---> Thu Jan 01 1970 00:03:44 GMT-0500 (Eastern Standard Time)

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date


EDIT: "Code Different" left a valuable comment that MDN no longer recommends using Date as a constructor like this due to browser differences. While the code above works fine in Chrome (v87.0.x) and Edge (v87.0.x), it gives an "Invalid Date" error in Firefox (v84.0.2).

One way to work around this is to make sure your string is in the more universal format of YYYY-MM-DD (obligatory xkcd), e.g., const s = '1970-01-01 00:03:44';, which seems to work in the three major browsers, but this doesn't exactly answer the original question.

Is there a free GUI management tool for Oracle Database Express?

You could try this: it's a very good tool, very fast and effective.

http://code.google.com/p/oracle-gui/

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.

Why does background-color have no effect on this DIV?

Floats don't have a height so the containing div has a height of zero.

<div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

overflow:hidden clears the float for most browsers.

zoom:1 clears the float for IE.

How to scale Docker containers in production

You can try Tsuru. Tsuru is a opensource PaaS inspired in Heroku, and it is already with some products in production at Globo.com(internet arm of the biggest Broadcast Television Company in Brazil)

It manages the entire flow of an application, since the container creation, deploy, routing(with hipache) with many nice features as docker cluster, scaling of units, segregated deploy, etc.

Take a look in our documentation bellow: http://docs.tsuru.io/

Here our post covering our environment: http://blog.tsuru.io/2014/04/04/running-tsuru-in-production-scaling-and-segregating-docker-containers/

Dump a NumPy array into a csv file

Writing record arrays as CSV files with headers requires a bit more work.

This example reads from a CSV file ('example.csv') and writes its contents to another CSV file (out.csv).

import numpy as np

# Write an example CSV file with headers on first line
with open('example.csv', 'w') as fp:
    fp.write('''\
col1,col2,col3
1,100.1,string1
2,222.2,second string
''')

# Read it as a Numpy record array
ar = np.recfromcsv('example.csv')
print(repr(ar))
# rec.array([(1, 100.1, 'string1'), (2, 222.2, 'second string')], 
#           dtype=[('col1', '<i4'), ('col2', '<f8'), ('col3', 'S13')])

# Write as a CSV file with headers on first line
with open('out.csv', 'w') as fp:
    fp.write(','.join(ar.dtype.names) + '\n')
    np.savetxt(fp, ar, '%s', ',')

Note that the above example cannot handle values which are strings with commas. To always enclose non-numeric values within quotes, use the csv package:

import csv

with open('out2.csv', 'wb') as fp:
    writer = csv.writer(fp, quoting=csv.QUOTE_NONNUMERIC)
    writer.writerow(ar.dtype.names)
    writer.writerows(ar.tolist())

Generate GUID in MySQL for existing Data?

MYsql

UPDATE tablename   SET columnName = UUID()

oracle

UPDATE tablename   SET columnName = SYS_GUID();

SQLSERVER

UPDATE tablename   SET columnName = NEWID();;

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Ditto Casper's answer:

puts Dir.pwd

As soon as you know current working directory, specify the file path relatively to that directory.

For example, if your working directory is project root, you can open a file under it directly like this

json_file = File.read(myfile.json)

Python: convert string to byte array

for python 3 it worked for what @HYRY posted. I needed it for a returned data in a dbus.array. This is the only way it worked

s = "ABCD"

from array import array

a = array("B", s)

Format date in a specific timezone

I was having the same issue with Moment.js. I've installed moment-timezone, but the issue wasn't resolved. Then, I did just what here it's exposed, set the timezone and it works like a charm:

moment(new Date({your_date})).zone("+08:00")

Thanks a lot!

Pythonic way to combine FOR loop and IF statement

I liked Alex's answer, because a filter is exactly an if applied to a list, so if you want to explore a subset of a list given a condition, this seems to be the most natural way

mylist = [1,2,3,4,5]
another_list = [2,3,4]

wanted = lambda x:x in another_list

for x in filter(wanted, mylist):
    print(x)

this method is useful for the separation of concerns, if the condition function changes, the only code to fiddle with is the function itself

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

for x in filter(wanted, mylist):
    print(x)

The generator method seems better when you don't want members of the list, but a modification of said members, which seems more fit to a generator

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

generator = (x**0.5 for x in mylist if wanted(x))

for x in generator:
    print(x)

Also, filters work with generators, although in this case it isn't efficient

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

generator = (x**0.9 for x in mylist)

for x in filter(wanted, generator):
    print(x)

But of course, it would still be nice to write like this:

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

# for x in filter(wanted, mylist):
for x in mylist if wanted(x):
    print(x)

Create iOS Home Screen Shortcuts on Chrome for iOS

The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.

Windows batch: sleep

Microsoft has a sleep function you can call directly.

    Usage:  sleep      time-to-sleep-in-seconds
            sleep [-m] time-to-sleep-in-milliseconds
            sleep [-c] commited-memory ratio (1%-100%)

You can just say sleep 1 for example to sleep for 1 second in your batch script.

IMO Ping is a bit of a hack for this use case.

In WPF, what are the differences between the x:Name and Name attributes?

The specified x:Name becomes the name of a field that is created in the underlying code when XAML is processed, and that field holds a reference to the object. In Silverlight, using the managed API, the process of creating this field is performed by the MSBuild target steps, which also are responsible for joining the partial classes for a XAML file and its code-behind. This behavior is not necessarily XAML-language specified; it is the particular implementation that Silverlight applies to use x:Name in its programming and application models.

Read More on MSDN...

Android and setting alpha for (image) view alpha

Use this form to ancient version of android.

ImageView myImageView;
myImageView = (ImageView) findViewById(R.id.img);

AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F);
alpha.setDuration(0); 
alpha.setFillAfter(true); 
myImageView.startAnimation(alpha);

What does android:layout_weight mean?

With layout_weight you can specify a size ratio between multiple views. E.g. you have a MapView and a table which should show some additional information to the map. The map should use 3/4 of the screen and table should use 1/4 of the screen. Then you will set the layout_weight of the map to 3 and the layout_weight of the table to 1.

To get it work you also have to set the height or width (depending on your orientation) to 0px.

What's the easiest way to call a function every 5 seconds in jQuery?

You don't need jquery for this, in plain javascript, the following will work!

var intervalId = window.setInterval(function(){
  /// call your function here
}, 5000);

To stop the loop you can use

clearInterval(intervalId) 

checking memory_limit in PHP

Command line to check ini:

$ php -r "echo ini_get('memory_limit');"

How can the size of an input text box be defined in HTML?

<input size="45" type="text" name="name">

The "size" specifies the visible width in characters of the element input.

You can also use the height and width from css.

<input type="text" name="name" style="height:100px; width:300px;">

Flask - Calling python function on button OnClick event

index.html (index.html should be in templates folder)

<!doctype html>
<html>

<head>
    <title>The jQuery Example</title>

    <h2>jQuery-AJAX in FLASK. Execute function on button click</h2>  

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
    <script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { },
    function(data) { }); return false; }); }); </script> 
</head>

<body>        
        <input type = "button" id = "mybutton" value = "Click Here" />
</body>    

</html>

test.py

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/SomeFunction')
def SomeFunction():
    print('In SomeFunction')
    return "Nothing"



if __name__ == '__main__':
   app.run()

1 = false and 0 = true?

It is common for comparison functions to return 0 on "equals", so that they can also return a negative number for "less than" and a positive number for "greater than". strcmp() and memcmp() work like this.

It is, however, idiomatic for zero to be false and nonzero to be true, because this is how the C flow control and logical boolean operators work. So it might be that the return values chosen for this function are fine, but it is the function's name that is in error (it should really just be called compare() or similar).

Android: How can I print a variable on eclipse console?

If the code you're testing is relatively simple then you can just create a regular Java project in the Package Explorer and copy the code across, run it and fix it there, then copy it back into your Android project.

The fact that System.out is redirected is pretty annoying for quickly testing simple methods, but that's the easiest solution I've found, rather than having to run the device emulator just to see if a regular expression works.

'any' vs 'Object'

any is something specific to TypeScript is explained quite well by alex's answer.

Object refers to the JavaScript object type. Commonly used as {} or sometimes new Object. Most things in javascript are compatible with the object data type as they inherit from it. But any is TypeScript specific and compatible with everything in both directions (not inheritance based). e.g. :

var foo:Object; 
var bar:any;
var num:number;

foo = num; // Not an error
num = foo; // ERROR 

// Any is compatible both ways 
bar = num;
num = bar;  

How to prevent line breaks in list items using CSS

Bootstrap 4 has a class named text-nowrap. It is just what you need.

C/C++ maximum stack size of program

Yes, there is a possibility of stack overflow. The C and C++ standard do not dictate things like stack depth, those are generally an environmental issue.

Most decent development environments and/or operating systems will let you tailor the stack size of a process, either at link or load time.

You should specify which OS and development environment you're using for more targeted assistance.

For example, under Ubuntu Karmic Koala, the default for gcc is 2M reserved and 4K committed but this can be changed when you link the program. Use the --stack option of ld to do that.

Passing a local variable from one function to another

First way is

function function1()
{
  var variable1=12;
  function2(variable1);
}

function function2(val)
{
  var variableOfFunction1 = val;

// Then you will have to use this function for the variable1 so it doesn't really help much unless that's what you want to do. }

Second way is

var globalVariable;
function function1()
{
  globalVariable=12;
  function2();
}

function function2()
{
  var local = globalVariable;
}

Thread-safe List<T> property

It seems like many of the people finding this are wanting a thread safe indexed dynamically sized collection. The closest and easiest thing I know of would be.

System.Collections.Concurrent.ConcurrentDictionary<int, YourDataType>

This would require you to ensure your key is properly incriminated if you want normal indexing behavior. If you are careful .count could suffice as the key for any new key value pairs you add.

HTML button to NOT submit form

I think this is the most annoying little peculiarity of HTML... That button needs to be of type "button" in order to not submit.

<button type="button">My Button</button>

Update 5-Feb-2019: As per the HTML Living Standard (and also HTML 5 specification):

The missing value default and invalid value default are the Submit Button state.

db.collection is not a function when using MongoClient v3.0

For those that want to continue using version ^3.0.1 be aware of the changes to how you use the MongoClient.connect() method. The callback doesn't return db instead it returns client, against which there is a function called db(dbname) that you must invoke to get the db instance you are looking for.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

Grant SELECT on multiple tables oracle

No. As the documentation shows, you can only grant access to one object at a time.

How to convert java.sql.timestamp to LocalDate (java8) java.time?

You can do:

timeStamp.toLocalDateTime().toLocalDate();

Note that timestamp.toLocalDateTime() will use the Clock.systemDefaultZone() time zone to make the conversion. This may or may not be what you want.

Should I use != or <> for not equal in T-SQL?

'<>' is from the SQL-92 standard and '!=' is a proprietary T-SQL operator. It's available in other databases as well, but since it isn't standard you have to take it on a case-by-case basis.

In most cases, you'll know what database you're connecting to so this isn't really an issue. At worst you might have to do a search and replace in your SQL.

How to make the web page height to fit screen height

Fixed positioning will do what you need:

#main
{         
    position:fixed;
    top:0px;
    bottom:0px;
    left:0px;
    right:0px;
}

How to open a PDF file in an <iframe>?

Using an iframe to "render" a PDF will not work on all browsers; it depends on how the browser handles PDF files. Some browsers (such as Firefox and Chrome) have a built-in PDF rendered which allows them to display the PDF inline where as some older browsers (perhaps older versions of IE attempt to download the file instead).

Instead, I recommend checking out PDFObject which is a Javascript library to embed PDFs in HTML files. It handles browser compatibility pretty well and will most likely work on IE8.

In your HTML, you could set up a div to display the PDFs:

<div id="pdfRenderer"></div>

Then, you can have Javascript code to embed a PDF in that div:

var pdf = new PDFObject({
  url: "https://something.com/HTC_One_XL_User_Guide.pdf",
  id: "pdfRendered",
  pdfOpenParams: {
    view: "FitH"
  }
}).embed("pdfRenderer");

How to provide password to a command that prompts for one in bash?

How to use autoexpect to pipe a password into a command:

These steps are illustrated with an Ubuntu 12.10 desktop. The exact commands for your distribution may be slightly different.

This is dangerous because you risk exposing whatever password you use to anyone who can read the autoexpect script file.

DO NOT expose your root password or power user passwords by piping them through expect like this. Root kits WILL find this in an instant and your box is owned.

EXPECT spawns a process, reads text that comes in then sends text predefined in the script file.

  1. Make sure you have expect and autoexpect installed:

    sudo apt-get install expect
    sudo apt-get install expect-dev
    
  2. Read up on it:

    man expect
    man autoexpect
    
  3. Go to your home directory:

    cd /home/el
    
  4. User el cannot chown a file to root and must enter a password:

    touch testfile.txt
    sudo chown root:root testfile.txt 
       [enter password to authorize the changing of the owner]
    
  5. This is the password entry we want to automate. Restart the terminal to ensure that sudo asks us for the password again. Go to /home/el again and do this:

    touch myfile.txt
    
    autoexpect -f my_test_expect.exp sudo chown root:root myfile.txt
    
        [enter password which authorizes the chown to root]
    
    autoexpect done, file is my_test_expect.exp
    
  6. You have created my_test_expect.exp file. Your super secret password is stored plaintext in this file. This should make you VERY uncomfortable. Mitigate some discomfort by restricting permissions and ownership as much as possible:

    sudo chown el my_test_expect.exp     //make el the owner.
    sudo chmod 700 my_test_expect.exp    //make file only readable by el.
    
  7. You see these sorts of commands at the bottom of my_test_expect.exp:

    set timeout -1
    spawn sudo chown root:root myfile.txt
    match_max 100000
    expect -exact "\[sudo\] password for el: "
    send -- "YourPasswordStoredInPlaintext\r"
    expect eof
    
  8. You will need to verify that the above expect commands are appropriate. If the autoexpect script is being overly sensitive or not sensitive enough then it will hang. In this case it's acceptable because the expect is waiting for text that will always arrive.

  9. Run the expect script as user el:

    expect my_test_expect.exp 
    spawn sudo chown root:root myfile.txt
    [sudo] password for el: 
    
  10. The password contained in my_test_expect.exp was piped into a chown to root by user el. To see if the password was accepted, look at myfile.txt:

    ls -l
    -rw-r--r--  1 root root          0 Dec  2 14:48 myfile.txt
    

It worked because it is root, and el never entered a password. If you expose your root, sudo, or power user password with this script, then acquiring root on your box will be easy. Such is the penalty for a security system that lets everybody in no questions asked.

Git merge develop into feature branch outputs "Already up-to-date" while it's not

Step by step self explaining commands for update of feature branch with the latest code from origin "develop" branch:

git checkout develop
git pull -p
git checkout feature_branch
git merge develop
git push origin feature_branch

Merge (with squash) all changes from another branch as a single commit

Found it! Merge command has a --squash option

git checkout master
git merge --squash WIP

at this point everything is merged, possibly conflicted, but not committed. So I can now:

git add .
git commit -m "Merged WIP"

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

Setting environment variable in react-native?

React native does not have the concept of global variables. It enforces modular scope strictly, in order to promote component modularity and reusability.

Sometimes, though, you need components to be aware of their environment. In this case it's very simple to define an Environment module which components can then call to get environment variables, for example:

environment.js

var _Environments = {
    production:  {BASE_URL: '', API_KEY: ''},
    staging:     {BASE_URL: '', API_KEY: ''},
    development: {BASE_URL: '', API_KEY: ''},
}

function getEnvironment() {
    // Insert logic here to get the current platform (e.g. staging, production, etc)
    var platform = getPlatform()

    // ...now return the correct environment
    return _Environments[platform]
}

var Environment = getEnvironment()
module.exports = Environment

my-component.js

var Environment = require('./environment.js')

...somewhere in your code...
var url = Environment.BASE_URL

This creates a singleton environment which can be accessed from anywhere inside the scope of your app. You have to explicitly require(...) the module from any components that use Environment variables, but that is a good thing.

Validation to check if password and confirm password are same is not working

I presume you've got validate_required() function from this page: http://www.w3schools.com/js/js_form_validation.asp?

function validate_required(field,alerttxt)
{
with (field)
  {
  if (value==null||value=="")
    {
    alert(alerttxt);return false;
    }
  else
    {
    return true;
    }
  }
}

In this case your last condition will not work as you expect it.

You can replace it with this:

if (password.value != cpassword.value) { 
   alert("Your password and confirmation password do not match.");
   cpassword.focus();
   return false; 
}

How to set multiple commands in one yaml file with Kubernetes?

I am not sure if the question is still active but due to the fact that I did not find the solution in the above answers I decided to write it down.

I use the following approach:

readinessProbe:
  exec:
    command:
    - sh
    - -c
    - |
      command1
      command2 && command3

I know my example is related to readinessProbe, livenessProbe, etc. but suspect the same case is for the container commands. This provides flexibility as it mirrors a standard script writing in Bash.

Add 2 hours to current time in MySQL?

The DATE_ADD() function will do the trick. (You can also use the ADDTIME() function if you're running at least v4.1.1.)

For your query, this would be:

SELECT * 
FROM courses 
WHERE DATE_ADD(now(), INTERVAL 2 HOUR) > start_time

Or,

SELECT * 
FROM courses 
WHERE ADDTIME(now(), '02:00:00') > start_time

Using NULL in C++?

The downside of NULL in C++ is that it is a define for 0. This is a value that can be silently converted to pointer, a bool value, a float/double, or an int.

That is not very type safe and has lead to actual bugs in an application I worked on.

Consider this:

void Foo(int i);
void Foo(Bar* b);
void Foo(bool b);


main()
{
     Foo(0);         
     Foo(NULL); // same as Foo(0)
} 

C++11 defines a nullptr that is convertible to a null pointer but not to other scalars. This is supported in all modern C++ compilers, including VC++ as of 2008. In older versions of GCC there is a similar feature, but then it was called __null.

How to fix Git error: object file is empty?

I had a similar problem. My laptop ran out of battery during a git operation. Boo.

I didn't have any backups. (N.B. Ubuntu One is not a backup solution for git; it will helpfully overwrite your sane repository with your corrupted one.)

To the git wizards, if this was a bad way to fix it, please leave a comment. It did, however, work for me... at least temporarily.

Step 1: Make a backup of .git (in fact I do this in between every step that changes something, but with a new copy-to name, e.g. .git-old-1, .git-old-2, etc.):

cp -a .git .git-old

Step 2: Run git fsck --full

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
error: object file .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e is empty
fatal: loose object 8b61d0135d3195966b443f6c73fb68466264c68e (stored in .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e) is corrupt

Step 3: Remove the empty file. I figured what the heck; its blank anyway.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ rm .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e 
rm: remove write-protected regular empty file `.git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e'? y

Step 3: Run git fsck again. Continue deleting the empty files. You can also cd into the .git directory and run find . -type f -empty -delete -print to remove all empty files. Eventually git started telling me it was actually doing something with the object directories:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: object file .git/objects/e0/cbccee33aea970f4887194047141f79a363636 is empty
fatal: loose object e0cbccee33aea970f4887194047141f79a363636 (stored in .git/objects/e0/cbccee33aea970f4887194047141f79a363636) is corrupt

Step 4: After deleting all of the empty files, I eventually came to git fsck actually running:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: HEAD: invalid sha1 pointer af9fc0c5939eee40f6be2ed66381d74ec2be895f
error: refs/heads/master does not point to a valid object!
error: refs/heads/master.u1conflict does not point to a valid object!
error: 0e31469d372551bb2f51a186fa32795e39f94d5c: invalid sha1 pointer in cache-tree
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
missing blob 8b61d0135d3195966b443f6c73fb68466264c68e
missing blob e89896b1282fbae6cf046bf21b62dd275aaa32f4
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a
missing blob caab8e3d18f2b8c8947f79af7885cdeeeae192fd
missing blob e4cf65ddf80338d50ecd4abcf1caf1de3127c229

Step 5: Try git reflog. Fail because my HEAD is broken.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git reflog
fatal: bad object HEAD

Step 6: Google. Find this. Manually get the last two lines of the reflog:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ tail -n 2 .git/logs/refs/heads/master
f2d4c4868ec7719317a8fce9dc18c4f2e00ede04 9f0abf890b113a287e10d56b66dbab66adc1662d Nathan VanHoudnos <[email protected]> 1347306977 -0400  commit: up to p. 24, including correcting spelling of my name
9f0abf890b113a287e10d56b66dbab66adc1662d af9fc0c5939eee40f6be2ed66381d74ec2be895f Nathan VanHoudnos <[email protected]> 1347358589 -0400  commit: fixed up to page 28

Step 7: Note that from Step 6 we learned that the HEAD is currently pointing to the very last commit. So let's try to just look at the parent commit:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git show 9f0abf890b113a287e10d56b66dbab66adc1662d
commit 9f0abf890b113a287e10d56b66dbab66adc1662d
Author: Nathan VanHoudnos <nathanvan@XXXXXX>
Date:   Mon Sep 10 15:56:17 2012 -0400

    up to p. 24, including correcting spelling of my name

diff --git a/tex/MCMC-in-IRT.tex b/tex/MCMC-in-IRT.tex
index 86e67a1..b860686 100644
--- a/tex/MCMC-in-IRT.tex
+++ b/tex/MCMC-in-IRT.tex

It worked!

Step 8: So now we need to point HEAD to 9f0abf890b113a287e10d56b66dbab66adc1662d.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git update-ref HEAD 9f0abf890b113a287e10d56b66dbab66adc1662d

Which didn't complain.

Step 9: See what fsck says:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: refs/heads/master.u1conflict does not point to a valid object!
error: 0e31469d372551bb2f51a186fa32795e39f94d5c: invalid sha1 pointer in cache-tree
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
missing blob 8b61d0135d3195966b443f6c73fb68466264c68e
missing blob e89896b1282fbae6cf046bf21b62dd275aaa32f4
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a
missing blob caab8e3d18f2b8c8947f79af7885cdeeeae192fd
missing blob e4cf65ddf80338d50ecd4abcf1caf1de3127c229

Step 10: The invalid sha1 pointer in cache-tree seemed like it was from a (now outdated) index file (source). So I killed it and reset the repo.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ rm .git/index
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git reset
Unstaged changes after reset:
M   tex/MCMC-in-IRT.tex
M   tex/recipe-example/build-example-plots.R
M   tex/recipe-example/build-failure-plots.R

Step 11: Looking at the fsck again...

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: refs/heads/master.u1conflict does not point to a valid object!
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a

The dangling blobs are not errors. I'm not concerned with master.u1conflict, and now that it is working I don't want to touch it anymore!

Step 12: Catching up with my local edits:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git status
# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   tex/MCMC-in-IRT.tex
#   modified:   tex/recipe-example/build-example-plots.R
#   modified:   tex/recipe-example/build-failure-plots.R
#
< ... snip ... >
no changes added to commit (use "git add" and/or "git commit -a")


nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git commit -a -m "recovering from the git fiasco"
[master 7922876] recovering from the git fiasco
 3 files changed, 12 insertions(+), 94 deletions(-)

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git add tex/sept2012_code/example-code-testing.R
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git commit -a -m "adding in the example code"
[master 385c023] adding in the example code
 1 file changed, 331 insertions(+)
 create mode 100644 tex/sept2012_code/example-code-testing.R

So hopefully that can be of some use to people in the future. I'm glad it worked.

Is there a way to add/remove several classes in one single instruction with classList?

The classList property ensures that duplicate classes are not unnecessarily added to the element. In order to keep this functionality, if you dislike the longhand versions or jQuery version, I'd suggest adding an addMany function and removeMany to DOMTokenList (the type of classList):

DOMTokenList.prototype.addMany = function(classes) {
    var array = classes.split(' ');
    for (var i = 0, length = array.length; i < length; i++) {
      this.add(array[i]);
    }
}

DOMTokenList.prototype.removeMany = function(classes) {
    var array = classes.split(' ');
    for (var i = 0, length = array.length; i < length; i++) {
      this.remove(array[i]);
    }
}

These would then be useable like so:

elem.classList.addMany("first second third");
elem.classList.removeMany("first third");

Update

As per your comments, if you wish to only write a custom method for these in the event they are not defined, try the following:

DOMTokenList.prototype.addMany = DOMTokenList.prototype.addMany || function(classes) {...}
DOMTokenList.prototype.removeMany = DOMTokenList.prototype.removeMany || function(classes) {...}

Installing a local module using npm?

So I had a lot of problems with all of the solutions mentioned so far...

I have a local package that I want to always reference (rather than npm link) because it won't be used outside of this project (for now) and also won't be uploaded to an npm repository for wide use as of yet.

I also need it to work on Windows AND Unix, so sym-links aren't ideal.

Pointing to the tar.gz result of (npm package) works for the dependent npm package folder, however this causes issues with the npm cache if you want to update the package. It doesn't always pull in the new one from the referenced npm package when you update it, even if you blow away node_modules and re-do your npm-install for your main project.

so.. This is what worked well for me!

Main Project's Package.json File Snippet:

  "name": "main-project-name",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    ...
    "preinstall": "cd ../some-npm-package-angular && npm install && npm run build"
  },
  "private": true,
  "dependencies": {
    ...
    "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist",
    ...
  }

This achieves 3 things:

  • Avoids the common error (at least with angular npm projects) "index.ts is not part of the compilation." - as it points to the built (dist) folder.
  • Adds a preinstall step to build the referenced npm client package to make sure the dist folder of our dependent package is built.
  • Avoids issues where referencing a tar.gz file locally may be cached by npm and not updated in the main project without lots of cleaning/troubleshooting/re-building/re-installing.

I hope this is clear, and helps someone out.

The tar.gz approach also sort of works..

npm install (file path) also sort of works.

This was all based off of a generated client from an openapi spec that we wanted to keep in a separate location (rather than using copy-pasta for individual files)

====== UPDATE: ======

There are additional errors with a regular development flow with the above solution, as npm's versioning scheme with local files is absolutely terrible. If your dependent package changes frequently, this whole scheme breaks because npm will cache your last version of the project and then blow up when the SHA hash doesn't match anymore with what was saved in your package-lock.json file, among other issues.

As a result, I recommend using the *.tgz approach with a version update for each change. This works by doing three things.

First:

For your dependent package, use the npm library "ng-packagr". This is automatically added to auto-generated client packages created by the angular-typescript code generator for OpenAPI 3.0.

As a result the project that I'm referencing has a "scripts" section within package.json that looks like this:

  "scripts": {
    "build": "ng-packagr -p ng-package.json",
    "package": "npm install && npm run build && cd dist && npm pack"
  },

And the project referencing this other project adds a pre-install step to make sure the dependent project is up to date and rebuilt before building itself:

  "scripts": {
    "preinstall": "npm run clean && cd ../some-npm-package-angular && npm run package"
  },

Second

Reference the built tgz npm package from your main project!

  "dependencies": {
    "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-<packageVersion>.tgz",
    ...
  }

Third

Update the dependent package's version EVERY TIME you update the dependent package. You'll also have to update the version in the main project.

If you do not do this, NPM will choke and use a cached version and explode when the SHA hash doesn't match. NPM versions file-based packages based on the filename changing. It won't check the package itself for an updated version in package.json, and the NPM team stated that they will not fix this, but people keep raising the issue: https://github.com/microsoft/WSL/issues/348

for now, just update the:

"version": "1.0.0-build5",

In the dependent package's package.json file, then update your reference to it in the main project to reference the new filename, ex:

"dependencies": {
       "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-1.0.0-build5.tgz",
        ...
}

You get used to it. Just update the two package.json files - version then the ref to the new filename.

Hope that helps someone...

How to delete an element from an array in C#

Balabaster's answer is correct if you want to remove all instances of the element. If you want to remove only the first one, you would do something like this:

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int firstFoundIndex = Array.IndexOf(numbers, numToRemove);
if (numbers >= 0)
{
    numbers = numbers.Take(firstFoundIndex).Concat(numbers.Skip(firstFoundIndex + 1)).ToArray();
}

Rename Pandas DataFrame Index

If you want to use the same mapping for renaming both columns and index you can do:

mapping = {0:'Date', 1:'SM'}
df.index.names = list(map(lambda name: mapping.get(name, name), df.index.names))
df.rename(columns=mapping, inplace=True)

How to get a key in a JavaScript object by its value?

This is a small extension to the Underscorejs method, and uses Lodash instead:

var getKeyByValue = function(searchValue) {
  return _.findKey(hash, function(hashValue) {
    return searchValue === hashValue;
  });
}

FindKey will search and return the first key which matches the value.
If you want the last match instead, use FindLastKey instead.

Downloading MySQL dump from command line

If you are running the MySQL other than default port:

mysqldump.exe -u username -p -P PORT_NO database > backup.sql

Polynomial time and exponential time

Polynomial time.

A polynomial is a sum of terms that look like Constant * x^k Exponential means something like Constant * k^x

(in both cases, k is a constant and x is a variable).

The execution time of exponential algorithms grows much faster than that of polynomial ones.

Best way to script remote SSH commands in Batch (Windows)

The -m switch of PuTTY takes a path to a script file as an argument, not a command.

Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m

So you have to save your command (command_run) to a plain text file (e.g. c:\path\command.txt) and pass that to PuTTY:

putty.exe -ssh user@host -pw password -m c:\path\command.txt

Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).

A command-line syntax is identical, an output redirection added:

plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt

See Using the command-line connection tool Plink.

And with Plink, you can actually provide the command directly on its command-line:

plink.exe -ssh user@host -pw password command > output.txt

Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

How to merge lists into a list of tuples?

One alternative without using zip:

list_c = [(p1, p2) for idx1, p1 in enumerate(list_a) for idx2, p2 in enumerate(list_b) if idx1==idx2]

In case one wants to get not only tuples 1st with 1st, 2nd with 2nd... but all possible combinations of the 2 lists, that would be done with

list_d = [(p1, p2) for p1 in list_a for p2 in list_b]

os.walk without digging into directories below

In Python 3, I was able to do this:

import os
dir = "/path/to/files/"

#List all files immediately under this folder:
print ( next( os.walk(dir) )[2] )

#List all folders immediately under this folder:
print ( next( os.walk(dir) )[1] )

git stash changes apply to new branch?

Since you've already stashed your changes, all you need is this one-liner:

  • git stash branch <branchname> [<stash>]

From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):

Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.

This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.

What are the advantages and disadvantages of recursion?

For the most part recursion is slower, and takes up more of the stack as well. The main advantage of recursion is that for problems like tree traversal it make the algorithm a little easier or more "elegant". Check out some of the comparisons:

link

random.seed(): What does it do?

Here is a small test that demonstrates that feeding the seed() method with the same argument will cause the same pseudo-random result:

# testing random.seed()

import random

def equalityCheck(l):
    state=None
    x=l[0]
    for i in l:
        if i!=x:
            state=False
            break
        else:
            state=True
    return state


l=[]

for i in range(1000):
    random.seed(10)
    l.append(random.random())

print "All elements in l are equal?",equalityCheck(l)

How to upgrade docker container after its image changed

Consider for this answers:

  • The database name is app_schema
  • The container name is app_db
  • The root password is root123

How to update MySQL when storing application data inside the container

This is considered a bad practice, because if you lose the container, you will lose the data. Although it is a bad practice, here is a possible way to do it:

1) Do a database dump as SQL:

docker exec app_db sh -c 'exec mysqldump app_schema -uroot -proot123' > database_dump.sql

2) Update the image:

docker pull mysql:5.6

3) Update the container:

docker rm -f app_db
docker run --name app_db --restart unless-stopped \
-e MYSQL_ROOT_PASSWORD=root123 \
-d mysql:5.6

4) Restore the database dump:

docker exec app_db sh -c 'exec mysql -uroot -proot123' < database_dump.sql

How to update MySQL container using an external volume

Using an external volume is a better way of managing data, and it makes easier to update MySQL. Loosing the container will not lose any data. You can use docker-compose to facilitate managing multi-container Docker applications in a single host:

1) Create the docker-compose.yml file in order to manage your applications:

version: '2'
services:
  app_db:
    image: mysql:5.6
    restart: unless-stopped
    volumes_from: app_db_data
  app_db_data:
    volumes: /my/data/dir:/var/lib/mysql

2) Update MySQL (from the same folder as the docker-compose.yml file):

docker-compose pull
docker-compose up -d

Note: the last command above will update the MySQL image, recreate and start the container with the new image.

Forking / Multi-Threaded Processes | Bash

I don't like using wait because it gets blocked until the process exits, which is not ideal when there are multiple process to wait on as I can't get a status update until the current process is done. I prefer to use a combination of kill -0 and sleep to this.

Given an array of pids to wait on, I use the below waitPids() function to get a continuous feedback on what pids are still pending to finish.

declare -a pids
waitPids() {
    while [ ${#pids[@]} -ne 0 ]; do
        echo "Waiting for pids: ${pids[@]}"
        local range=$(eval echo {0..$((${#pids[@]}-1))})
        local i
        for i in $range; do
            if ! kill -0 ${pids[$i]} 2> /dev/null; then
                echo "Done -- ${pids[$i]}"
                unset pids[$i]
            fi
        done
        pids=("${pids[@]}") # Expunge nulls created by unset.
        sleep 1
    done
    echo "Done!"
}

When I start a process in the background, I add its pid immediately to the pids array by using this below utility function:

addPid() {
    local desc=$1
    local pid=$2
    echo "$desc -- $pid"
    pids=(${pids[@]} $pid)
}

Here is a sample that shows how to use:

for i in {2..5}; do
    sleep $i &
    addPid "Sleep for $i" $!
done
waitPids

And here is how the feedback looks:

Sleep for 2 -- 36271
Sleep for 3 -- 36272
Sleep for 4 -- 36273
Sleep for 5 -- 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Done -- 36271
Waiting for pids: 36272 36273 36274
Done -- 36272
Waiting for pids: 36273 36274
Done -- 36273
Waiting for pids: 36274
Done -- 36274
Done!

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

How do I compare 2 rows from the same table (SQL Server)?

You can join a table to itself as many times as you require, it is called a self join.

An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.

SELECT a.SelfJoinTableID
FROM   dbo.SelfJoinTable a
       INNER JOIN dbo.SelfJoinTable b
         ON a.SelfJoinTableID = b.SelfJoinTableID
       INNER JOIN dbo.SelfJoinTable c
         ON a.SelfJoinTableID = c.SelfJoinTableID
WHERE  a.Status = 'Status to filter a'
       AND b.Status = 'Status to filter b'
       AND c.Status = 'Status to filter c' 

What does (function($) {})(jQuery); mean?

Actually, this example helped me to understand what does (function($) {})(jQuery); mean.

Consider this:

// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4

And now consider this:

  • jQuery is a variable holding jQuery object.
  • $ is a variable name like any other (a, $b, a$b etc.) and it doesn't have any special meaning like in PHP.

Knowing that we can take another look at our example:

var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4

Can I loop through a table variable in T-SQL?

look like this demo:

DECLARE @vTable TABLE (IdRow int not null primary key identity(1,1),ValueRow int);

-------Initialize---------
insert into @vTable select 345;
insert into @vTable select 795;
insert into @vTable select 565;
---------------------------

DECLARE @cnt int = 1;
DECLARE @max int = (SELECT MAX(IdRow) FROM @vTable);

WHILE @cnt <= @max
BEGIN
    DECLARE @tempValueRow int = (Select ValueRow FROM @vTable WHERE IdRow = @cnt);

    ---work demo----
    print '@tempValueRow:' + convert(varchar(10),@tempValueRow);
    print '@cnt:' + convert(varchar(10),@cnt);
    print'';
    --------------

    set @cnt = @cnt+1;
END

Version without idRow, using ROW_NUMBER

    DECLARE @vTable TABLE (ValueRow int);
-------Initialize---------
insert into @vTable select 345;
insert into @vTable select 795;
insert into @vTable select 565;
---------------------------

DECLARE @cnt int = 1;
DECLARE @max int = (select count(*) from @vTable);

WHILE @cnt <= @max
BEGIN
    DECLARE @tempValueRow int = (
        select ValueRow 
        from (select ValueRow
            , ROW_NUMBER() OVER(ORDER BY (select 1)) as RowId 
            from @vTable
        ) T1 
    where t1.RowId = @cnt
    );

    ---work demo----
    print '@tempValueRow:' + convert(varchar(10),@tempValueRow);
    print '@cnt:' + convert(varchar(10),@cnt);
    print'';
    --------------

    set @cnt = @cnt+1;
END

How do I write a for loop in bash

The bash for consists on a variable (the iterator) and a list of words where the iterator will, well, iterate.

So, if you have a limited list of words, just put them in the following syntax:

for w in word1 word2 word3
do
  doSomething($w)
done

Probably you want to iterate along some numbers, so you can use the seq command to generate a list of numbers for you: (from 1 to 100 for example)

seq 1 100

and use it in the FOR loop:

for n in $(seq 1 100)
do
  doSomething($n)
done

Note the $(...) syntax. It's a bash behaviour, it allows you to pass the output from one command (in our case from seq) to another (the for)

This is really useful when you have to iterate over all directories in some path, for example:

for d in $(find $somepath -type d)
do
  doSomething($d)
done

The possibilities are infinite to generate the lists.

How to rebuild docker container in docker-compose.yml?

Only:

$ docker-compose restart [yml_service_name]

How can I de-install a Perl module installed via `cpan`?

Update 2013: This code is obsolescent. Upvote bsb's late-coming answer instead.


I don't need to uninstall modules often, but the .packlist file based approach has never failed me so far.

use 5.010;
use ExtUtils::Installed qw();
use ExtUtils::Packlist qw();

die "Usage: $0 Module::Name Module::Name\n" unless @ARGV;

for my $mod (@ARGV) {
    my $inst = ExtUtils::Installed->new;

    foreach my $item (sort($inst->files($mod))) {
        say "removing $item";
        unlink $item or warn "could not remove $item: $!\n";
    }

    my $packfile = $inst->packlist($mod)->packlist_file;
    print "removing $packfile\n";
    unlink $packfile or warn "could not remove $packfile: $!\n";
}

Launch Pycharm from command line (terminal)

pycharm download & Open in UBUNTU

Download:

Open:

  1. Navigate to bin directory in the extracted folder.

  2. run : ./pycharm.sh

reStructuredText tool support

Salvaging (and extending) the list from an old version of the Wikipedia page:

Documentation

Implementations

Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

Python - Docutils

The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

  • rst2html - from reStructuredText to HTML
  • rst2xml - from reStructuredText to XML
  • rst2latex - from reStructuredText to LaTeX
  • rst2odt - from reStructuredText to ODF Text (word processor) document.
  • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
  • rst2man - from reStructuredText to Man page

Haskell - Pandoc

Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

  • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
  • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

Java - JRst

JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

Scala - Laika

Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.

Perl

PHP

C#/.NET

Nim/C

The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

  • rst - implements a reStructuredText parser
  • rstast - implements an AST for the reStructuredText parser
  • rstgen - implements a generator of HTML/Latex from reStructuredText

Other 3rd party converters

Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

From reStructuredText

  • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
    1. starts a small web server
    2. calls docutils to render your document(s) to HTML
    3. calls your device's browser to display the output HTML.
  • rst2pdf - from reStructuredText to PDF
  • rst2odp - from reStructuredText to ODF Presentation
  • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
  • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
  • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

To reStructuredText

  • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
  • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
  • db2rst is a simple and limited DocBook to reStructuredText translator
  • pod2rst - convert .pod files to reStructuredText files

Extensions

Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.

Sphinx

The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.

rest2web

rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.

Pygments

Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

Free Editors

While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.

Emacs

The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el

Vim

The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:

Jed

There is a rst mode for the Jed programmers editor.

gedit

gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.

Geany

Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).

Leo

Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

It also provides a way to preview the resulting HTML, in a "viewrendered" pane.

FTE

The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.

PyK

PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.

Eclipse

The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.

NoTex

NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.

Notepad++

Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

Visual Studio Code

Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

Dedicated reStructuredText Editors

Proprietary editors

Sublime Text

Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

BBEdit / TextWrangler

BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.

TextMate

TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.

Intype

Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

E Text Editor

E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.

PyCharm

PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)

Wiki

here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:

MediaWiki

MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.

MoinMoin

MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

There is a reStructuredText Parser for MoinMoin.

Trac

Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

This Wiki

This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.

rstiki

rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.

ikiwiki

Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

Web Services

Sandbox

An Online reStructuredText editor can be used to play with the markup and see the results immediately.

Blogging frameworks

WordPress

WordPreSt reStructuredText plugin for WordPress. (PHP)

Zine

reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)

pelican

Pelican is a static blog generator that supports writing articles in ReST. (Python)

hyde

Hyde is a static website generator that supports ReST. (Python)

Acrylamid

Acrylamid is a static blog generator that supports writing articles in ReST. (Python)

Nikola

Nikola is a Static Site and Blog Generator that supports ReST. (Python)

ipsum genera

Ipsum genera is a static blog generator written in Nim.

Yozuch

Yozuch is a static blog generator written in Python.

More

How to disable a link using only CSS?

Bootstrap Disabled Link

<a href="#" class="btn btn-primary btn-lg disabled" role="button">Primary link</a>

<a href="#" class="btn btn-default btn-lg disabled" role="button">Link</a>

Bootstrap Disabled Button but it looks like link

<button type="button" class="btn btn-link">Link</button>

How to convert string to char array in C++?

Try this way it should be work.

string line="hello world";
char * data = new char[line.size() + 1];
copy(line.begin(), line.end(), data);
data[line.size()] = '\0'; 

How is a JavaScript hash map implemented?

<html>
<head>
<script type="text/javascript">
function test(){
var map= {'m1': 12,'m2': 13,'m3': 14,'m4': 15}
     alert(map['m3']);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="test()"/>
</body>
</html>

How can I escape latex code received through user input?

When you read the string from the GUI control, it is already a "raw" string. If you print out the string you might see the backslashes doubled up, but that's an artifact of how Python displays strings; internally there's still only a single backslash.

>>> a='\nu + \lambda + \theta'
>>> a
'\nu + \\lambda + \theta'
>>> len(a)
20
>>> b=r'\nu + \lambda + \theta'
>>> b
'\\nu + \\lambda + \\theta'
>>> len(b)
22
>>> b[0]
'\\'
>>> print b
\nu + \lambda + \theta

Downloading video from YouTube

You can check out libvideo. It's much more up-to-date than YoutubeExtractor, and is fast and clean to use.

Apache: "AuthType not set!" 500 Error

The problem here can be formulated another way: how do I make a config that works both in apache 2.2 and 2.4?

Require all granted is only in 2.4, but Allow all ... stops working in 2.4, and we want to be able to rollout a config that works in both.

The only solution I found, which I am not sure is the proper one, is to use:

# backwards compatibility with apache 2.2
Order allow,deny
Allow from all

# forward compatibility with apache 2.4
Require all granted
Satisfy Any

This should resolve your problem, or at least did for me. Now the problem will probably be much harder to solve if you have more complex access rules...

See also this fairly similar question. The Debian wiki also has useful instructions for supporting both 2.2 and 2.4.

Why is access to the path denied?

The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.

I hit the same thing. Check to ensure that the file is NOT HIDDEN.

Disable spell-checking on HTML textfields

The following code snippet disables it for all textarea and input[type=text] elements:

(function () {
    function disableSpellCheck() {
        let selector = 'input[type=text], textarea';
        let textFields = document.querySelectorAll(selector);

        textFields.forEach(
            function (field, _currentIndex, _listObj) {
                field.spellcheck = false;
            }
        );
    }

    disableSpellCheck();
})();

Update Rows in SSIS OLEDB Destination

You can't do a bulk-update in SSIS within a dataflow task with the OOB components.

The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.

Stage data

http://www.sqlservercentral.com/Images/11369.png

Set based updates

enter image description here

You'll get much better performance with a pattern like this versus using the OLE DB Command transformation for anything but trivial amounts of data.

If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.

How to fix corrupted git repository?

Before trying any of the fixes described on this page, I would advise to make a copy of your repo and work on this copy only. Then at the end if you can fix it, compare it with the original to ensure you did not lose any file in the repair process.

Another alternative which worked for me was to reset the git head and index to its previous state using:

git reset --keep

You can also do the same manually by opening the Git GUI and selecting each "Staged changes" and click on "Unstage the change". When everything is unstaged, you should now be able to compress your database, check your database and commit.

I also tried the following commands but they did not work for me, but they might for you depending on the exact issue you have:

git reset --mixed
git fsck --full
git gc --auto
git prune --expire now
git reflog --all

Finally, to avoid this problem of synchronization damaging your git index (which can happen with DropBox, SpiderOak, or any other cloud disk), you can do the following:

  1. Convert your .git folder into a single "bundle" git file by using: git bundle create my_repo.git --all, then it should work just the same as before, but since everything is in a single file you won't risk the synchronization damaging your git repo anymore.
  2. Disable instantaneous synchronization: SpiderOak allows you to set the scheduling for checking changes to "automatic" (which means that it is as soon as possible, being monitoring file changes thanks to the OS notifications). This is bad because it will start to upload changes as soon as you are doing a change, and then download the change, so it might erase the latest changes you were just doing. A solution to fix this issue is to set the changes monitoring delay to 5 minutes or more. This also fixes issues with instant saving note taking applications (such as Notepad++).

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

PowerShell: Format-Table without headers

Try the -HideTableHeaders parameter to Format-Table:

gci | ft -HideTableHeaders

(I'm using PowerShell v2. I don't know if this was in v1.)

Algorithm to compare two images

Read the paper: Porikli, Fatih, Oncel Tuzel, and Peter Meer. “Covariance Tracking Using Model Update Based on Means on Riemannian Manifolds”. (2006) IEEE Computer Vision and Pattern Recognition.

I was successfully able to detect overlapping regions in images captured from adjacent webcams using the technique presented in this paper. My covariance matrix was composed of Sobel, canny and SUSAN aspect/edge detection outputs, as well as the original greyscale pixels.

Examples for string find in Python

I'm not sure what you're looking for, do you mean find()?

>>> x = "Hello World"
>>> x.find('World')
6
>>> x.find('Aloha');
-1

Session variables in ASP.NET MVC

I would think you'll want to think about if things really belong in a session state. This is something I find myself doing every now and then and it's a nice strongly typed approach to the whole thing but you should be careful when putting things in the session context. Not everything should be there just because it belongs to some user.

in global.asax hook the OnSessionStart event

void OnSessionStart(...)
{
    HttpContext.Current.Session.Add("__MySessionObject", new MySessionObject());
}

From anywhere in code where the HttpContext.Current property != null you can retrive that object. I do this with an extension method.

public static MySessionObject GetMySessionObject(this HttpContext current)
{
    return current != null ? (MySessionObject)current.Session["__MySessionObject"] : null;
}

This way you can in code

void OnLoad(...)
{
    var sessionObj = HttpContext.Current.GetMySessionObject();
    // do something with 'sessionObj'
}

Calling the base constructor in C#

You can also do a conditional check with parameters in the constructor, which allows some flexibility.

public MyClass(object myObject=null): base(myObject ?? new myOtherObject())
{
}

or

public MyClass(object myObject=null): base(myObject==null ? new myOtherObject(): myObject)
{
}

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

It doesn't appear that iframes display and scroll properly. You can use an object tag to replace an iframe and the contents will be scrollable with 2 fingers. Here's a simple example:

<html>
    <head>
        <meta name="viewport" content="minimum-scale=1.0; maximum-scale=1.0; user-scalable=false; initial-scale=1.0;"/>
    </head>
    <body>
        <div>HEADER - use 2 fingers to scroll contents:</div>
        <div id="scrollee" style="height:75%;" >
            <object id="object" height="90%" width="100%" type="text/html" data="http://en.wikipedia.org/"></object>
        </div>
        <div>FOOTER</div>
    </body>
</html>

How to display a jpg file in Python?

Don't forget to include

import Image

In order to show it use this :

Image.open('pathToFile').show()

Properly embedding Youtube video into bootstrap 3.0 page

I know it's late, I have the same issue with an old custom theme, just added to boostrap.css:

.embed-responsive {
  position: relative;
  display: block;
  height: 0;
  padding: 0;
  overflow: hidden;
}
.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object,
.embed-responsive video {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 0;
}
.embed-responsive-16by9 {
  padding-bottom: 56.25%;
}
.embed-responsive-4by3 {
  padding-bottom: 75%;
}

And for the video:

<div class="embed-responsive embed-responsive-16by9" >
<iframe class="embed-responsive-item"  src="https://www.youtube.com/embed/jVIxe3YLNs8"></iframe>
</div>

How to increase time in web.config for executing sql query

I think you can't increase the time for query execution, but you need to increase the timeout for the request.

Execution Timeout Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. (Default time is 110 seconds.)

For Details, please have a look at https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.100%29.aspx

You can do in the web.config. e.g

<httpRuntime maxRequestLength="2097152" executionTimeout="600" />

Bootstrap 3 offset on right not left

I'm using the following simple custom CSS I wrote to achieve this.

.col-xs-offset-right-12 {
  margin-right: 100%;
}
.col-xs-offset-right-11 {
  margin-right: 91.66666667%;
}
.col-xs-offset-right-10 {
  margin-right: 83.33333333%;
}
.col-xs-offset-right-9 {
  margin-right: 75%;
}
.col-xs-offset-right-8 {
  margin-right: 66.66666667%;
}
.col-xs-offset-right-7 {
  margin-right: 58.33333333%;
}
.col-xs-offset-right-6 {
  margin-right: 50%;
}
.col-xs-offset-right-5 {
  margin-right: 41.66666667%;
}
.col-xs-offset-right-4 {
  margin-right: 33.33333333%;
}
.col-xs-offset-right-3 {
  margin-right: 25%;
}
.col-xs-offset-right-2 {
  margin-right: 16.66666667%;
}
.col-xs-offset-right-1 {
  margin-right: 8.33333333%;
}
.col-xs-offset-right-0 {
  margin-right: 0;
}
@media (min-width: 768px) {
  .col-sm-offset-right-12 {
    margin-right: 100%;
  }
  .col-sm-offset-right-11 {
    margin-right: 91.66666667%;
  }
  .col-sm-offset-right-10 {
    margin-right: 83.33333333%;
  }
  .col-sm-offset-right-9 {
    margin-right: 75%;
  }
  .col-sm-offset-right-8 {
    margin-right: 66.66666667%;
  }
  .col-sm-offset-right-7 {
    margin-right: 58.33333333%;
  }
  .col-sm-offset-right-6 {
    margin-right: 50%;
  }
  .col-sm-offset-right-5 {
    margin-right: 41.66666667%;
  }
  .col-sm-offset-right-4 {
    margin-right: 33.33333333%;
  }
  .col-sm-offset-right-3 {
    margin-right: 25%;
  }
  .col-sm-offset-right-2 {
    margin-right: 16.66666667%;
  }
  .col-sm-offset-right-1 {
    margin-right: 8.33333333%;
  }
  .col-sm-offset-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 992px) {
  .col-md-offset-right-12 {
    margin-right: 100%;
  }
  .col-md-offset-right-11 {
    margin-right: 91.66666667%;
  }
  .col-md-offset-right-10 {
    margin-right: 83.33333333%;
  }
  .col-md-offset-right-9 {
    margin-right: 75%;
  }
  .col-md-offset-right-8 {
    margin-right: 66.66666667%;
  }
  .col-md-offset-right-7 {
    margin-right: 58.33333333%;
  }
  .col-md-offset-right-6 {
    margin-right: 50%;
  }
  .col-md-offset-right-5 {
    margin-right: 41.66666667%;
  }
  .col-md-offset-right-4 {
    margin-right: 33.33333333%;
  }
  .col-md-offset-right-3 {
    margin-right: 25%;
  }
  .col-md-offset-right-2 {
    margin-right: 16.66666667%;
  }
  .col-md-offset-right-1 {
    margin-right: 8.33333333%;
  }
  .col-md-offset-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 1200px) {
  .col-lg-offset-right-12 {
    margin-right: 100%;
  }
  .col-lg-offset-right-11 {
    margin-right: 91.66666667%;
  }
  .col-lg-offset-right-10 {
    margin-right: 83.33333333%;
  }
  .col-lg-offset-right-9 {
    margin-right: 75%;
  }
  .col-lg-offset-right-8 {
    margin-right: 66.66666667%;
  }
  .col-lg-offset-right-7 {
    margin-right: 58.33333333%;
  }
  .col-lg-offset-right-6 {
    margin-right: 50%;
  }
  .col-lg-offset-right-5 {
    margin-right: 41.66666667%;
  }
  .col-lg-offset-right-4 {
    margin-right: 33.33333333%;
  }
  .col-lg-offset-right-3 {
    margin-right: 25%;
  }
  .col-lg-offset-right-2 {
    margin-right: 16.66666667%;
  }
  .col-lg-offset-right-1 {
    margin-right: 8.33333333%;
  }
  .col-lg-offset-right-0 {
    margin-right: 0;
  }
}

How to use && in EL boolean expressions in Facelets?

Facelets is a XML based view technology. The & is a special character in XML representing the start of an entity like &amp; which ends with the ; character. You'd need to either escape it, which is ugly:

rendered="#{beanA.prompt == true &amp;&amp; beanB.currentBase != null}"

or to use the and keyword instead, which is preferred as to readability and maintainability:

rendered="#{beanA.prompt == true and beanB.currentBase != null}"

See also:


Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true:

rendered="#{beanA.prompt and beanB.currentBase != null}"

Detect click outside React component

None of the other answers here worked for me. I was trying to hide a popup on blur, but since the contents were absolutely positioned, the onBlur was firing even on the click of inner contents too.

Here is an approach that did work for me:

// Inside the component:
onBlur(event) {
    // currentTarget refers to this component.
    // relatedTarget refers to the element where the user clicked (or focused) which
    // triggered this event.
    // So in effect, this condition checks if the user clicked outside the component.
    if (!event.currentTarget.contains(event.relatedTarget)) {
        // do your thing.
    }
},

Hope this helps.

twitter bootstrap typeahead ajax example

when using ajax, try $.getJSON() instead of $.get() if you have trouble with the correct display of the results.

In my case i got only the first character of every result when i used $.get(), although i used json_encode() server-side.

Is it possible to apply CSS to half of a character?

Just for the record in history!

I've come up with a solution for my own work from 5-6 years ago, which is Gradext ( pure javascript and pure css, no dependency ) .

The technical explanation is you can create an element like this:

<span>A</span>

now if you want to make a gradient on text, you need to create some multiple layers, each individually specifically colored and the spectrum created will illustrate the gradient effect.

for example look at this is the word lorem inside of a <span> and will cause a horizontal gradient effect ( check the examples ):

 <span data-i="0" style="color: rgb(153, 51, 34);">L</span>
 <span data-i="1" style="color: rgb(154, 52, 35);">o</span>
 <span data-i="2" style="color: rgb(155, 53, 36);">r</span>
 <span data-i="3" style="color: rgb(156, 55, 38);">e</span>
 <span data-i="4" style="color: rgb(157, 56, 39);">m</span>

and you can continue doing this pattern for a long time and long paragraph as well.

enter image description here

But!

What if you want to create a vertical gradient effect on texts?

Then there's another solution which could be helpful. I will describe in details.

Assuming our first <span> again. but the content shouldn't be the letters individually; the content should be the whole text, and now we're going to copy the same ??<span> again and again ( count of spans will define the quality of your gradient, more span, better result, but poor performance ). have a look at this:

<span data-i="6" style="color: rgb(81, 165, 39); overflow: hidden; height: 11.2px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="7" style="color: rgb(89, 174, 48); overflow: hidden; height: 12.8px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="8" style="color: rgb(97, 183, 58); overflow: hidden; height: 14.4px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="9" style="color: rgb(105, 192, 68); overflow: hidden; height: 16px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="10" style="color: rgb(113, 201, 78); overflow: hidden; height: 17.6px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="11" style="color: rgb(121, 210, 88); overflow: hidden; height: 19.2px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>

enter image description here

Again, But!

what if you want to make these gradient effects to move and create an animation out of it?

well, there's another solution for it too. You should definitely check animation: true or even .hoverable() method which will lead to a gradient to start based on cursor position! ( sounds cool xD )

enter image description here

this is simply how we're creating gradients ( linear or radial ) on texts. If you liked the idea or want to know more about it, you should check the links provided.


Maybe this is not the best option, maybe not the best performant way to do this, but it will open up some space to create exciting and delightful animations to inspire some other people for a better solution.

It will allow you to use gradient style on texts, which is supported by even IE8!

Here you can find a working live demo and the original repository is here on GitHub as well, open source and ready to get some updates ( :D )

This is my first time ( yeah, after 5 years, you've heard it right ) to mention this repository anywhere on the Internet, and I'm excited about that!


[Update - 2019 August:] Github removed github-pages demo of that repository because I'm from Iran! Only the source code is available here tho...

Sublime Text 3 how to change the font size of the file sidebar?

Some limited flexibility is available if your using the Afterglow Theme.

https://github.com/YabataDesign/afterglow-theme

You can edit your user preferences in the following way.

Sublime Text -> Preferences -> Settings - User:

{
    "sidebar_size_14": true
}

https://github.com/YabataDesign/afterglow-theme#sidebar-size-options

How to set initial value and auto increment in MySQL?

Alternatively, If you are too lazy to write the SQL query. Then this solution is for you. enter image description here

  1. Open phpMyAdmin
  2. Select desired Table
  3. Click on Operations tab
  4. Set your desired initial Value for AUTO_INCREMENT
  5. Done..!

Laravel is there a way to add values to a request array

I tried $request->merge($array) function in Laravel 5.2 and it is working perfectly.

Example:

$request->merge(["key"=>"value"]);

How to download source in ZIP format from GitHub?

Even though this is fairly an old question, I have my 2 cents to share.

You can download the repo as tar.gz as well

Like the zipball link pointed by various answers here, There is a tarball link as well which downloads the content of the git repository in tar.gz format.

curl -L http://github.com/zoul/Finch/tarball/master/

A better way

Git also provides a different URL pattern where you can simply append the type of file you want to download at the end of url. This way is better if you want to process these urls in a batch or bash script.

curl -L http://github.com/zoul/Finch/archive/master.zip

curl -L http://github.com/zoul/Finch/archive/master.tar.gz

To download a specific commit or branch

Replace master with the commit-hash or the branch-name in the above urls like below.

curl -L http://github.com/zoul/Finch/archive/cfeb671ac55f6b1aba6ed28b9bc9b246e0e.zip    
curl -L http://github.com/zoul/Finch/archive/cfeb671ac55f6b1aba6ed28b9bc9b246e0e.tar.gz

curl -L http://github.com/zoul/Finch/archive/your-branch-name.zip
curl -L http://github.com/zoul/Finch/archive/your-branch-name.tar.gz

What is (functional) reactive programming?

The short and clear explanation about Reactive Programming appears on Cyclejs - Reactive Programming, it uses simple and visual samples.

A [module/Component/object] is reactive means it is fully responsible for managing its own state by reacting to external events.

What is the benefit of this approach? It is Inversion of Control, mainly because [module/Component/object] is responsible for itself, improving encapsulation using private methods against public ones.

It is a good startup point, not a complete source of knowlege. From there you could jump to more complex and deep papers.

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

If you are using eclipse and maven for handling dependencies, you may need to take these extra steps to make sure eclipse copies the dependencies properly Maven dependencies not visible in WEB-INF/lib (namely the Deployment Assembly for Dynamic web application)

python: changing row index of pandas data frame

followers_df.reset_index()
followers_df.reindex(index=range(0,20))

Playing m3u8 Files with HTML Video Tag

<html>
<body>
    <video width="600" height="400" controls>
        <source src="index.m3u8" type="application/x-mpegURL">
    </video>
</body> 

Stream HLS or m3u8 files using above code. it works for desktop: ms edge browser (not working with desktop chrome) and mobile: chrome,opera mini browser.

To play on all browser use flash based media player. media player to support all browser

Proxy Basic Authentication in C#: HTTP 407 error

This problem had been bugging me for years the only workaround for me was to ask our networks team to make exceptions on our firewall so that certain URL requests didn't need to be authenticated on the proxy which is not ideal.

Recently I upgraded the project to .NET 4 from 3.5 and the code just started working using the default credentials for the proxy, no hardcoding of credentials etc.

request.Proxy.Credentials = CredentialCache.DefaultCredentials;

Can typescript export a function?

If you are using this for Angular, then export a function via a named export. Such as:

function someFunc(){}

export { someFunc as someFuncName }

otherwise, Angular will complain that object is not a function.

How do I add python3 kernel to jupyter (IPython)

I successfully installed python3 kernel on macOS El Capitan (ipython version: 4.1.0) with following commands.

python3 -m pip install ipykernel
python3 -m ipykernel install --user

You can see all installed kernels with jupyter kernelspec list.

More info is available here

How to generate a range of numbers between two numbers?

I do it with recursive ctes, but i'm not sure if it is the best way

declare @initial as int = 1000;
declare @final as int =1050;

with cte_n as (
    select @initial as contador
    union all
    select contador+1 from cte_n 
    where contador <@final
) select * from cte_n option (maxrecursion 0)

saludos.

Replace Line Breaks in a String C#

I needed to replace the \r\n with an actual carriage return and line feed and replace \t with an actual tab. So I came up with the following:

public string Transform(string data)
{
    string result = data;
    char cr = (char)13;
    char lf = (char)10;
    char tab = (char)9;

    result = result.Replace("\\r", cr.ToString());
    result = result.Replace("\\n", lf.ToString());
    result = result.Replace("\\t", tab.ToString());

    return result;
}

Property 'json' does not exist on type 'Object'

For future visitors: In the new HttpClient (Angular 4.3+), the response object is JSON by default, so you don't need to do response.json().data anymore. Just use response directly.

Example (modified from the official documentation):

import { HttpClient } from '@angular/common/http';

@Component(...)
export class YourComponent implements OnInit {

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('https://api.github.com/users')
        .subscribe(response => console.log(response));
  }
}

Don't forget to import it and include the module under imports in your project's app.module.ts:

...
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module after BrowserModule.
    HttpClientModule,
    ...
  ],
  ...

getting the last item in a javascript object

Yes, there is a way using Object.keys(obj). It is explained in this page:

var fruitObject = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
Object.keys(fruitObject); // this returns all properties in an array ["a", "b", "c"]

If you want to get the value of the last object, you could do this:

fruitObject[Object.keys(fruitObject)[Object.keys(fruitObject).length - 1]] // "carrot"

Android Saving created bitmap to directory on sd card

This answer is an update with a little more consideration for OOM and various other leaks.

Assumes you have a directory intended as the destination and a name String already defined.

    File destination = new File(directory.getPath() + File.separatorChar + filename);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    source.compress(Bitmap.CompressFormat.PNG, 100, bytes);

    FileOutputStream fo = null;
    try {
        destination.createNewFile();

        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
    } catch (IOException e) {

    } finally {
        try {
            fo.close();
        } catch (IOException e) {}
    }

Why is my CSS bundling not working with a bin deployed MVC4 app?

Omitting runAllManagedModulesForAllRequests="true" also worked for me. Add the following configuration in web.config:

<modules>
  <remove name="BundleModule" />
  <add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</modules>

runAllManagedModulesForAllRequests will impose a performance hit on your website if not used appropriately. Check out this article.

How do I create an array of strings in C?

hello you can try this bellow :

 char arr[nb_of_string][max_string_length]; 
 strcpy(arr[0], "word");

a nice example of using, array of strings in c if you want it

#include <stdio.h>
#include <string.h>


int main(int argc, char *argv[]){

int i, j, k;

// to set you array
//const arr[nb_of_string][max_string_length]
char array[3][100];

char temp[100];
char word[100];

for (i = 0; i < 3; i++){
    printf("type word %d : ",i+1);
    scanf("%s", word);
    strcpy(array[i], word);
}

for (k=0; k<3-1; k++){
    for (i=0; i<3-1; i++)
    {
        for (j=0; j<strlen(array[i]); j++)
        {
            // if a letter ascii code is bigger we swap values
            if (array[i][j] > array[i+1][j])
            {
                strcpy(temp, array[i+1]);
                strcpy(array[i+1], array[i]);
                strcpy(array[i], temp);

                j = 999;
            }

            // if a letter ascii code is smaller we stop
            if (array[i][j] < array[i+1][j])
            {
                    j = 999;
            }

        }
    }
}

for (i=0; i<3; i++)
{
    printf("%s\n",array[i]);
}

return 0;
}

Close a MessageBox after several seconds

There is an undocumented API in user32.dll named MessageBoxTimeout() but it requires Windows XP or later.

Javascript: formatting a rounded number to N decimals

This works for rounding to N digits (if you just want to truncate to N digits remove the Math.round call and use the Math.trunc one):

function roundN(value, digits) {
   var tenToN = 10 ** digits;
   return /*Math.trunc*/(Math.round(value * tenToN)) / tenToN;
}

Had to resort to such logic at Java in the past when I was authoring data manipulation E-Slate components. That is since I had found out that adding 0.1 many times to 0 you'd end up with some unexpectedly long decimal part (this is due to floating point arithmetics).

A user comment at Format number to always show 2 decimal places calls this technique scaling.

Some mention there are cases that don't round as expected and at http://www.jacklmoore.com/notes/rounding-in-javascript/ this is suggested instead:

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

Get the _id of inserted document in Mongo database in NodeJS

Now you can use insertOne method and in promise's result.insertedId

Node.js/Express.js App Only Works on Port 3000

Just a note for Mac OS X and Linux users:

If you want to run your Node / Express app on a port number lower than 1024, you have to run as the superuser: sudo PORT=80 node app.js

Replace one character with another in Bash

Try this for paths:

echo \"hello world\"|sed 's/ /+/g'|sed 's/+/\/g'|sed 's/\"//g'

It replaces the space inside the double-quoted string with a + sing, then replaces the + sign with a backslash, then removes/replaces the double-quotes.

I had to use this to replace the spaces in one of my paths in Cygwin.

echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'

Hash table runtime complexity (insert, search and delete)

Perhaps you were looking at the space complexity? That is O(n). The other complexities are as expected on the hash table entry. The search complexity approaches O(1) as the number of buckets increases. If at the worst case you have only one bucket in the hash table, then the search complexity is O(n).

Edit in response to comment I don't think it is correct to say O(1) is the average case. It really is (as the wikipedia page says) O(1+n/k) where K is the hash table size. If K is large enough, then the result is effectively O(1). But suppose K is 10 and N is 100. In that case each bucket will have on average 10 entries, so the search time is definitely not O(1); it is a linear search through up to 10 entries.

How to remove unused imports in Intellij IDEA on commit?

In Mac IntelliJ IDEA, the command is Cmd + Option + O

For some older versions it is apparently Ctrl + Option + O.

(Letter O not Zero 0) on the latest version 2019.x

How to install Python packages from the tar.gz file without using pip install

Install it by running

python setup.py install

Better yet, you can download from github. Install git via apt-get install git and then follow this steps:

git clone https://github.com/mwaskom/seaborn.git
cd seaborn
python setup.py install

Delete topic in Kafka 0.8.1.1

As mentioned in doc here

Topic deletion option is disabled by default. To enable it set the server config delete.topic.enable=true Kafka does not currently support reducing the number of partitions for a topic or changing the replication factor.

Make sure delete.topic.enable=true

Simplest way to do a recursive self-join?

Check following to help the understand the concept of CTE recursion

DECLARE
@startDate DATETIME,
@endDate DATETIME

SET @startDate = '11/10/2011'
SET @endDate = '03/25/2012'

; WITH CTE AS (
    SELECT
        YEAR(@startDate) AS 'yr',
        MONTH(@startDate) AS 'mm',
        DATENAME(mm, @startDate) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        @startDate 'new_date'
    UNION ALL
    SELECT
        YEAR(new_date) AS 'yr',
        MONTH(new_date) AS 'mm',
        DATENAME(mm, new_date) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        DATEADD(d,1,new_date) 'new_date'
    FROM CTE
    WHERE new_date < @endDate
    )
SELECT yr AS 'Year', mon AS 'Month', count(dd) AS 'Days'
FROM CTE
GROUP BY mon, yr, mm
ORDER BY yr, mm
OPTION (MAXRECURSION 1000)

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

on sql 2008 this is valid

DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable

on sql server 2005, you need to do this

DECLARE @myVariable nvarchar(Max) 
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable

Default instance name of SQL Server Express

You're right, it's localhost\SQLEXPRESS (just no $) and yes, it's the same for both 2005 and 2008 express versions.

How to save a data.frame in R?

Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.

write.csv(Data_output, "output.csv", row.names = F, quote = F)

credit to Peter and Ilja, UMCG, the Netherlands

shift a std_logic_vector of n bit to right or left

This is typically done manually by choosing the appropriate bits from the vector and then appending 0s.

For example, to shift a vector 8 bits

variable tmp : std_logic_vector(15 downto 0)
...
tmp := x"00" & tmp(15 downto 8);

Hopefully this simple answer is useful to someone

@Cacheable key on multiple method arguments

After some limited testing with Spring 3.2, it seems one can use a SpEL list: {..., ..., ...}. This can also include null values. Spring passes the list as the key to the actual cache implementation. When using Ehcache, such will at some point invoke List#hashCode(), which takes all its items into account. (I am not sure if Ehcache only relies on the hash code.)

I use this for a shared cache, in which I include the method name in the key as well, which the Spring default key generator does not include. This way I can easily wipe the (single) cache, without (too much...) risking matching keys for different methods. Like:

@Cacheable(value="bookCache", 
  key="{ #root.methodName, #isbn?.id, #checkWarehouse }")
public Book findBook(ISBN isbn, boolean checkWarehouse) 
...

@Cacheable(value="bookCache", 
  key="{ #root.methodName, #asin, #checkWarehouse }")
public Book findBookByAmazonId(String asin, boolean checkWarehouse)
...

Of course, if many methods need this and you're always using all parameters for your key, then one can also define a custom key generator that includes the class and method name:

<cache:annotation-driven mode="..." key-generator="cacheKeyGenerator" />
<bean id="cacheKeyGenerator" class="net.example.cache.CacheKeyGenerator" />

...with:

public class CacheKeyGenerator 
  implements org.springframework.cache.interceptor.KeyGenerator {

    @Override
    public Object generate(final Object target, final Method method, 
      final Object... params) {

        final List<Object> key = new ArrayList<>();
        key.add(method.getDeclaringClass().getName());
        key.add(method.getName());

        for (final Object o : params) {
            key.add(o);
        }
        return key;
    }
}

How to set null to a GUID property

you can make guid variable to accept null first using ? operator then you use Guid.Empty or typecast it to null using (Guid?)null;

eg:

 Guid? id = Guid.Empty;

or

 Guid? id =  (Guid?)null;

How can I count the number of matches for a regex?

From Java 9, you can use the stream provided by Matcher.results()

long matches = matcher.results().count();