Programs & Examples On #Cfengine

CFEngine is a configuration management tool that allows you to automate system configuration and administration.

Unable to access JSON property with "-" dash

For ansible, and using hyphen, this worked for me:

    - name: free-ud-ssd-space-in-percent
      debug:
        var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]

How to parse JSON Array (Not Json Object) in Android

            URL url = new URL("your URL");
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            BufferedReader reader;
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            //setting the json string
            String finalJson = buffer.toString();

            //this is your string get the pattern from buffer.
            JSONArray jsonarray = new JSONArray(finalJson);

What does "where T : class, new()" mean?

where T : struct

The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information.

where T : class

The type argument must be a reference type, including any class, interface, delegate, or array type. (See note below.)

where T : new() The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last.

where T : [base class name]

The type argument must be or derive from the specified base class.

where T : [interface name]

The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

where T : U

The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.

Arguments to main in C

Had made just a small change to @anthony code so we can get nicely formatted output with argument numbers and values. Somehow easier to read on output when you have multiple arguments:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("The following arguments were passed to main():\n");
    printf("argnum \t value \n");
    for (int i = 0; i<argc; i++) printf("%d \t %s \n", i, argv[i]);
    printf("\n");

    return 0;
} 

And output is similar to:

The following arguments were passed to main():
0        D:\Projects\test\vcpp\bcppcomp1\Debug\bcppcomp.exe
1        -P
2        TestHostAttoshiba
3        _http._tcp
4        local
5        80
6        MyNewArgument
7        200.124.211.235
8        type=NewHost
9        test=yes
10       result=output

Regex to check with starts with http://, https:// or ftp://

Unless there is some compelling reason to use a regex, I would just use String.startsWith:

bool matches = test.startsWith("http://")
            || test.startsWith("https://") 
            || test.startsWith("ftp://");

I wouldn't be surprised if this is faster, too.

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

Ajax Upload image

Image upload using ajax and check image format and upload max size   

<form class='form-horizontal' method="POST"  id='document_form' enctype="multipart/form-data">
                                    <div class='optionBox1'>
                                        <div class='row inviteInputWrap1 block1'>
                                            <div class='col-3'>
                                                <label class='col-form-label'>Name</label>
                                                <input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <label class='col-form-label'>File</label>
                                                <input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <span class='deleteInviteWrap1 remove1 d-none'>
                                                    <i class='fas fa-trash'></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class='row'>
                                             <div class='col-8 pl-3 pb-4 mt-4'>
                                                <span class='btn btn-info add1 pr-3'>+ Add More</span>
                                                 <button class='btn btn-primary'>Submit</button> 
                                            </div>
                                        </div>
                                    </div>
                                    </form>     
                                    
                                    </div>  
                      
    
      $.validator.setDefaults({
       submitHandler: function (form) 
         {
               $.ajax({
                    url : "action1.php",
                    type : "POST",
                    data : new FormData(form),
                    mimeType: "multipart/form-data",
                    contentType: false,
                    cache: false,
                    dataType:'json',
                    processData: false,
                    success: function(data)
                    {
                        if(data.status =='success')
                            {
                                 swal("Document has been successfully uploaded!", {
                                    icon: "success",
                                 });
                                 setTimeout(function(){
                                    window.location.reload(); 
                                },1200);
                            }
                            else
                            {
                                swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
                            }   
                    },
                    error:function(data)
                    {
                        swal ( "Ops!" ,  "error in document upload." ,  "error" );
                    }
                });
            }
      });
    
      $('#document_form').validate({
        rules: {
            "name[]": {
              required: true
          },
          "file[]": {
              required: true,
              extension: "jpg,jpeg,png,pdf,doc",
              filesize :2000000 
          }
        },
        messages: {
            "name[]": {
            required: "Please enter name"
          },
          "file[]": {
            required: "Please enter file",
            extension :'Please upload only jpg,jpeg,png,pdf,doc'
          }
        },
        errorElement: 'span',
        errorPlacement: function (error, element) {
          error.addClass('invalid-feedback');
          element.closest('.col-3').append(error);
        },
        highlight: function (element, errorClass, validClass) {
          $(element).addClass('is-invalid');
        },
        unhighlight: function (element, errorClass, validClass) {
          $(element).removeClass('is-invalid');
        }
      });
    
      $.validator.addMethod('filesize', function(value, element, param) {
         return this.optional(element) || (element.files[0].size <= param)
        }, 'File size must be less than 2 MB');

How to place div in top right hand corner of page

You can use css float

<div style='float: left;'><a href="login.php">Log in</a></div>

<div style='float: right;'><a href="home.php">Back to Home</a></div>

Have a look at this CSS Positioning

Split a string by a delimiter in python

You may be interested in the csv module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.

import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]

for row in csv.reader( lines ):
    ...

Reverse Contents in Array

#include "stdafx.h"
#include <iostream>
using namespace std;

void main()
{
    int n, i;
    cout << "n = ";
    cin >> n;
    int *a = new int[n];
    int *b = new int[n];
    for (i = 0; i < n; i++)
    {
        cout << "a[" << i << "]= ";
        cin >> a[i];
    }
    for (i = 0; i < n; i++)
    {
        b[i] = a[n - 1 - i];
    }
    for (i = 0; i < n; i++)
    {
        cout << b[i];
    }
}

Integer expression expected error in shell script

Try this:

If [ $a -lt 4 ] || [ $a -gt 64 ] ; then \n
     Something something \n
elif [ $a -gt 4 ] || [ $a -lt 64 ] ; then \n
     Something something \n
else \n
    Yes it works for me :) \n

Laravel Eloquent - distinct() and count() not working properly together

This was working for me so Try This: $ad->getcodes()->distinct('pid')->count()

jQuery returning "parsererror" for ajax request

There are lots of suggestions to remove

dataType: "json"

While I grant that this works it's ignoring the underlying issue. If you're confident the return string really is JSON then look for errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:

Connection: Keep-Alive
Content-Type: application/json; charset=utf-8

{"type":"scan","data":{"image":".\/output\/ou...

In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping

dataType: json

span with onclick event inside a tag

<a href="http://the.url.com/page.html">
    <span onclick="hide(); return false">Hide me</span>
</a>

This is the easiest solution.

Sending intent to BroadcastReceiver from adb

I had the same problem and found out that you have to escape spaces in the extra:

adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test\ from\ adb"

So instead of "test from adb" it should be "test\ from\ adb"

Download image with JavaScript

As @Ian explained, the problem is that jQuery's click() is not the same as the native one.

Therefore, consider using vanilla-js instead of jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

Demo

How do I make Git use the editor of my choice for commits?

In Windows 7, setting editor to Notepad++

  • Open any text editor.
  • Open this file: C:\Users\YOUR_USERNAME\.gitconfig
  • Add this section to the bottom:

For 64 bit Notepad++ use:

[core]
    editor = 'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar

For 32 bit Notepad++ use:

[core]
    editor = 'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar
  • Save and close the file.
  • When you're committing with git, just write git commit and press Enter. It will pop open Notepad++.
  • Write your commit message at the top of the file, and save and close the file. Done!

How to use KeyListener

Here is an SSCCE,

package experiment;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class KeyListenerTester extends JFrame implements KeyListener {

    JLabel label;

    public KeyListenerTester(String s) {
        super(s);
        JPanel p = new JPanel();
        label = new JLabel("Key Listener!");
        p.add(label);
        add(p);
        addKeyListener(this);
        setSize(200, 100);
        setVisible(true);

    }

    @Override
    public void keyTyped(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key typed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key typed");
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key pressed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key pressed");
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key Released");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key Released");
        }
    }

    public static void main(String[] args) {
        new KeyListenerTester("Key Listener Tester");
    }
}

Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings

C++ template constructor

There is no way to explicitly specify the template arguments when calling a constructor template, so they have to be deduced through argument deduction. This is because if you say:

Foo<int> f = Foo<int>();

The <int> is the template argument list for the type Foo, not for its constructor. There's nowhere for the constructor template's argument list to go.

Even with your workaround you still have to pass an argument in order to call that constructor template. It's not at all clear what you are trying to achieve.

SQL Server - SELECT FROM stored procedure

It sounds like you might just need to use a view. A view allows a query to be represented as a table so it, the view, can be queried.

Number of lines in a file in Java

I have implemented another solution to the problem, I found it more efficient in counting rows:

try
(
   FileReader       input = new FileReader("input.txt");
   LineNumberReader count = new LineNumberReader(input);
)
{
   while (count.skip(Long.MAX_VALUE) > 0)
   {
      // Loop just in case the file is > Long.MAX_VALUE or skip() decides to not read the entire file
   }

   result = count.getLineNumber() + 1;                                    // +1 because line index starts at 0
}

Difference between .dll and .exe?

I don't know why everybody is answering this question in context of .NET. The question was a general one and didn't mention .NET anywhere.

Well, the major differences are:

EXE

  1. An exe always runs in its own address space i.e., It is a separate process.
  2. The purpose of an EXE is to launch a separate application of its own.

DLL

  1. A dll always needs a host exe to run. i.e., it can never run in its own address space.
  2. The purpose of a DLL is to have a collection of methods/classes which can be re-used from some other application.
  3. DLL is Microsoft's implementation of a shared library.

The file format of DLL and exe is essentially the same. Windows recognizes the difference between DLL and EXE through PE Header in the file. For details of PE Header, You can have a look at this Article on MSDN

Running CMD command in PowerShell

You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.

If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock option.

Spring Boot Java Config Set Session Timeout

  • Spring Boot version 1.0: server.session.timeout=1200
  • Spring Boot version 2.0: server.servlet.session.timeout=10m
    NOTE: If a duration suffix is not specified, seconds will be used.

Python requests - print entire http request (raw)?

test_print.py content:

import logging
import pytest
import requests
from requests_toolbelt.utils import dump


def print_raw_http(response):
    data = dump.dump_all(response, request_prefix=b'', response_prefix=b'')
    return '\n' * 2 + data.decode('utf-8')

@pytest.fixture
def logger():
    log = logging.getLogger()
    log.addHandler(logging.StreamHandler())
    log.setLevel(logging.DEBUG)
    return log

def test_print_response(logger):
    session = requests.Session()
    response = session.get('http://127.0.0.1:5000/')
    assert response.status_code == 300, logger.warning(print_raw_http(response))

hello.py content:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

Run:

 $ python -m flask hello.py
 $ python -m pytest test_print.py

Stdout:

------------------------------ Captured log call ------------------------------
DEBUG    urllib3.connectionpool:connectionpool.py:225 Starting new HTTP connection (1): 127.0.0.1:5000
DEBUG    urllib3.connectionpool:connectionpool.py:437 http://127.0.0.1:5000 "GET / HTTP/1.1" 200 13
WARNING  root:test_print_raw_response.py:25 

GET / HTTP/1.1
Host: 127.0.0.1:5000
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive


HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 13
Server: Werkzeug/1.0.1 Python/3.6.8
Date: Thu, 24 Sep 2020 21:00:54 GMT

Hello, World!

dropping infinite values from dataframes in pandas?

Here is another method using .loc to replace inf with nan on a Series:

s.loc[(~np.isfinite(s)) & s.notnull()] = np.nan

So, in response to the original question:

df = pd.DataFrame(np.ones((3, 3)), columns=list('ABC'))

for i in range(3): 
    df.iat[i, i] = np.inf

df
          A         B         C
0       inf  1.000000  1.000000
1  1.000000       inf  1.000000
2  1.000000  1.000000       inf

df.sum()
A    inf
B    inf
C    inf
dtype: float64

df.apply(lambda s: s[np.isfinite(s)].dropna()).sum()
A    2
B    2
C    2
dtype: float64

Can I set max_retries for requests.request?

It is the underlying urllib3 library that does the retrying. To set a different maximum retry count, use alternative transport adapters:

from requests.adapters import HTTPAdapter

s = requests.Session()
s.mount('http://stackoverflow.com', HTTPAdapter(max_retries=5))

The max_retries argument takes an integer or a Retry() object; the latter gives you fine-grained control over what kinds of failures are retried (an integer value is turned into a Retry() instance which only handles connection failures; errors after a connection is made are by default not handled as these could lead to side-effects).


Old answer, predating the release of requests 1.2.1:

The requests library doesn't really make this configurable, nor does it intend to (see this pull request). Currently (requests 1.1), the retries count is set to 0. If you really want to set it to a higher value, you'll have to set this globally:

import requests

requests.adapters.DEFAULT_RETRIES = 5

This constant is not documented; use it at your own peril as future releases could change how this is handled.

Update: and this did change; in version 1.2.1 the option to set the max_retries parameter on the HTTPAdapter() class was added, so that now you have to use alternative transport adapters, see above. The monkey-patch approach no longer works, unless you also patch the HTTPAdapter.__init__() defaults (very much not recommended).

Two Decimal places using c#

The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use

yournumber.ToString("0.00");

How do I disable text selection with CSS or JavaScript?

You can use JavaScript to do what you want:


if (document.addEventListener !== undefined) {
  // Not IE
  document.addEventListener('click', checkSelection, false);
} else {
  // IE
  document.attachEvent('onclick', checkSelection);
}

function checkSelection() {
    var sel = {};
    if (window.getSelection) {
        // Mozilla
        sel = window.getSelection();
    } else if (document.selection) {
        // IE
        sel = document.selection.createRange();
    }

    // Mozilla
    if (sel.rangeCount) {
        sel.removeAllRanges();
        return;
    }

    // IE
    if (sel.text > '') {
        document.selection.empty();
        return;
    }
}

Soap box: You really shouldn't be screwing with the client's user agent in this manner. If the client wants to select things on the document, then they should be able to select things on the document. It doesn't matter if you don't like the highlight color, because you aren't the one viewing the document.

Twitter bootstrap scrollable table

Figured I would post on here since I could not get any of the above to work with Bootstrap 4. I found this online and worked perfectly for me...

table
{
    width: 100%;
    display: block;
    border:solid black 1px;
}

thead
{
    display: inline-block;
    width: 100%;
    height: 20px;
}

tbody
{
    height: 200px;
    display: inline-block;
    width: 100%;
    overflow: auto;
}

th, td
{
    width: 100px;
    border:solid 1px black;
    text-align:center;
}

I have also attached the working jsfindle.

https://jsfiddle.net/jgngg28t/

Hope it helps someone else.

using if else with eval in aspx page

 <%if (System.Configuration.ConfigurationManager.AppSettings["OperationalMode"] != "live") {%>
                        &nbsp;[<%=System.Environment.MachineName%>]
                        <%}%>

Path of assets in CSS files in Symfony 2

I offen manage css/js plugin with composer which install it under vendor. I symlink those to the web/bundles directory, that's let composer update bundles as needed.

exemple:

1 - symlink once at all (use command fromweb/bundles/

ln -sf vendor/select2/select2/dist/ select2

2 - use asset where needed, in twig template :

{{ asset('bundles/select2/css/fileinput.css) }}

Regards.

PHP: Split string into array, like explode with no delimiter

$array = str_split("$string");

will actuall work pretty fine, BUT if you want to preserve the special characters in that string, and you want to do some manipulation with them, THAN I would use

do {
    $array[] = mb_substr( $string, 0, 1, 'utf-8' );
} while ( $string = mb_substr( $string, 1, mb_strlen( $string ), 'utf-8' ) );

because for some of mine personal uses, it has been shown to be more reliable when there is an issue with special characters

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How to test if a string is JSON or not?

There are probably tests you can do, for instance if you know that the JSON returned is always going to be surrounded by { and } then you could test for those characters, or some other hacky method. Or you could use the json.org JS library to try and parse it and test if it succeeds.

I would however suggest a different approach. Your PHP script currently returns JSON if the call is successful, but something else if it is not. Why not always return JSON?

E.g.

Successful call:

{ "status": "success", "data": [ <your data here> ] }

Erroneous call:

{ "status": "error", "error": "Database not found" }

This would make writing your client side JS much easier - all you have to do is check the "status" member and the act accordingly.

How to run Nginx within a Docker container without halting?

To add Tomer and Charles answers,

Syntax to run nginx in forground in Docker container using Entrypoint:

ENTRYPOINT nginx -g 'daemon off;' 

Not directly related but to run multiple commands with Entrypoint:

ENTRYPOINT /bin/bash -x /myscripts/myscript.sh && nginx -g 'daemon off;' 

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

If datasource is defined in application.resources, make sure it is locate right under src/main and add it to the build path.

How to check the function's return value if true or false

Wrong syntax. You can't compare a Boolean to a string like "false" or "true". In your case, just test it's inverse:

if(!ValidateForm()) { ...

You could test against the constant false, but it's rather ugly and generally frowned upon:

if(ValidateForm() == false) { ...

Hibernate: flush() and commit()

flush() will synchronize your database with the current state of object/objects held in the memory but it does not commit the transaction. So, if you get any exception after flush() is called, then the transaction will be rolled back. You can synchronize your database with small chunks of data using flush() instead of committing a large data at once using commit() and face the risk of getting an OutOfMemoryException.

commit() will make data stored in the database permanent. There is no way you can rollback your transaction once the commit() succeeds.

Close popup window

For such a seemingly simple thing this can be a royal pain in the butt! I found a solution that works beautifully (class="video-close" is obviously particular to this button and optional)

 <a href="javascript:window.open('','_self').close();" class="video-close">Close this window</a>

How to set the JSTL variable value in javascript?

one more approach to use.

first, define the following somewhere on the page:

<div id="valueHolderId">${someValue}</div>

then in JS, just do something similar to

var someValue = $('#valueHolderId').html();

it works great for the cases when all scripts are inside .js files and obviously there is no jstl available

Use LIKE %..% with field values in MySQL

  SELECT t1.a, t2.b
  FROM t1
  JOIN t2 ON t1.a LIKE '%'+t2.b +'%'

because the last answer not work

how to use math.pi in java

Replace

volume = (4 / 3) Math.PI * Math.pow(radius, 3);

With:

volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;

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

.ui-datepicker {-ms-transform: translate(100px,100px); -webkit-transform: translate(100px,100px); transform: translate(100px,100px);}

How to import a Python class that is in a directory above?

Here's a three-step, somewhat minimalist version of ThorSummoner's answer for the sake of clarity. It doesn't quite do what I want (I'll explain at the bottom), but it works okay.

Step 1: Make directory and setup.py

filepath_to/project_name/
    setup.py

In setup.py, write:

import setuptools

setuptools.setup(name='project_name')

Step 2: Install this directory as a package

Run this code in console:

python -m pip install --editable filepath_to/project_name

Instead of python, you may need to use python3 or something, depending on how your python is installed. Also, you can use -e instead of --editable.

Now, your directory will look more or less like this. I don't know what the egg stuff is.

filepath_to/project_name/
    setup.py
    test_3.egg-info/
        dependency_links.txt
        PKG-INFO
        SOURCES.txt
        top_level.txt

This folder is considered a python package and you can import from files in this parent directory even if you're writing a script anywhere else on your computer.

Step 3. Import from above

Let's say you make two files, one in your project's main directory and another in a sub directory. It'll look like this:

filepath_to/project_name/
    top_level_file.py
    subdirectory/
        subfile.py

    setup.py          |
    test_3.egg-info/  |----- Ignore these guys
        ...           |

Now, if top_level_file.py looks like this:

x = 1

Then I can import it from subfile.py, or really any other file anywhere else on your computer.

# subfile.py  OR  some_other_python_file_somewhere_else.py

import random # This is a standard package that can be imported anywhere.
import top_level_file # Now, top_level_file.py works similarly.

print(top_level_file.x)

This is different than what I was looking for: I hoped python had a one-line way to import from a file above. Instead, I have to treat the script like a module, do a bunch of boilerplate, and install it globally for the entire python installation to have access to it. It's overkill. If anyone has a simpler method than doesn't involve the above process or importlib shenanigans, please let me know.

PyTorch: How to get the shape of a Tensor as a list of int

If you're a fan of NumPyish syntax, then there's tensor.shape.

In [3]: ar = torch.rand(3, 3)

In [4]: ar.shape
Out[4]: torch.Size([3, 3])

# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]

# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]

# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]

P.S.: Note that tensor.shape is an alias to tensor.size(), though tensor.shape is an attribute of the tensor in question whereas tensor.size() is a function.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

To load data via a GET request you don't need any URLRequest (and no semicolons)

let listUrlString =  "http://bla.com?batchSize=" + String(batchSize) + "&fromIndex=" + String(fromIndex)
let myUrl = URL(string: listUrlString)!
let task = URLSession.shared.dataTask(with: myUrl) { ...

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

How to wait for a number of threads to complete?

instead of join(), which is an old API, you can use CountDownLatch. I have modified your code as below to fulfil your requirement.

import java.util.concurrent.*;
class DoSomethingInAThread implements Runnable{
    CountDownLatch latch;
    public DoSomethingInAThread(CountDownLatch latch){
        this.latch = latch;
    } 
    public void run() {
        try{
            System.out.println("Do some thing");
            latch.countDown();
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

public class CountDownLatchDemo {
    public static void main(String[] args) {
        try{
            CountDownLatch latch = new CountDownLatch(1000);
            for (int n=0; n<1000; n++) {
                Thread t = new Thread(new DoSomethingInAThread(latch));
                t.start();
            }
            latch.await();
            System.out.println("In Main thread after completion of 1000 threads");
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

Explanation:

  1. CountDownLatch has been initialized with given count 1000 as per your requirement.

  2. Each worker thread DoSomethingInAThread will decrement the CountDownLatch, which has been passed in constructor.

  3. Main thread CountDownLatchDemo await() till the count has become zero. Once the count has become zero, you will get below line in output.

    In Main thread after completion of 1000 threads
    

More info from oracle documentation page

public void await()
           throws InterruptedException

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.

Refer to related SE question for other options:

wait until all threads finish their work in java

What are some uses of template template parameters?

I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:

template <template<class> class H, class S>
void f(const H<S> &value) {
}

Here, H is a template, but I wanted this function to deal with all specializations of H.

NOTE: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!).

I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that std::vector doesn't have a typedef value_type.

So how would you write a function which can create variables of the right type for the vectors elements? This would work.

template <template<class, class> class V, class T, class A>
void f(V<T, A> &v) {
    // This can be "typename V<T, A>::value_type",
    // but we are pretending we don't have it

    T temp = v.back();
    v.pop_back();
    // Do some work on temp

    std::cout << temp << std::endl;
}

NOTE: std::vector has two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly.

which you can use like this:

f<std::vector, int>(v); // v is of type std::vector<int> using any allocator

or better yet, we can just use:

f(v); // everything is deduced, f can deal with a vector of any type!

UPDATE: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing auto. Now the same function can be written as:

template <class Cont>
void f(Cont &v) {

    auto temp = v.back();
    v.pop_back();
    // Do some work on temp

    std::cout << temp << std::endl;
}

which is how I'd prefer to write this type of code.

How to vertically center <div> inside the parent element with CSS?

You can vertically align a div in another div. See this example on JSFiddle or consider the example below.

HTML

<div class="outerDiv">
    <div class="innerDiv"> My Vertical Div </div>
</div>

CSS

.outerDiv {
    display: inline-flex;  // <-- This is responsible for vertical alignment
    height: 400px;
    background-color: red;
    color: white;
}

.innerDiv {
    margin: auto 5px;   // <-- This is responsible for vertical alignment
    background-color: green;   
}

The .innerDiv's margin must be in this format: margin: auto *px;

[Where, * is your desired value.]

display: inline-flex is supported in the latest (updated/current version) browsers with HTML5 support.

It may not work in Internet Explorer :P :)

Always try to define a height for any vertically aligned div (i.e. innerDiv) to counter compatibility issues.

How to select id with max date group by category in PostgreSQL?

Try this one:

SELECT t1.* FROM Table1 t1
JOIN 
(
   SELECT category, MAX(date) AS MAXDATE
   FROM Table1
   GROUP BY category
) t2
ON T1.category = t2.category
AND t1.date = t2.MAXDATE

See this SQLFiddle

Getting the parent of a directory in Bash

If /home/smith/Desktop/Test/../ is what you want:

dirname 'path/to/child/dir'

as seen here.

Can I get "&&" or "-and" to work in PowerShell?

I tried this sequence of commands in PowerShell:

First Test

PS C:\> $MyVar = "C:\MyTxt.txt"
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
True

($MyVar -ne $null) returned true and (Get-Content $MyVar) also returned true.

Second Test

PS C:\> $MyVar = $null
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
False

($MyVar -ne $null) returned false and so far I must assume the (Get-Content $MyVar) also returned false.

The third test proved the second condition was not even analyzed.

PS C:\> ($MyVar -ne $null) -and (Get-Content "C:\MyTxt.txt")
False

($MyVar -ne $null) returned false and proved the second condition (Get-Content "C:\MyTxt.txt") never ran, by returning false on the whole command.

Programmatic equivalent of default(Type)

You can use PropertyInfo.SetValue(obj, null). If called on a value type it will give you the default. This behavior is documented in .NET 4.0 and in .NET 4.5.

A valid provisioning profile for this executable was not found for debug mode

Bringing an app up from Xcode 3 to 4.3 I found the Bundle name and Bundle identifier had to be set to match the AppId. If all else fails, give that a whirl.

Why can I not switch branches?

I got this message when updating new files from remote and index got out of whack. Tried to fix the index, but resolving via Xcode 4.5, GitHub.app (103), and GitX.app (0.7.1) failed. So, I did this:

git commit -a -m "your commit message here"

which worked in bypassing the git index.

Two blog posts that helped me understand about Git and Xcode are:

  • Ray Wenderlich on Xcode 4.5 and
  • Oliver Steele from 2008

  • How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

    I recently found this library that converts an Excel workbook file into a DataSet: Excel Data Reader

    IDENTITY_INSERT is set to OFF - How to turn it ON?

    Reminder

    SQL Server only allows one table to have IDENTITY_INSERT property set to ON.

    This does not work:

    SET IDENTITY_INSERT TableA ON
    SET IDENTITY_INSERT TableB ON
    ... INSERT ON TableA ...
    ... INSERT ON TableB ...
    SET IDENTITY_INSERT TableA OFF
    SET IDENTITY_INSERT TableB OFF
    

    Instead:

    SET IDENTITY_INSERT TableA ON
    ... INSERT ON TableA ...
    SET IDENTITY_INSERT TableA OFF
    SET IDENTITY_INSERT TableB ON
    ... INSERT ON TableB ...
    SET IDENTITY_INSERT TableB OFF
    

    VC++ fatal error LNK1168: cannot open filename.exe for writing

    The problem is probably that you forgot to close the program and that you instead have the program running in the background.

    Find the console window where the exe file program is running, and close it by clicking the X in the upper right corner. Then try to recompile the program. In my case this solved the problem.

    I know this posting is old, but I am answering for the other people like me who find this through the search engines.

    Auto reloading python Flask app upon code changes

    A few updates for Flask 1.0 and above

    the basic approach to hot re-loading is:

    $ export FLASK_APP=my_application
    $ export FLASK_ENV=development
    $ flask run
    
    • you should use FLASK_ENV=development (not FLASK_DEBUG=1)
    • as a safety check, you can run flask run --debugger just to make sure it's turned on
    • the Flask CLI will now automatically read things like FLASK_APP and FLASK_ENV if you have an .env file in the project root and have python-dotenv installed

    How to upgrade Git on Windows to the latest version?

    If someone checking in 2021, this works fine;

    git update-git-for-windows
    

    This will download the latest version of git. After that a window will open which asks for installing new version of git. Install that and you are done. To check the version of the git on your computer;

    git --version
    

    Most efficient way to check if a file is empty in Java on Windows

    Check if the first line of file is empty:

    BufferedReader br = new BufferedReader(new FileReader("path_to_some_file"));     
    if (br.readLine() == null) {
        System.out.println("No errors, and file empty");
    }
    

    Trigger change event <select> using jquery

    $('#edit_user_details').find('select').trigger('change');
    

    It would change the select html tag drop-down item with id="edit_user_details".

    Mockito test a void method throws an exception

    If you ever wondered how to do it using the new BDD style of Mockito:

    willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));
    

    And for future reference one may need to throw exception and then do nothing:

    willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));
    

    How do you get the contextPath from JavaScript, the right way?

    Based on the discussion in the comments (particularly from BalusC), it's probably not worth doing anything more complicated than this:

    <script>var ctx = "${pageContext.request.contextPath}"</script>
    

    How to loop through a directory recursively to delete files with certain extensions

    The following will loop through the given directory recursively and list all the contents :

    for d in /home/ubuntu/*; do echo "listing contents of dir: $d"; ls -l $d/; done

    Referencing system.management.automation.dll in Visual Studio

    A copy of System.Management.Automation.dll is installed when you install the windows SDK (a suitable, recent version of it, anyway). It should be in C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\

    VB.NET: Clear DataGridView

    You can also try this code if you want to clear all data in your DataGridView

    DataGridView1.DataSource.Clear()
    

    What are good message queue options for nodejs?

    Look at node-queue-lib. Perhaps it is enough that you. It support node.js and browsers. Has two delivery strategies: broadcast and round-robin. Only javascript.

    Quick example:

    var Queue = require('node-queue-lib/queue.core');
    
    var queue = new Queue('Queue name', 'broadcast');
    
    // subscribe on 'Queue name' messages
    queue.subscribe(function (err, subscriber) {
        subscriber.on('error', function(err){
            //
        });
        subscriber.on('data', function (data, accept) {
            console.log(data);
            accept(); // accept process message
        });
    });
    
    // publish message
    queue.publish('test');
    

    Create a string and append text to it

    Use the string concatenation operator:

    Dim str As String = New String("") & "some other string"
    

    Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.

    This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.

    See "How to: Concatenate Multiple Strings" for more information on both methods.

    Can Selenium WebDriver open browser windows silently in the background?

    It may be in options. Here is the identical Java code.

            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.setHeadless(true);
            WebDriver driver = new ChromeDriver(chromeOptions);
    

    How to override trait function and call it from the overridden function?

    Another variation: Define two functions in the trait, a protected one that performs the actual task, and a public one which in turn calls the protected one.

    This just saves classes from having to mess with the 'use' statement if they want to override the function, since they can still call the protected function internally.

    trait A {
        protected function traitcalc($v) {
            return $v+1;
        }
    
        function calc($v) {
            return $this->traitcalc($v);
        }
    }
    
    class MyClass {
        use A;
    
        function calc($v) {
            $v++;
            return $this->traitcalc($v);
        }
    }
    
    class MyOtherClass {
        use A;
    }
    
    
    print (new MyClass())->calc(2); // will print 4
    
    print (new MyOtherClass())->calc(2); // will print 3
    

    How do you change library location in R?

    This post is just to mention an additional option. In case you need to set custom R libs in your Linux shell script you may easily do so by

    export R_LIBS="~/R/lib"
    

    See R admin guide on complete list of options.

    Setting a checkbox as checked with Vue.js

    To set the value of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over modules and each module has a checked property.

    The following code will bind the checkbox with that property:

    <input type="checkbox" v-model="module.checked" v-bind:id="module.id">
    

    Notice that I removed v-bind:value="module.id". You shouldn't use v-model and v-bind:value on the same element. From the vue docs:

    <input v-model="something">
    

    is just syntactic sugar for:

    <input v-bind:value="something" v-on:input="something = $event.target.value">
    

    So, by using v-model and v-bind:value, you actually end up having v-bind:value twice, which could lead to undefined behavior.

    How to access the SMS storage on Android?

    You are going to need to call the SmsManager class. You are probably going to need to use the STATUS_ON_ICC_READ constant and maybe put what you get there into your apps local db so that you can keep track of what you have already read vs the new stuff for your app to parse through. BUT bear in mind that you have to declare the use of the class in your manifest, so users will see that you have access to their SMS called out in the permissions dialogue they get when they install. Seeing SMS access is unusual and could put some users off. Good luck.

    Here is the link that goes into depth on the Sms Manager

    How can I check whether an array is null / empty?

    Method to check array for null or empty also is present on org.apache.commons.lang:

    import org.apache.commons.lang.ArrayUtils;
    
    ArrayUtils.isEmpty(array);
    

    How to amend a commit without changing commit message (reusing the previous one)?

    git commit -C HEAD --amend will do what you want. The -C option takes the metadata from another commit.

    How can I get table names from an MS Access Database?

    Best not to mess with msysObjects (IMHO).

    CurrentDB.TableDefs
    CurrentDB.QueryDefs
    CurrentProject.AllForms
    CurrentProject.AllReports
    CurrentProject.AllMacros
    

    CSV parsing in Java - working example..?

    I would recommend that you start by pulling your task apart into it's component parts.

    1. Read string data from a CSV
    2. Convert string data to appropriate format

    Once you do that, it should be fairly trivial to use one of the libraries you link to (which most certainly will handle task #1). Then iterate through the returned values, and cast/convert each String value to the value you want.

    If the question is how to convert strings to different objects, it's going to depend on what format you are starting with, and what format you want to wind up with.

    DateFormat.parse(), for example, will parse dates from strings. See SimpleDateFormat for quickly constructing a DateFormat for a certain string representation. Integer.parseInt() will prase integers from strings.

    Currency, you'll have to decide how you want to capture it. If you want to just capture as a float, then Float.parseFloat() will do the trick (just use String.replace() to remove all $ and commas before you parse it). Or you can parse into a BigDecimal (so you don't have rounding problems). There may be a better class for currency handling (I don't do much of that, so am not familiar with that area of the JDK).

    Difference between Dictionary and Hashtable

    Simply, Dictionary<TKey,TValue> is a generic type, allowing:

    • static typing (and compile-time verification)
    • use without boxing

    If you are .NET 2.0 or above, you should prefer Dictionary<TKey,TValue> (and the other generic collections)

    A subtle but important difference is that Hashtable supports multiple reader threads with a single writer thread, while Dictionary offers no thread safety. If you need thread safety with a generic dictionary, you must implement your own synchronization or (in .NET 4.0) use ConcurrentDictionary<TKey, TValue>.

    How to use [DllImport("")] in C#?

    You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

    using System.Runtime.InteropServices;
    
    
    public class WindowHandling
    {
        [DllImport("User32.dll")]
        public static extern int SetForegroundWindow(IntPtr point);
    
        public void ActivateTargetApplication(string processName, List<string> barcodesList)
        {
            Process p = Process.Start("notepad++.exe");
            p.WaitForInputIdle();
            IntPtr h = p.MainWindowHandle;
            SetForegroundWindow(h);
            SendKeys.SendWait("k");
            IntPtr processFoundWindow = p.MainWindowHandle;
        }
    }
    

    Python: Tuples/dictionaries as keys, select, sort

    A dictionary probably isn't what you should be using in this case. A more full featured library would be a better alternative. Probably a real database. The easiest would be sqlite. You can keep the whole thing in memory by passing in the string ':memory:' instead of a filename.

    If you do want to continue down this path, you can do it with the extra attributes in the key or the value. However a dictionary can't be the key to a another dictionary, but a tuple can. The docs explain what's allowable. It must be an immutable object, which includes strings, numbers and tuples that contain only strings and numbers (and more tuples containing only those types recursively...).

    You could do your first example with d = {('apple', 'red') : 4}, but it'll be very hard to query for what you want. You'd need to do something like this:

    #find all apples
    apples = [d[key] for key in d.keys() if key[0] == 'apple']
    
    #find all red items
    red = [d[key] for key in d.keys() if key[1] == 'red']
    
    #the red apple
    redapples = d[('apple', 'red')]
    

    How to remove CocoaPods from a project?

    I was able to remove my pods in the project using the CocoaPods app (Version 1.5.2). Afterwards I only deleted the podfile, podfile.lock and xcworkspace files in the folder.

    MongoDB: Server has startup warnings ''Access control is not enabled for the database''

    Mongodb v3.4

    You need to do the following to create a secure database:

    Make sure the user starting the process has permissions and that the directories exist (/data/db in this case).

    1) Start MongoDB without access control.

    mongod --port 27017 --dbpath /data/db
    

    2) Connect to the instance.

    mongo --port 27017
    

    3) Create the user administrator (in the admin authentication database).

    use admin
    db.createUser(
      {
        user: "myUserAdmin",
        pwd: "abc123",
        roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
      }
    )
    

    4) Re-start the MongoDB instance with access control.

    mongod --auth --port 27017 --dbpath /data/db
    

    5) Connect and authenticate as the user administrator.

    mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
    

    6) Create additional users as needed for your deployment (e.g. in the test authentication database).

    use test
    db.createUser(
      {
        user: "myTester",
        pwd: "xyz123",
        roles: [ { role: "readWrite", db: "test" },
                 { role: "read", db: "reporting" } ]
      }
    )
    

    7) Connect and authenticate as myTester.

    mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"
    

    I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/

    Show Hide div if, if statement is true

    This does not need jquery, you could set a variable inside the if and use it in html or pass it thru your template system if any

    <?php
    $showDivFlag=false
    $query3 = mysql_query($query3);
    $numrows = mysql_num_rows($query3);
    if ($numrows > 0){
        $fvisit = mysql_fetch_array($result3);
        $showDivFlag=true;
     }else {
    
     }
    
    ?>
    

    later in html

      <div id="results" <?php if ($showDivFlag===false){?>style="display:none"<?php } ?>>
    

    Difference between array_push() and $array[] =

    You should always use $array[] if possible because as the box states there is no overhead for the function call. Thus it is a bit faster than the function call.

    Should I use int or Int32

    I use int in the event that Microsoft changes the default implementation for an integer to some new fangled version (let's call it Int32b).

    Microsoft can then change the int alias to Int32b, and I don't have to change any of my code to take advantage of their new (and hopefully improved) integer implementation.

    The same goes for any of the type keywords.

    How to execute VBA Access module?

    If you just want to run a function for testing purposes, you can use the Immediate Window in Access.

    Press Ctrl + G in the VBA editor to open it.

    Then you can run your functions like this:

    • ?YourFunction("parameter")
      (for functions with a return value - the return value is displayed in the Immediate Window)
    • YourSub "parameter"
      (for subs without a return value, or for functions when you don't care about the return value)
    • ?variable
      (to display the value of a variable)

    How to do a for loop in windows command line?

    You might also consider adding ".

    For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

    Tainted canvases may not be exported

    If someone views on my answer, you maybe in this condition:

    1. Trying to get a map screenshot in canvas using openlayers (version >= 3)
    2. And viewed the example of exporting map
    3. Using ol.source.XYZ to render map layer

    Bingo!

    Using ol.source.XYZ.crossOrigin = 'Anonymous' to solve your confuse. Or like following code:

         var baseLayer = new ol.layer.Tile({
             name: 'basic',
             source: new ol.source.XYZ({
                 url: options.baseMap.basic,
                 crossOrigin: "Anonymous"
             })
         });
    

    Using `date` command to get previous, current and next month

    the main problem occur when you don't have date --date option available and you don't have permission to install it, then try below -

    Previous month
    #cal -3|awk 'NR==1{print toupper(substr($1,1,3))"-"$2}'
    DEC-2016 
    Current month
    #cal -3|awk 'NR==1{print toupper(substr($3,1,3))"-"$4}'
    JAN-2017
    Next month
    #cal -3|awk 'NR==1{print toupper(substr($5,1,3))"-"$6}'
    FEB-2017
    

    How do I set the default schema for a user in MySQL

    There is no default database for user. There is default database for current session.

    You can get it using DATABASE() function -

    SELECT DATABASE();
    

    And you can set it using USE statement -

    USE database1;
    

    You should set it manually - USE db_name, or in the connection string.

    How to create a sticky navigation bar that becomes fixed to the top after scrolling

    I have found this simple javascript snippet very useful.

    $(document).ready(function()
    {
        var navbar = $('#navbar');
    
        navbar.after('<div id="more-div" style="height: ' + navbar.outerHeight(true) + 'px" class="hidden"></div>');
        var afternavbar = $('#more-div');
    
        var abovenavbar = $('#above-navbar');
    
        $(window).on('scroll', function()
        {
            if ($(window).scrollTop() > abovenavbar.height())
            {
                navbar.addClass('navbar-fixed-top');
                afternavbar.removeClass('hidden');
            }
            else
            {
                navbar.removeClass('navbar-fixed-top');
                afternavbar.addClass('hidden');
            }
        });
    });
    

    Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

    In my case I added the missing import, which was the ReactiveFormsModule.

    Regex: Use start of line/end of line signs (^ or $) in different context

    you just need to use word boundary (\b) instead of ^ and $:

    \bgarp\b
    

    Is it possible to run selenium (Firefox) web driver without a GUI?

    Yes. You can use HTMLUnitDriver instead for FirefoxDriver while starting webdriver. This is headless browser setup. Details can be found here.

    How to remove an element from a list by index

    It doesn't sound like you're working with a list of lists, so I'll keep this short. You want to use pop since it will remove elements not elements that are lists, you should use del for that. To call the last element in python it's "-1"

    >>> test = ['item1', 'item2']
    >>> test.pop(-1)
    'item2'
    >>> test
    ['item1']
    

    builtins.TypeError: must be str, not bytes

    The outfile should be in binary mode.

    outFile = open('output.xml', 'wb')
    

    Interview question: Check if one string is a rotation of other string

    Opera's simple pointer rotation trick works, but it is extremely inefficient in the worst case in running time. Simply imagine a string with many long repetitive runs of characters, ie:

    S1 = HELLOHELLOHELLO1HELLOHELLOHELLO2

    S2 = HELLOHELLOHELLO2HELLOHELLOHELLO1

    The "loop until there's a mismatch, then increment by one and try again" is a horrible approach, computationally.

    To prove that you can do the concatenation approach in plain C without too much effort, here is my solution:

      int isRotation(const char* s1, const char* s2) {
            assert(s1 && s2);
    
            size_t s1Len = strlen(s1);
    
            if (s1Len != strlen(s2)) return 0;
    
            char s1SelfConcat[ 2 * s1Len + 1 ];
    
            sprintf(s1SelfConcat, "%s%s", s1, s1);   
    
            return (strstr(s1SelfConcat, s2) ? 1 : 0);
    }
    

    This is linear in running time, at the expense of O(n) memory usage in overhead.

    (Note that the implementation of strstr() is platform-specific, but if particularly brain-dead, can always be replaced with a faster alternative such as the Boyer-Moore algorithm)

    Safest way to get last record ID from a table

    SELECT IDENT_CURRENT('Table')
    

    You can use one of these examples:

    SELECT * FROM Table 
    WHERE ID = (
        SELECT IDENT_CURRENT('Table'))
    
    SELECT * FROM Table
    WHERE ID = (
        SELECT MAX(ID) FROM Table)
    
    SELECT TOP 1 * FROM Table
    ORDER BY ID DESC
    

    But the first one will be more efficient because no index scan is needed (if you have index on Id column).

    The second one solution is equivalent to the third (both of them need to scan table to get max id).

    How to Load RSA Private Key From File

    You need to convert your private key to PKCS8 format using following command:

    openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key
    

    After this your java program can read it.

    RS256 vs HS256: What's the difference?

    There is a difference in performance.

    Simply put HS256 is about 1 order of magnitude faster than RS256 for verification but about 2 orders of magnitude faster than RS256 for issuing (signing).

     640,251  91,464.3 ops/s
      86,123  12,303.3 ops/s (RS256 verify)
       7,046   1,006.5 ops/s (RS256 sign)
    

    Don't get hung up on the actual numbers, just think of them with respect of each other.

    [Program.cs]

    class Program
    {
        static void Main(string[] args)
        {
            foreach (var duration in new[] { 1, 3, 5, 7 })
            {
                var t = TimeSpan.FromSeconds(duration);
    
                byte[] publicKey, privateKey;
    
                using (var rsa = new RSACryptoServiceProvider())
                {
                    publicKey = rsa.ExportCspBlob(false);
                    privateKey = rsa.ExportCspBlob(true);
                }
    
                byte[] key = new byte[64];
    
                using (var rng = new RNGCryptoServiceProvider())
                {
                    rng.GetBytes(key);
                }
    
                var s1 = new Stopwatch();
                var n1 = 0;
    
                using (var hs256 = new HMACSHA256(key))
                {
                    while (s1.Elapsed < t)
                    {
                        s1.Start();
                        var hash = hs256.ComputeHash(privateKey);
                        s1.Stop();
                        n1++;
                    }
                }
    
                byte[] sign;
    
                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.ImportCspBlob(privateKey);
    
                    sign = rsa.SignData(privateKey, "SHA256");
                }
    
                var s2 = new Stopwatch();
                var n2 = 0;
    
                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.ImportCspBlob(publicKey);
    
                    while (s2.Elapsed < t)
                    {
                        s2.Start();
                        var success = rsa.VerifyData(privateKey, "SHA256", sign);
                        s2.Stop();
                        n2++;
                    }
                }
    
                var s3 = new Stopwatch();
                var n3 = 0;
    
                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.ImportCspBlob(privateKey);
    
                    while (s3.Elapsed < t)
                    {
                        s3.Start();
                        rsa.SignData(privateKey, "SHA256");
                        s3.Stop();
                        n3++;
                    }
                }
    
                Console.WriteLine($"{s1.Elapsed.TotalSeconds:0} {n1,7:N0} {n1 / s1.Elapsed.TotalSeconds,9:N1} ops/s");
                Console.WriteLine($"{s2.Elapsed.TotalSeconds:0} {n2,7:N0} {n2 / s2.Elapsed.TotalSeconds,9:N1} ops/s");
                Console.WriteLine($"{s3.Elapsed.TotalSeconds:0} {n3,7:N0} {n3 / s3.Elapsed.TotalSeconds,9:N1} ops/s");
    
                Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n2 / s2.Elapsed.TotalSeconds),9:N1}x slower (verify)");
                Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n3 / s3.Elapsed.TotalSeconds),9:N1}x slower (issue)");
    
                // RS256 is about 7.5x slower, but it can still do over 10K ops per sec.
            }
        }
    }
    

    Passing route control with optional parameter after root in express?

    Express version:

    "dependencies": {
        "body-parser": "^1.19.0",
        "express": "^4.17.1"
      }
    

    Optional parameter are very much handy, you can declare and use them easily using express:

    app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
        console.log("category Id: "+req.params.cId);
        console.log("product ID: "+req.params.pId);
        if (req.params.batchNo){
            console.log("Batch No: "+req.params.batchNo);
        }
    });
    

    In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

    Now I can call with only categoryId and productId or with all three-parameter.

    http://127.0.0.1:3000/api/v1/tours/5/10
    //or
    http://127.0.0.1:3000/api/v1/tours/5/10/8987
    

    enter image description here enter image description here

    How do I change a PictureBox's image?

    You can use the ImageLocation property of pictureBox1:

    pictureBox1.ImageLocation = @"C:\Users\MSI\Desktop\MYAPP\Slider\Slider\bt1.jpg";
    

    Any way to declare an array in-line?

    As Draemon says, the closest that Java comes to inline arrays is new String[]{"blah", "hey", "yo"} however there is a neat trick that allows you to do something like

    array("blah", "hey", "yo") with the type automatically inferred.

    I have been working on a useful API for augmenting the Java language to allow for inline arrays and collection types. For more details google project Espresso4J or check it out here

    How to run a script as root on Mac OS X?

    sudo ./scriptname

    sudo bash will basically switch you over to running a shell as root, although it's probably best to stay as su as little as possible.

    Javascript "Not a Constructor" Exception while creating objects

    The code as posted in the question cannot generate that error, because Project is not a user-defined function / valid constructor.

    function x(a,b,c){}
    new x(1,2,3);               // produces no errors
    

    You've probably done something like this:

    function Project(a,b,c) {}
    Project = {};               // or possibly   Project = new Project
    new Project(1,2,3);         // -> TypeError: Project is not a constructor
    

    Variable declarations using var are hoisted and thus always evaluated before the rest of the code. So, this can also be causing issues:

    function Project(){}
    function localTest() {
        new Project(1,2,3); // `Project` points to the local variable,
                            // not the global constructor!
    
       //...some noise, causing you to forget that the `Project` constructor was used
        var Project = 1;    // Evaluated first
    }
    

    How do you find the sum of all the numbers in an array in Java?

    In Apache Math : There is StatUtils.sum(double[] arr)

    How to install "ifconfig" command in my ubuntu docker image?

    You could also consider:

    RUN apt-get update && apt-get install -y iputils-ping
    

    (as Contango comments: you must first run apt-get update, to avoid error with missing repository).

    See "Replacing ifconfig with ip"

    it is most often recommended to move forward with the command that has replaced ifconfig. That command is ip, and it does a great job of stepping in for the out-of-date ifconfig.

    But as seen in "Getting a Docker container's IP address from the host", using docker inspect can be more useful depending on your use case.

    How do I set an ASP.NET Label text from code behind on page load?

    In the page load event you set your label

    lbl_username.text = "some text";

    CSS: Force float to do a whole new line

    You can wrap them in a div and give the div a set width (the width of the widest image + margin maybe?) and then float the divs. Then, set the images to the center of their containing divs. Your margins between images won't be consistent for the differently sized images but it'll lay out much more nicely on the page.

    How do I remove blank elements from an array?

    Here is one more approach to achieve this

    we can use presence with select

    cities = ["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"]
    
    cities.select(&:presence)
    
    ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
    

    Powershell send-mailmessage - email to multiple recipients

    here is a full (gmail) and simple solution... just use normal ; delimiter.. best for passing in as params.

    $to = "[email protected];[email protected]"
    $user = "[email protected]"    
    $pass = ConvertTo-SecureString -String "pass" -AsPlainText -Force
    
    $cred = New-Object System.Management.Automation.PSCredential $user, $pass
    $mailParam = @{
        To = $to.Split(';')
        From = "IT Alerts <[email protected]>"
        Subject = "test"
        Body = "test"
        SmtpServer = "smtp.gmail.com"
        Port = 587
        Credential = $cred
    }
    
    Send-MailMessage @mailParam -UseSsl
    

    Template not provided using create-react-app

    TLDR: Uninstall the global package using npm uninstall -g create-react-app and generate new react apps using npx create-react-app app.


    Issue

    You're using an older version of create-react-app that you have installed globally using npm. The create-react-app command invokes this global package.

    You could've confirmed that you were using an outdated version by running npm outdated -g create-react-app or comparing create-react-app --version with npm view create-react-app.

    The fact that the version of react-scripts was up to date, has nothing to do with the version of the package that is bootstrapping the app (create-react-app), which grabs the latest versions of the packages that it uses (react-scripts in this case).

    Solution

    If you want to continue using the create-react-app command, you'll need to update the global package using npm update -g create-react-app. Note that you'll want to do this periodically to keep it up to date. You'll notice that create-react-app does not recommend this (noted in the logs from your install).

    A better approach would be to delete the global install entirely (npm uninstall -g create-react-app) and instead use npx so that it grabs the latest version of the package every time (more detail on npx below).

    You should confirm that it was uninstalled globally by trying to use create-react-app to make sure the command is "not found".

    Issues with uninstalling?

    You can debug where it was installed using which create-react-app. If you're having issues uninstalling it, you may have multiple versions of node/npm on your machine (from multiple installs, or because you use a node version manager such as nvm). This is a separate issue I won't address here, but there's some info in this answer.

    A quick nuclear approach would be to forcefully remove it (rm -rf) at the path that which create-react-app returns.


    Supplement

    Global npm packages and the npx command

    $ NPM_PACKAGE_NAME will always use the globally installed version of the package, regardless of which directory you're in.

    $ npx NPM_PACKAGE_NAME will use the first version of the package that it finds when searching up from the current directory to the root:

    • If you have the package in your current directory, it will use that.
    • Else if you have the package in a directory that is a parent of your current directory, it will use the first one it finds.
    • Else if you have the package installed globally, it will use that.
    • Else if you don't have the package at all, it will temporarily install it, use it, and then discard it. - this is the best way to ensure the package is up to date.

    More info about npx can be found in this answer.

    Using npx with create-react-app

    create-react-app has some special commands/aliases to create a react app (instead of npx) that are specific to that package (yarn create react-app, npm init react-app), but npx create-react-app will work the same as it does with other packages.

    yarn vs npm global installs

    Yarn stores global installs in a different folder than npm, which is why yarn create react-app would work immediately without uninstalling the global npm package (as far as yarn is concerned, the package hasn't been installed).

    This is just a temporary solution though, as you'll need to remember to always use yarn instead of npm when using Create React App.

    Maximum size of a varchar(max) variable

    EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value syntax is incorrect.

    I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. error message. In 2008, the modified script is still successful.

    declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
    declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
    declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
    declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
    select LEN(@GGMMsg)
    

    printf \t option

    That's something controlled by your terminal, not by printf.

    printf simply sends a \t to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.

    How to get enum value by string or int

    There are numerous ways to do this, but if you want a simple example, this will do. It just needs to be enhanced with necessary defensive coding to check for type safety and invalid parsing, etc.

        /// <summary>
        /// Extension method to return an enum value of type T for the given string.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T ToEnum<T>(this string value)
        {
            return (T) Enum.Parse(typeof(T), value, true);
        }
    
        /// <summary>
        /// Extension method to return an enum value of type T for the given int.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T ToEnum<T>(this int value)
        {
            var name = Enum.GetName(typeof(T), value);
            return name.ToEnum<T>();
        }
    

    How to compare numbers in bash?

    I solved this by using a small function to convert version strings to plain integer values that can be compared:

    function versionToInt() {
      local IFS=.
      parts=($1)
      let val=1000000*parts[0]+1000*parts[1]+parts[2]
      echo $val
    }
    

    This makes two important assumptions:

    1. Input is a "normal SemVer string"
    2. Each part is between 0-999

    For example

    versionToInt 12.34.56  # --> 12034056
    versionToInt 1.2.3     # -->  1002003
    

    Example testing whether npm command meets minimum requirement ...

    NPM_ACTUAL=$(versionToInt $(npm --version))  # Capture npm version
    NPM_REQUIRED=$(versionToInt 4.3.0)           # Desired version
    if [ $NPM_ACTUAL \< $NPM_REQUIRED ]; then
      echo "Please update to npm@latest"
      exit 1
    fi
    

    How to set Java SDK path in AndroidStudio?

    Click "use embedded JDK" on version Android Studio 3.2.1

    click this box

    Insert entire DataTable into database at once instead of row by row?

    Consider this approach, you don't need a for loop:

    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
    {
        bulkCopy.DestinationTableName = 
            "dbo.BulkCopyDemoMatchingColumns";
    
        try
        {
            // Write from the source to the destination.
            bulkCopy.WriteToServer(ExitingSqlTableName);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    

    A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

    I had the same issue because of the wrong order of the code statements. Maintain the below order to resolve the issue. All get methods statements first and later httpClient methods.

          HttpClient httpClient = new HttpClient();
    get = new GetMethod(instanceUrl+usersEndPointUri);
    get.setRequestHeader("Content-Type", "application/json");
    get.setRequestHeader("Accept", "application/json");
    
    httpClient.getParams().setParameter("http.protocol.single-cookie-header", true);
    httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    httpClient.executeMethod(get);
    

    Setting the zoom level for a MKMapView

    Based on @AdilSoomro's great answer. I have come up with this:

    @interface MKMapView (ZoomLevel)
    - (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                      zoomLevel:(NSUInteger)zoomLevel
                       animated:(BOOL)animated;
    
    -(double) getZoomLevel;
    @end
    
    
    
    @implementation MKMapView (ZoomLevel)
    
    - (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                      zoomLevel:(NSUInteger)zoomLevel animated:(BOOL)animated {
        MKCoordinateSpan span = MKCoordinateSpanMake(0, 360/pow(2, zoomLevel)*self.frame.size.width/256);
        [self setRegion:MKCoordinateRegionMake(centerCoordinate, span) animated:animated];
    }
    
    
    -(double) getZoomLevel {
        return log2(360 * ((self.frame.size.width/256) / self.region.span.longitudeDelta));
    }
    
    @end
    

    Mysql SELECT CASE WHEN something then return field

    You are mixing the 2 different CASE syntaxes inappropriately.

    Use this style (Searched)

      CASE  
      WHEN u.nnmu ='0' THEN mu.naziv_mesta
      WHEN u.nnmu ='1' THEN m.naziv_mesta
     ELSE 'GRESKA'
     END as mesto_utovara,
    

    Or this style (Simple)

      CASE u.nnmu 
      WHEN '0' THEN mu.naziv_mesta
      WHEN '1' THEN m.naziv_mesta
     ELSE 'GRESKA'
     END as mesto_utovara,
    

    Not This (Simple but with boolean search predicates)

      CASE u.nnmu 
      WHEN u.nnmu ='0' THEN mu.naziv_mesta
      WHEN u.nnmu ='1' THEN m.naziv_mesta
     ELSE 'GRESKA'
     END as mesto_utovara,
    

    In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

    For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

     SELECT CASE  '0'
      WHEN 1 THEN '0'
      WHEN 0 THEN '1'
     ELSE 'GRESKA'
     END as mesto_utovara
    

    if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

     SELECT CASE  '1'
      WHEN 0 THEN '0'
      WHEN 1 THEN '1'
     ELSE 'GRESKA'
     END as mesto_utovara
    

    Java ByteBuffer to String

    The answers referring to simply calling array() are not quite correct: when the buffer has been partially consumed, or is referring to a part of an array (you can ByteBuffer.wrap an array at a given offset, not necessarily from the beginning), we have to account for that in our calculations. This is the general solution that works for buffers in all cases (does not cover encoding):

    if (myByteBuffer.hasArray()) {
        return new String(myByteBuffer.array(),
            myByteBuffer.arrayOffset() + myByteBuffer.position(),
            myByteBuffer.remaining());
    } else {
        final byte[] b = new byte[myByteBuffer.remaining()];
        myByteBuffer.duplicate().get(b);
        return new String(b);
    }
    

    For the concerns related to encoding, see Andy Thomas' answer.

    How to target the href to div

    if you use

    angularjs

    you have just to write the right css in order to frame you div html code

    <div 
    style="height:51px;width:111px;margin-left:203px;" 
    ng-click="nextDetail()">
    </div>
    


    JS Code(in your controller):

    $scope.nextDetail = function()
    {
    ....
    }
    

    Ignore self-signed ssl cert using Jersey Client

    Just adding the same code with the imports. Also contains the unimplemented code that is needed for compilation. I initially had trouble finding out what was imported for this code. Also adding the right package for the X509Certificate. Got this working with trial and error:

    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import javax.security.cert.CertificateException;
    import javax.security.cert.X509Certificate;
    import javax.ws.rs.core.MultivaluedMap;
    
     TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
    
         public java.security.cert.X509Certificate[] getAcceptedIssuers() {
             java.security.cert.X509Certificate[] chck = null;
             ;
             return chck;
         }
    
         public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                 throws CertificateException {
             // TODO Auto-generated method stub
    
         }
    
         public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                 throws CertificateException {
    
         }
    
         public void checkClientTrusted(
                 java.security.cert.X509Certificate[] arg0, String arg1)
                         throws java.security.cert.CertificateException {
             // TODO Auto-generated method stub
    
         }
    
         public void checkServerTrusted(
                 java.security.cert.X509Certificate[] arg0, String arg1)
                         throws java.security.cert.CertificateException {
             // TODO Auto-generated method stub
    
         }
     } };
    
     // Install the all-trusting trust manager
     try {
         SSLContext sc = SSLContext.getInstance("TLS");
         sc.init(null, trustAllCerts, new SecureRandom());
         HttpsURLConnection
         .setDefaultSSLSocketFactory(sc.getSocketFactory());
     } catch (Exception e) {
         ;
     }
    

    AttributeError: 'module' object has no attribute 'urlretrieve'

    Suppose you have following lines of code

    MyUrl = "www.google.com" #Your url goes here
    urllib.urlretrieve(MyUrl)
    

    If you are receiving following error message

    AttributeError: module 'urllib' has no attribute 'urlretrieve'
    

    Then you should try following code to fix the issue:

    import urllib.request
    MyUrl = "www.google.com" #Your url goes here
    urllib.request.urlretrieve(MyUrl)
    

    Why is there no SortedList in Java?

    Consider using indexed-tree-map . It's an enhanced JDK's TreeSet that provides access to element by index and finding the index of an element without iteration or hidden underlying lists that back up the tree. The algorithm is based on updating weights of changing nodes every time there is a change.

    Show "Open File" Dialog

    Addition to what Albert has already said:

    This code (a mashup of various samples) provides the ability to have a SaveAs dialog box

    Function getFileName() As String
        Dim fDialog    As Object
        Set fDialog = Application.FileDialog(msoFileDialogSaveAs)
        Dim varFile As Variant
    
        With fDialog
           .AllowMultiSelect = False
           .Title = "Select File Location to Export XLSx :"
           .InitialFileName = "jeffatwood.xlsx"
    
        If .Show = True Then
           For Each varFile In .SelectedItems
             getFileName = varFile
           Next
        End If
    End With
    End Function
    

    How to delete columns in pyspark dataframe

    Adding to @Patrick's answer, you can use the following to drop multiple columns

    columns_to_drop = ['id', 'id_copy']
    df = df.drop(*columns_to_drop)
    

    How to disable logging on the standard error stream in Python?

    No need to divert stdout. Here is better way to do it:

    import logging
    class MyLogHandler(logging.Handler):
        def emit(self, record):
            pass
    
    logging.getLogger().addHandler(MyLogHandler())
    

    An even simpler way is:

    logging.getLogger().setLevel(100)
    

    Convert International String to \u Codes in java

    There's a command-line tool that ships with java called native2ascii. This converts unicode files to ASCII-escaped files. I've found that this is a necessary step for generating .properties files for localization.

    @font-face src: local - How to use the local font if the user already has it?

    If you want to check for local files first do:

    @font-face {
    font-family: 'Green Sans Web';
    src:
        local('Green Web'),
        local('GreenWeb-Regular'),
        url('GreenWeb.ttf');
    }
    

    There is a more elaborate description of what to do here.

    Counting Chars in EditText Changed Listener

    how about just getting the length of char in your EditText and display it?

    something along the line of

    tv.setText(s.length() + " / " + String.valueOf(charCounts));
    

    How to set user environment variables in Windows Server 2008 R2 as a normal user?

    There are three ways

    1) This runs the GUI editor for the user environment variables. It does exactly what the OP wanted to do and does not prompt for administrative credentials.

    rundll32.exe sysdm.cpl,EditEnvironmentVariables
    

    (bonus: This works on Windows Vista to Windows 10 for desktops and Windows Server 2008 through Server 2016. It does not work on Windows NT, 2000, XP, and 2003. However, on the older systems you can use sysdm.cpl without the ",EditEnvironmentVariables" parameter and then navigate to the Advanced tab and then Environment Variables button.)

    2) Use the SETX command from the command prompt. This is like the set command but updates the environment that's stored in the registry. Unfortunately, SETX is not as easy to use as the built in SET command. There's no way to list the variables for example. Thus it's impossible to do something such as appending a folder to the user's PATH variable. While SET will display the variables you don't know which ones are user vs. system variables and the PATH that's shown is a combination of both.

    3) Use regedit and navigate to HKEY_CURRENT_USER\Environment

    Keep in mind that changes to the user's environment does not immediately propagate to all processes currently running for that user. You can see this in a command prompt where your changes will not be visible if you use SET. For example

    rem Add a user environment variable named stackoverflow that's set to "test"
    setx stackoverflow test
    set st
    

    This should show all variables whose names start with the letters "st". If there are none then it displays "Environment variable st not defined". Exit the command prompt and start another. Try set st again and you'll see

    stackoverflow=test
    

    To delete the stackoverflow variable use

    setx stackoverflow ""
    

    It will respond with "SUCCESS: Specified value was saved." which looks strange given you want to delete the variable. However, if you start a new command prompt then set st will show that there are no variables starting with the letters "st"

    (correction - I discovered that setx stackoverflow "" did not delete the variable. It's in the registry as an empty string. The SET command though interprets it as though there is no variable. if not defined stackoverflow echo Not defined says it's not defined.)

    align textbox and text/labels in html?

    You have two boxes, left and right, for each label/input pair. Both boxes are in one row and have fixed width. Now, you just have to make label text float to the right with text-align: right;

    Here's a simple example:

    http://jsfiddle.net/qP46X/

    Difference between CLOB and BLOB from DB2 and Oracle Perspective?

    They can be considered as equivalent. The limits in size are the same:

    • Maximum length of CLOB (in bytes or OCTETS)) 2 147 483 647
    • Maximum length of BLOB (in bytes) 2 147 483 647

    There is also the DBCLOBs, for double byte characters.

    References:

    How to log cron jobs?

    There are at least three different types of logging:

    1. The logging BEFORE the program is executed, which only logs IF the cronjob TRIED to execute the command. That one is located in /var/log/syslog, as already mentioned by @Matthew Lock.

    2. The logging of errors AFTER the program tried to execute, which can be sent to an email or to a file, as mentioned by @Spliffster. I prefer logging to a file, because with email THEN you have a NEW source of problems, and its checking if email sending and reception is working perfectly. Sometimes it is, sometimes it's not. For example, in a simple common desktop machine in which you are not interested in configuring an smtp, sometimes you will prefer logging to a file:

       * * * *  COMMAND_ABSOLUTE_PATH > /ABSOLUTE_PATH_TO_LOG 2>&1
      
      • I would also consider checking the permissions of /ABSOLUTE_PATH_TO_LOG, and run the command from that user's permissions. Just for verification, while you test whether it might be a potential source of problems.
    3. The logging of the program itself, with its own error-handling and logging for tracking purposes.

    There are some common sources of problems with cronjobs: * The ABSOLUTE PATH of the binary to be executed. When you run it from your shell, it might work, but the cron process seems to use another environment, and hence it doesn't always find binaries if you don't use the absolute path. * The LIBRARIES used by a binary. It's more or less the same previous point, but make sure that, if simply putting the NAME of the command, is referring to exactly the binary which uses the very same library, or better, check if the binary you are referring with the absolute path is the very same you refer when you use the console directly. The binaries can be found using the locate command, for example:

    $locate python
    

    Be sure that the binary you will refer, is the very same the binary you are calling in your shell, or simply test again in your shell using the absolute path that you plan to put in the cronjob.

    • Another common source of problems is the syntax in the cronjob. Remember that there are special characters you can use for lists (commas), to define ranges (dashes -), to define increment of ranges (slashes), etc. Take a look: http://www.softpanorama.org/Utilities/cron.shtml

    Efficient way to rotate a list in python

    Simplest way I can think of:

    a.append(a.pop(0))
    

    Most common C# bitwise operations on enums

    For the best performance and zero garbage, use this:

    using System;
    using T = MyNamespace.MyFlags;
    
    namespace MyNamespace
    {
        [Flags]
        public enum MyFlags
        {
            None = 0,
            Flag1 = 1,
            Flag2 = 2
        }
    
        static class MyFlagsEx
        {
            public static bool Has(this T type, T value)
            {
                return (type & value) == value;
            }
    
            public static bool Is(this T type, T value)
            {
                return type == value;
            }
    
            public static T Add(this T type, T value)
            {
                return type | value;
            }
    
            public static T Remove(this T type, T value)
            {
                return type & ~value;
            }
        }
    }
    

    anaconda/conda - install a specific package version

    If any of these characters, '>', '<', '|' or '*', are used, a single or double quotes must be used

    conda install [-y] package">=version"
    conda install [-y] package'>=low_version, <=high_version'
    conda install [-y] "package>=low_version, <high_version"
    
    conda install -y torchvision">=0.3.0"
    conda install  openpyxl'>=2.4.10,<=2.6.0'
    conda install "openpyxl>=2.4.10,<3.0.0"
    

    where option -y, --yes Do not ask for confirmation.

    Here is a summary:

    Format         Sample Specification     Results
    Exact          qtconsole==4.5.1         4.5.1
    Fuzzy          qtconsole=4.5            4.5.0, 4.5.1, ..., etc.
    >=, >, <, <=  "qtconsole>=4.5"          4.5.0 or higher
                   qtconsole"<4.6"          less than 4.6.0
    
    OR            "qtconsole=4.5.1|4.5.2"   4.5.1, 4.5.2
    AND           "qtconsole>=4.3.1,<4.6"   4.3.1 or higher but less than 4.6.0
    

    Potion of the above information credit to Conda Cheat Sheet

    Tested on conda 4.7.12

    Is std::vector copying the objects with a push_back?

    std::vector always makes a copy of whatever is being stored in the vector.

    If you are keeping a vector of pointers, then it will make a copy of the pointer, but not the instance being to which the pointer is pointing. If you are dealing with large objects, you can (and probably should) always use a vector of pointers. Often, using a vector of smart pointers of an appropriate type is good for safety purposes, since handling object lifetime and memory management can be tricky otherwise.

    How to wrap text of HTML button with fixed width?

    white-space: normal;
    word-wrap: break-word;
    

    Mine works with both

    MySQL INSERT INTO ... VALUES and SELECT

    try this

    INSERT INTO TABLE1 (COL1 , COL2,COL3) values
    ('A STRING' , 5 , (select idTable2 from Table2) )
    where ...
    

    What is the difference between a generative and a discriminative algorithm?

    The short answer

    Many of the answers here rely on the widely-used mathematical definition [1]:

    • Discriminative models directly learn the conditional predictive distribution p(y|x).
    • Generative models learn the joint distribution p(x,y) (or rather, p(x|y) and p(y)).
      • Predictive distribution p(y|x) can be obtained with Bayes' rule.

    Although very useful, this narrow definition assumes the supervised setting, and is less handy when examining unsupervised or semi-supervised methods. It also doesn't apply to many contemporary approaches for deep generative modeling. For example, now we have implicit generative models, e.g. Generative Adversarial Networks (GANs), which are sampling-based and don't even explicitly model the probability density p(x) (instead learning a divergence measure via the discriminator network). But we call them "generative models” since they are used to generate (high-dimensional [10]) samples.

    A broader and more fundamental definition [2] seems equally fitting for this general question:

    • Discriminative models learn the boundary between classes.
      • So they can discriminate between different kinds of data instances.
    • Generative models learn the distribution of data.
      • So they can generate new data instances.

    From http://primo.ai/index.php?title=Discriminative_vs._Generative Image source


    A closer look

    Even so, this question implies somewhat of a false dichotomy [3]. The generative-discriminative "dichotomy" is in fact a spectrum which you can even smoothly interpolate between [4].

    As a consequence, this distinction gets arbitrary and confusing, especially when many popular models do not neatly fall into one or the other [5,6], or are in fact hybrid models (combinations of classically "discriminative" and "generative" models).

    Nevertheless it's still a highly useful and common distinction to make. We can list some clear-cut examples of generative and discriminative models, both canonical and recent:

    • Generative: Naive Bayes, latent Dirichlet allocation (LDA), Generative Adversarial Networks (GAN), Variational Autoencoders (VAE), normalizing flows.
    • Discriminative: Support vector machine (SVM), logistic regression, most deep neural networks.

    There is also a lot of interesting work deeply examining the generative-discriminative divide [7] and spectrum [4,8], and even transforming discriminative models into generative models [9].

    In the end, definitions are constantly evolving, especially in this rapidly growing field :) It's best to take them with a pinch of salt, and maybe even redefine them for yourself and others.


    Sources

    1. Possibly originating from "Machine Learning - Discriminative and Generative" (Tony Jebara, 2004).
    2. Crash Course in Machine Learning by Google
    3. The Generative-Discriminative Fallacy
    4. "Principled Hybrids of Generative and Discriminative Models" (Lasserre et al., 2006)
    5. @shimao's question
    6. Binu Jasim's answer
    7. Comparing logistic regression and naive Bayes:
    8. https://www.microsoft.com/en-us/research/wp-content/uploads/2016/04/DengJaitly2015-ch1-2.pdf
    9. "Your classifier is secretly an energy-based model" (Grathwohl et al., 2019)
    10. Stanford CS236 notes: Technically, a probabilistic discriminative model is also a generative model of the labels conditioned on the data. However, the term generative models is typically reserved for high dimensional data.

    How do I implement a progress bar in C#?

    The idea behind reporting progress with the background worker is through sending a 'percent completed' event. You are yourself responsible for determining somehow 'how much' work has been completed. Unfortunately this is often the most difficult part.

    In your case, the bulk of the work is database-related. There is to my knowledge no way to get progress information from the DB directly. What you can try to do however, is split up the work dynamically. E.g., if you need to read a lot of data, a naive way to implement this could be.

    • Determine how many rows are to be retrieved (SELECT COUNT(*) FROM ...)
    • Divide the actual reading in smaller chunks, reporting progress every time one chunk is completed:

      for (int i = 0; i < count; i++)
      {
          bgWorker.ReportProgress((100 * i) / count);
          // ... (read data for step i)
      }
      

    How to get the Android device's primary e-mail address

    public String getUsername() {
        AccountManager manager = AccountManager.get(this);
        Account[] accounts = manager.getAccountsByType("com.google");
        List<String> possibleEmails = new LinkedList<String>();
    
        for (Account account : accounts) {
            // TODO: Check possibleEmail against an email regex or treat
            // account.name as an email address only for certain account.type values.
            possibleEmails.add(account.name);
        }
    
        if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
            String email = possibleEmails.get(0);
            String[] parts = email.split("@");
    
            if (parts.length > 1)
                return parts[0];
        }
        return null;
    }
    

    What happens if you don't commit a transaction to a database (say, SQL Server)?

    Any uncomitted transaction will leave the server locked and other queries won't execute on the server. You either need to rollback the transaction or commit it. Closing out of SSMS will also terminate the transaction which will allow other queries to execute.

    List(of String) or Array or ArrayList

    look to the List AddRange method here

    How to get input from user at runtime

    To read the user input and store it in a variable, for later use, you can use SQL*Plus command ACCEPT.

    Accept <your variable> <variable type if needed [number|char|date]> prompt 'message'
    

    example

    accept x number prompt 'Please enter something: '
    

    And then you can use the x variable in a PL/SQL block as follows:

    declare 
      a number;
    begin
      a := &x;
    end;
    /
    

    Working with a string example:

    accept x char prompt 'Please enter something: '
    
    declare 
      a varchar2(10);
    begin
      a := '&x';   -- for a substitution variable of char data type 
    end;           -- to be treated as a character string it needs
    /              -- to be enclosed with single quotation marks
    

    How to get selenium to wait for ajax response?

    A more general solution than waiting for an element would be to wait for all the connections to the server to close. This will allow you to wait for all ajax calls to finish, even if they don't have any callback and thus don't affect the page. More details can be found here.

    Using C# and jQuery, I have created the following method to wait for all AJax calls to complete (if anyone have more direct ways of accessing JS variables from C#, please comment):

    internal void WaitForAjax(int timeOut = 15)
    {
        var value = "";
        RepeatUntil(
            () => value = GetJavascriptValue("jQuery.active"), 
            () => value == "0", 
            "Ajax calls did not complete before timeout"
        );
    }
    
    internal void RepeatUntil(Action repeat, Func<bool> until, string errorMessage, int timeout = 15)
    {
        var end = DateTime.Now + TimeSpan.FromSeconds(timeout);
        var complete = false;
    
        while (DateTime.Now < end)
        {
            repeat();
            try
            {
                if (until())
                {
                    complete = true;
                    break;
                }
            }
            catch (Exception)
            { }
            Thread.Sleep(500);
        }
        if (!complete)
            throw new TimeoutException(errorMessage);
    }
    
    internal string GetJavascriptValue(string variableName)
    {
        var id = Guid.NewGuid().ToString();
        _selenium.RunScript(String.Format(@"window.$('body').append(""<input type='text' value='""+{0}+""' id='{1}'/>"");", variableName, id));
        return _selenium.GetValue(id);
    }
    

    Another git process seems to be running in this repository

    Use the below command in the root directory of the application. This will delete the index.lock file and release the active lock.

    rm .git/index.lock
    

    Reverse order of foreach list items

    Walking Backwards

    If you're looking for a purely PHP solution, you can also simply count backwards through the list, access it front-to-back:

    $accounts = Array(
      '@jonathansampson',
      '@f12devtools',
      '@ieanswers'
    );
    
    $index = count($accounts);
    
    while($index) {
      echo sprintf("<li>%s</li>", $accounts[--$index]);
    }
    

    The above sets $index to the total number of elements, and then begins accessing them back-to-front, reducing the index value for the next iteration.

    Reversing the Array

    You could also leverage the array_reverse function to invert the values of your array, allowing you to access them in reverse order:

    $accounts = Array(
      '@jonathansampson',
      '@f12devtools',
      '@ieanswers'
    );
    
    foreach ( array_reverse($accounts) as $account ) {
      echo sprintf("<li>%s</li>", $account);
    }
    

    Where do you include the jQuery library from? Google JSAPI? CDN?

    In addition to people who advices to host it on own server, I'd proposed to keep it on separate domain (e.g. static.website.com) to allow browsers to load it into separate from other content thread. This tip also works for all static stuff, say images and css.

    List all files from a directory recursively with Java

    This Function will probably list all the file name and its path from its directory and its subdirectories.

    public void listFile(String pathname) {
        File f = new File(pathname);
        File[] listfiles = f.listFiles();
        for (int i = 0; i < listfiles.length; i++) {
            if (listfiles[i].isDirectory()) {
                File[] internalFile = listfiles[i].listFiles();
                for (int j = 0; j < internalFile.length; j++) {
                    System.out.println(internalFile[j]);
                    if (internalFile[j].isDirectory()) {
                        String name = internalFile[j].getAbsolutePath();
                        listFile(name);
                    }
    
                }
            } else {
                System.out.println(listfiles[i]);
            }
    
        }
    
    }
    

    Python update a key in dict if it doesn't exist

    Use dict.setdefault():

    >>> d = {1: 'one'}
    >>> d.setdefault(1, '1')
    'one'
    >>> d    # d has not changed because the key already existed
    {1: 'one'}
    >>> d.setdefault(2, 'two')
    'two'
    >>> d
    {1: 'one', 2: 'two'}
    

    PHP check if date between two dates

    function get_format($df) {
    
        $str = '';
        $str .= ($df->invert == 1) ? ' - ' : '';
        if ($df->y > 0) {
            // years
            $str .= ($df->y > 1) ? $df->y . ' Years ' : $df->y . ' Year ';
        } if ($df->m > 0) {
            // month
            $str .= ($df->m > 1) ? $df->m . ' Months ' : $df->m . ' Month ';
        } if ($df->d > 0) {
            // days
            $str .= ($df->d > 1) ? $df->d . ' Days ' : $df->d . ' Day ';
        } 
    
        echo $str;
    }
    
    $yr=$year;
    $dates=$dor;
    $myyear='+'.$yr.' years';
    $new_date = date('Y-m-d', strtotime($myyear, strtotime($dates)));
    $date1 = new DateTime("$new_date");
    $date2 = new DateTime("now");
    $diff = $date2->diff($date1);
    

    401 Unauthorized: Access is denied due to invalid credentials

    I realize its an old question, but this came up in my searches. Had a similar issue for an MVC application recently built, deployed for the first time, and Authentication mechanism wasn't completely hashed out.

    It wasn't an IIS setting in my case, it was a Controller that was not [AllowAnonymous] decorated. I was using a Render.Action/Html.Action in a Layout.cshtml and the User was unauthenticated. So the Layout tried to load an Authenticated Action in an UnAuthenticated context.

    Once I updated the action to AllowAnonymous, the problem went away, and this is what led me to it.

    Hope this helps someone.

    Biggest differences of Thrift vs Protocol Buffers?

    I think most of these points have missed the basic fact that Thrift is an RPC framework, which happens to have the ability to serialize data using a variety of methods (binary, XML, etc).

    Protocol Buffers are designed purely for serialization, it's not a framework like Thrift.

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

    i don't see any for loop to initalize the variables.you can do something like this.

    for(i=0;i<50;i++){
     /* Code which is necessary with a simple if statement*/
    
       }
    

    Create a global variable in TypeScript

    Inside a .d.ts definition file

    type MyGlobalFunctionType = (name: string) => void
    

    If you work in the browser, you add members to the browser's window context:

    interface Window {
      myGlobalFunction: MyGlobalFunctionType
    }
    

    Same idea for NodeJS:

    declare module NodeJS {
      interface Global {
        myGlobalFunction: MyGlobalFunctionType
      }
    }
    

    Now you declare the root variable (that will actually live on window or global)

    declare const myGlobalFunction: MyGlobalFunctionType;
    

    Then in a regular .ts file, but imported as side-effect, you actually implement it:

    global/* or window */.myGlobalFunction = function (name: string) {
      console.log("Hey !", name);
    };
    

    And finally use it elsewhere in the codebase, with either:

    global/* or window */.myGlobalFunction("Kevin");
    
    myGlobalFunction("Kevin");
    

    Add a reference column migration in Rails 4

    Create a migration file

    rails generate migration add_references_to_uploads user:references
    

    Default foreign key name

    This would create a user_id column in uploads table as a foreign key

    class AddReferencesToUploads < ActiveRecord::Migration[5.2]
      def change
        add_reference :uploads, :user, foreign_key: true
      end
    end
    

    user model:

    class User < ApplicationRecord
      has_many :uploads
    end
    

    upload model:

    class Upload < ApplicationRecord
      belongs_to :user
    end
    

    Customize foreign key name:

    add_reference :uploads, :author, references: :user, foreign_key: true
    

    This would create an author_id column in the uploads tables as the foreign key.

    user model:

    class User < ApplicationRecord
      has_many :uploads, foreign_key: 'author_id'
    end
    

    upload model:

    class Upload < ApplicationRecord
      belongs_to :user
    end
    

    What is the difference between hg forget and hg remove?

    If you use "hg remove b" against a file with "A" status, which means it has been added but not commited, Mercurial will respond:

      not removing b: file has been marked for add (use forget to undo)
    

    This response is a very clear explication of the difference between remove and forget.

    My understanding is that "hg forget" is for undoing an added but not committed file so that it is not tracked by version control; while "hg remove" is for taking out a committed file from version control.

    This thread has a example for using hg remove against files of 7 different types of status.

    jQuery onclick event for <li> tags

    In your question it seems that you have span selector with given to every span a seperate class into ul li option and then you have many answers, i.e.

    $(document).ready(function()
     {
       $('ul.art-vmenu li').click(function(e) 
        { 
         alert($(this).find("span.t").text());
       });
    });
    

    But you need not to use ul.art-vmenu li rather you can use direct ul with the use of on as used in below example :

    $(document).ready(function()
     {
      $("ul.art-vmenu").on("click","li", function(){
         alert($(this).find("span.t").text());
      });
    });
    

    Differences between .NET 4.0 and .NET 4.5 in High level in .NET

    Here is a great resource from Microsoft which includes a high level features overview for each .NET release since 1.0 up to the present day. It also include information about the associated Visual Studio release and Windows version compatibility.

    .NET Framework Versions and Dependencies

    How to use the COLLATE in a JOIN in SQL Server?

    As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server

    SELECT *
      FROM [FAEB].[dbo].[ExportaComisiones] AS f
      JOIN [zCredifiel].[dbo].[optPerson] AS p
      ON (p.vTreasuryId = f.RFC) COLLATE Database_Default 
    

    Split string in Lua?

    Just as string.gmatch will find patterns in a string, this function will find the things between patterns:

    function string:split(pat)
      pat = pat or '%s+'
      local st, g = 1, self:gmatch("()("..pat..")")
      local function getter(segs, seps, sep, cap1, ...)
        st = sep and seps + #sep
        return self:sub(segs, (seps or 0) - 1), cap1 or sep, ...
      end
      return function() if st then return getter(st, g()) end end
    end
    

    By default it returns whatever is separated by whitespace.

    angular2 manually firing click event on particular element

    To get the native reference to something like an ion-input, ry using this

    @ViewChild('fileInput', { read: ElementRef }) fileInput: ElementRef;
    

    and then

    this.fileInput.nativeElement.querySelector('input').click()
    

    Find unique lines

    You could also print out the unique value in "file" using the cat command by piping to sort and uniq

    cat file | sort | uniq -u

    Angular - How to apply [ngStyle] conditions

    For a single style attribute, you can use the following syntax:

    <div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">
    

    I assumed that the background color should not be set if neither style1 nor style2 is true.


    Since the question title mentions ngStyle, here is the equivalent syntax with that directive:

    <div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">
    

    T-SQL: Deleting all duplicate rows but keeping one

    Example query:

    DELETE FROM Table
    WHERE ID NOT IN
    (
    SELECT MIN(ID)
    FROM Table
    GROUP BY Field1, Field2, Field3, ...
    )
    

    Here fields are column on which you want to group the duplicate rows.

    How to get names of classes inside a jar file?

    This is a hack I'm using:

    You can use java's autocomplete like this:

    java -cp path_to.jar <Tab>
    

    This will give you a list of classes available to pass as the starting class. Of course, trying to use one that has no main file will not do anything, but you can see what java thinks the classes inside the .jar are called.

    How to set a variable to be "Today's" date in Python/Pandas

    If you want a string mm/dd/yyyy instead of the datetime object, you can use strftime (string format time):

    >>> dt.datetime.today().strftime("%m/%d/%Y")
                       # ^ note parentheses
    '02/12/2014'
    

    How to make an element width: 100% minus padding?

    Use css calc()

    Super simple and awesome.

    input {
        width: -moz-calc(100% - 15px);
        width: -webkit-calc(100% - 15px);
        width: calc(100% - 15px);
    }?
    

    As seen here: Div width 100% minus fixed amount of pixels
    By webvitaly (https://stackoverflow.com/users/713523/webvitaly)
    Original source: http://web-profile.com.ua/css/dev/css-width-100prc-minus-100px/

    Just copied this over here, because I almost missed it in the other thread.

    How can I use if/else in a dictionary comprehension?

    You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

    { (some_key if condition else default_key):(something_if_true if condition
              else something_if_false) for key, value in dict_.items() }
    

    The final if clause acts as a filter, which is different from having the conditional expression.


    Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

    How do I run a program with a different working directory from current, from Linux shell?

    Just change the last "&&" into ";" and it will cd back no matter if the command fails or succeeds:

    cd SOME_PATH && run_some_command ; cd -
    

    How to change default text color using custom theme?

    When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.

    styles.xml:

    <resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
        <item name="android:editTextColor">#295055</item> 
        <item name="android:textColorPrimary">#295055</item>
        <item name="android:textColorSecondary">#295055</item>
        <item name="android:textColorTertiary">#295055</item>
        <item name="android:textColorPrimaryInverse">#295055</item>
        <item name="android:textColorSecondaryInverse">#295055</item>
        <item name="android:textColorTertiaryInverse">#295055</item>
    
         <item name="android:windowBackground">@drawable/custom_background</item>        
    </style>
    
    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>
    

    parent="@android:style/Theme.Light" is Google’s native colors. Here is a reference of what the native styles are: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml

    The default Android style is also called “Theme”. So you calling it Theme probably confused the program.

    name="Theme.AppBaseTheme" means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light". This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">

    @drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.

    #295055 is a dark blue color.

    My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).

    Then in Android Manifest, remember to include the code:

    <application
    android:theme="@style/Theme.AppBaseTheme">
    

    Download Excel file via AJAX MVC

    On Submit form

    public ActionResult ExportXls()
    {   
     var filePath="";
      CommonHelper.WriteXls(filePath, "Text.xls");
    }
    
     public static void WriteXls(string filePath, string targetFileName)
        {
            if (!String.IsNullOrEmpty(filePath))
            {
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.Charset = "utf-8";
                response.ContentType = "text/xls";
                response.AddHeader("content-disposition", string.Format("attachment; filename={0}", targetFileName));
                response.BinaryWrite(File.ReadAllBytes(filePath));
                response.End();
            }
        }
    

    Get image data url in JavaScript?

    Coming long after, but none of the answers here are entirely correct.

    When drawn on a canvas, the passed image is uncompressed + all pre-multiplied.
    When exported, its uncompressed or recompressed with a different algorithm, and un-multiplied.

    All browsers and devices will have different rounding errors happening in this process
    (see Canvas fingerprinting).

    So if one wants a base64 version of an image file, they have to request it again (most of the time it will come from cache) but this time as a Blob.

    Then you can use a FileReader to read it either as an ArrayBuffer, or as a dataURL.

    _x000D_
    _x000D_
    function toDataURL(url, callback){_x000D_
        var xhr = new XMLHttpRequest();_x000D_
        xhr.open('get', url);_x000D_
        xhr.responseType = 'blob';_x000D_
        xhr.onload = function(){_x000D_
          var fr = new FileReader();_x000D_
        _x000D_
          fr.onload = function(){_x000D_
            callback(this.result);_x000D_
          };_x000D_
        _x000D_
          fr.readAsDataURL(xhr.response); // async call_x000D_
        };_x000D_
        _x000D_
        xhr.send();_x000D_
    }_x000D_
    _x000D_
    toDataURL(myImage.src, function(dataURL){_x000D_
      result.src = dataURL;_x000D_
    _x000D_
      // now just to show that passing to a canvas doesn't hold the same results_x000D_
      var canvas = document.createElement('canvas');_x000D_
      canvas.width = myImage.naturalWidth;_x000D_
      canvas.height = myImage.naturalHeight;_x000D_
      canvas.getContext('2d').drawImage(myImage, 0,0);_x000D_
    _x000D_
      console.log(canvas.toDataURL() === dataURL); // false - not same data_x000D_
      });
    _x000D_
    <img id="myImage" src="https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png" crossOrigin="anonymous">_x000D_
    <img id="result">
    _x000D_
    _x000D_
    _x000D_

    Difference between JSONObject and JSONArray

    I always use object, it is more easily extendable, JSON array is not. For example you originally had some data as a json array, then you needed to add a status header on it you'd be a bit stuck, unless you'd nested the data in an object. The only disadvantage is a slight increase in complexity of creation / parsing.

    So instead of

    [datum0, datum1, datumN]
    

    You'd have

    {data: [datum0, datum1, datumN]}
    

    then later you can add more...

    {status: "foo", data: [datum0, datum1, datumN]}
    

    How do I temporarily disable triggers in PostgreSQL?

    You can also disable triggers in pgAdmin (III):

    1. Find your table
    2. Expand the +
    3. Find your trigger in Triggers
    4. Right-click, uncheck "Trigger Enabled?"

    Access images inside public folder in laravel

    You simply need to use the asset helper function in Laravel. (The url helper can also be used in this manner)

    <img src="{{ asset('images/arrow.gif') }}" />
    

    For the absolute path, you use public_path instead.

    <p>Absolute path: {{ public_path('images/arrow.gif') }}</p>
    

    If you are providing the URL to a public image from a controller (backend) you can use asset as well, or secure_asset if you want HTTPS. eg:

    $url = asset('images/arrow.gif'); # http://example.com/assets/images/arrow.gif
    $secure_url = secure_asset('images/arrow.gif'); # https://example.com/assets/images/arrow.gif
    
    return $secure_url;
    

    Lastly, if you want to go directly to the image on a given route you can redirect to it:

    return \Redirect::to($secure_url);
    

    More Laravel helper functions can be found here

    How to pass object with NSNotificationCenter

    Swift 5.1 Custom Object/Type

    // MARK: - NotificationName
    // Extending notification name to avoid string errors.
    extension Notification.Name {
        static let yourNotificationName = Notification.Name("yourNotificationName")
    }
    
    
    // MARK: - CustomObject
    class YourCustomObject {
        // Any stuffs you would like to set in your custom object as always.
        init() {}
    }
    
    // MARK: - Notification Sender Class
    class NotificatioSenderClass {
    
         // Just grab the content of this function and put it to your function responsible for triggering a notification.
        func postNotification(){
            // Note: - This is the important part pass your object instance as object parameter.
            let yourObjectInstance = YourCustomObject()
            NotificationCenter.default.post(name: .yourNotificationName, object: yourObjectInstance)
        }
    }
    
    // MARK: -Notification  Receiver class
    class NotificationReceiverClass: UIViewController {
        // MARK: - ViewController Lifecycle
        override func viewDidLoad() {
            super.viewDidLoad()
            // Register your notification listener
            NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNotificationWithCustomObject), name: .yourNotificationName, object: nil)
        }
    
        // MARK: - Helpers
        @objc private func didReceiveNotificationWithCustomObject(notification: Notification){
            // Important: - Grab your custom object here by casting the notification object.
            guard let yourPassedObject = notification.object as? YourCustomObject else {return}
            // That's it now you can use your custom object
            //
            //
    
        }
          // MARK: - Deinit
      deinit {
          // Save your memory by releasing notification listener
          NotificationCenter.default.removeObserver(self, name: .yourNotificationName, object: nil)
        }
    
    
    
    
    }
    
    

    Running the new Intel emulator for Android

    Here there are two issues we have to concentrate on:

    1. HAX device failed to open,

      For this problem, you have to run the HAX device setup file from the HAX addon folder. Follow Speed Up Android Emulator to know clearly how.

    2. If you created the AVD through AVD manager then you can change the RAM size in AVD Manager and device edit option.

    If you created the AVD through command line, then you should start the AVD from command line will work,

    emulator -memory 512 -avd gtv_avd
    

    Compare two date formats in javascript/jquery

    As in your example, the fit_start_time is not later than the fit_end_time.

    Try it the other way round:

    var fit_start_time  = $("#fit_start_time").val(); //2013-09-5
    var fit_end_time    = $("#fit_end_time").val(); //2013-09-10
    
    if(Date.parse(fit_start_time) <= Date.parse(fit_end_time)){
        alert("Please select a different End Date.");
    }
    

    Update

    Your code implies that you want to see the alert with the current variables you have. If this is the case then the above code is correct. If you're intention (as per the implication of the alert message) is to make sure their fit_start_time variable is a date that is before the fit_end_time, then your original code is fine, but the data you're getting from the jQuery .val() methods is not parsing correctly. It would help if you gave us the actual HTML which the selector is sniffing at.

    How to get index using LINQ?

    myCars.Select((v, i) => new {car = v, index = i}).First(myCondition).index;
    

    or the slightly shorter

    myCars.Select((car, index) => new {car, index}).First(myCondition).index;
    

    Class is not abstract and does not override abstract method

    Both classes Rectangle and Ellipse need to override both of the abstract methods.

    To work around this, you have 3 options:

    • Add the two methods
    • Make each class that extends Shape abstract
    • Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:

      abstract class Shape {
          // ...
          void draw(Graphics g);
      }
      

    And

        class Rectangle extends Shape {
            void draw(Graphics g) {
                // ...
            }
        }
    

    Finally

        class Ellipse extends Shape {
            void draw(Graphics g) {
                // ...
            }
        }
    

    And you can switch in between them, like so:

        Shape shape = new Ellipse();
        shape.draw(/* ... */);
    
        shape = new Rectangle();
        shape.draw(/* ... */);
    

    Again, just an example.

    Using a dictionary to select function to execute

    This will call methods from dictionary

    This is python switch statement with function calling

    Create few modules as per the your requirement. If want to pass arguments then pass.

    Create a dictionary, which will call these modules as per requirement.

        def function_1(arg):
            print("In function_1")
    
        def function_2(arg):
            print("In function_2")
    
        def function_3(fileName):
            print("In function_3")
            f_title,f_course1,f_course2 = fileName.split('_')
            return(f_title,f_course1,f_course2)
    
    
        def createDictionary():
    
            dict = {
    
                1 : function_1,
                2 : function_2,
                3 : function_3,
    
            }    
            return dict
    
        dictionary = createDictionary()
        dictionary[3](Argument)#pass any key value to call the method
    

    How to get ° character in a string in python?

    just use \xb0 (in a string); python will convert it automatically

    How exactly does __attribute__((constructor)) work?

    Here is a "concrete" (and possibly useful) example of how, why, and when to use these handy, yet unsightly constructs...

    Xcode uses a "global" "user default" to decide which XCTestObserver class spews it's heart out to the beleaguered console.

    In this example... when I implicitly load this psuedo-library, let's call it... libdemure.a, via a flag in my test target á la..

    OTHER_LDFLAGS = -ldemure
    

    I want to..

    1. At load (ie. when XCTest loads my test bundle), override the "default" XCTest "observer" class... (via the constructor function) PS: As far as I can tell.. anything done here could be done with equivalent effect inside my class' + (void) load { ... } method.

    2. run my tests.... in this case, with less inane verbosity in the logs (implementation upon request)

    3. Return the "global" XCTestObserver class to it's pristine state.. so as not to foul up other XCTest runs which haven't gotten on the bandwagon (aka. linked to libdemure.a). I guess this historically was done in dealloc.. but I'm not about to start messing with that old hag.

    So...

    #define USER_DEFS NSUserDefaults.standardUserDefaults
    
    @interface      DemureTestObserver : XCTestObserver @end
    @implementation DemureTestObserver
    
    __attribute__((constructor)) static void hijack_observer() {
    
    /*! here I totally hijack the default logging, but you CAN
        use multiple observers, just CSV them, 
        i.e. "@"DemureTestObserverm,XCTestLog"
    */
      [USER_DEFS setObject:@"DemureTestObserver" 
                    forKey:@"XCTestObserverClass"];
      [USER_DEFS synchronize];
    }
    
    __attribute__((destructor)) static void reset_observer()  {
    
      // Clean up, and it's as if we had never been here.
      [USER_DEFS setObject:@"XCTestLog" 
                    forKey:@"XCTestObserverClass"];
      [USER_DEFS synchronize];
    }
    
    ...
    @end
    

    Without the linker flag... (Fashion-police swarm Cupertino demanding retribution, yet Apple's default prevails, as is desired, here)

    enter image description here

    WITH the -ldemure.a linker flag... (Comprehensible results, gasp... "thanks constructor/destructor"... Crowd cheers) enter image description here

    Rounded corner for textview in android

    1. Right Click on Drawable Folder and Create new File
    2. Name the file according to you and add the extension as .xml.
    3. Add the following code in the file
      <?xml version="1.0" encoding="utf-8"?>
      <shape xmlns:android="http://schemas.android.com/apk/res/android"
          android:shape="rectangle">
          <corners android:radius="5dp" />
          <stroke android:width="1dp"  />
          <solid android:color="#1e90ff" />
      </shape>
    
    1. Add the line where you want the rounded edge android:background="@drawable/corner"

    How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

    This is more an update (for Symfony v:2.7+ and JmsSerializer v:0.13.*@dev), so to avoid that Jms tries to load and serialise the whole object graph ( or in case of cyclic relation ..)

    Model:

    use Doctrine\ORM\Mapping as ORM;
    use JMS\Serializer\Annotation\ExclusionPolicy;  
    use JMS\Serializer\Annotation\Exclude;  
    use JMS\Serializer\Annotation\MaxDepth; /* <=== Required */
    /**
     * User
     *
     * @ORM\Table(name="user_table")
    ///////////////// OTHER Doctrine proprieties //////////////
     */
     public class User
    {
        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected   $id;
    
        /**
         * @ORM\ManyToOne(targetEntity="FooBundle\Entity\Game")
         * @ORM\JoinColumn(nullable=false)
         * @MaxDepth(1)
         */
        protected $game;
       /*
          Other proprieties ....and Getters ans setters
          ......................
          ......................
       */
    

    Inside an Action:

    use JMS\Serializer\SerializationContext;
      /* Necessary include to enbale max depth */
    
      $users = $this
                  ->getDoctrine()
                  ->getManager()
                  ->getRepository("FooBundle:User")
                  ->findAll();
    
      $serializer = $this->container->get('jms_serializer');
      $jsonContent = $serializer
                       ->serialize(
                            $users, 
                            'json', 
                            SerializationContext::create()
                                     ->enableMaxDepthChecks()
                      );
    
      return new Response($jsonContent);
    

    "A namespace cannot directly contain members such as fields or methods"

    The snippet you're showing doesn't seem to be directly responsible for the error.

    This is how you can CAUSE the error:

    namespace MyNameSpace
    {
       int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
    
       class MyClass
       {
          ...
       }
    }
    

    If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

    Get event listeners attached to node using addEventListener

    You can't.

    The only way to get a list of all event listeners attached to a node is to intercept the listener attachment call.

    DOM4 addEventListener

    Says

    Append an event listener to the associated list of event listeners with type set to type, listener set to listener, and capture set to capture, unless there already is an event listener in that list with the same type, listener, and capture.

    Meaning that an event listener is added to the "list of event listeners". That's all. There is no notion of what this list should be nor how you should access it.