Programs & Examples On #Extension objects

Sending GET request with Authentication headers using restTemplate

Here's a super-simple example with basic authentication, headers, and exception handling...

private HttpHeaders createHttpHeaders(String user, String password)
{
    String notEncoded = user + ":" + password;
    String encodedAuth = "Basic " + Base64.getEncoder().encodeToString(notEncoded.getBytes());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", encodedAuth);
    return headers;
}

private void doYourThing() 
{
    String theUrl = "http://blah.blah.com:8080/rest/api/blah";
    RestTemplate restTemplate = new RestTemplate();
    try {
        HttpHeaders headers = createHttpHeaders("fred","1234");
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
        System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
    }
    catch (Exception eek) {
        System.out.println("** Exception: "+ eek.getMessage());
    }
}

how to get domain name from URL

#!/usr/bin/perl -w
use strict;

my $url = $ARGV[0];
if($url =~ /([^:]*:\/\/)?([^\/]*\.)*([^\/\.]+)\.[^\/]+/g) {
  print $3;
}

error: Your local changes to the following files would be overwritten by checkout

i had got the same error. Actually i tried to override the flutter Old SDK Package with new Updated Package. so that error occurred.

i opened flutter sdk directory with VS Code and cleaned the project

use this code in VSCode cmd

git clean -dxf

then use git pull

Adding default parameter value with type hint in Python

Your second way is correct.

def foo(opts: dict = {}):
    pass

print(foo.__annotations__)

this outputs

{'opts': <class 'dict'>}

It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.

I strongly advise against using mutable keyword arguments. More information here.

How do I use CMake?

CMake takes a CMakeList file, and outputs it to a platform-specific build format, e.g. a Makefile, Visual Studio, etc.

You run CMake on the CMakeList first. If you're on Visual Studio, you can then load the output project/solution.

How to put a tooltip on a user-defined function

Not a tooltip solution but an adequate workaround:

Start typing the UDF =MyUDF( then press CTRL + Shift + A and your function parameters will be displayed. So long as those parameters have meaningful names you at-least have a viable prompt

For example, this:

=MyUDF( + CTRL + Shift + A

Turns into this:

=MyUDF(sPath, sFileName)

Permutation of array

Implementation via recursion (dynamic programming), in Java, with test case (TestNG).


Code

PrintPermutation.java

import java.util.Arrays;

/**
 * Print permutation of n elements.
 * 
 * @author eric
 * @date Oct 13, 2018 12:28:10 PM
 */
public class PrintPermutation {
    /**
     * Print permutation of array elements.
     * 
     * @param arr
     * @return count of permutation,
     */
    public static int permutation(int arr[]) {
        return permutation(arr, 0);
    }

    /**
     * Print permutation of part of array elements.
     * 
     * @param arr
     * @param n
     *            start index in array,
     * @return count of permutation,
     */
    private static int permutation(int arr[], int n) {
        int counter = 0;
        for (int i = n; i < arr.length; i++) {
            swapArrEle(arr, i, n);
            counter += permutation(arr, n + 1);
            swapArrEle(arr, n, i);
        }
        if (n == arr.length - 1) {
            counter++;
            System.out.println(Arrays.toString(arr));
        }

        return counter;
    }

    /**
     * swap 2 elements in array,
     * 
     * @param arr
     * @param i
     * @param k
     */
    private static void swapArrEle(int arr[], int i, int k) {
        int tmp = arr[i];
        arr[i] = arr[k];
        arr[k] = tmp;
    }
}

PrintPermutationTest.java (test case via TestNG)

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * PrintPermutation test.
 * 
 * @author eric
 * @date Oct 14, 2018 3:02:23 AM
 */
public class PrintPermutationTest {
    @Test
    public void test() {
        int arr[] = new int[] { 0, 1, 2, 3 };
        Assert.assertEquals(PrintPermutation.permutation(arr), 24);

        int arrSingle[] = new int[] { 0 };
        Assert.assertEquals(PrintPermutation.permutation(arrSingle), 1);

        int arrEmpty[] = new int[] {};
        Assert.assertEquals(PrintPermutation.permutation(arrEmpty), 0);
    }
}

Gradle to execute Java class (without modifying build.gradle)

You just need to use the Gradle Application plugin:

apply plugin:'application'
mainClassName = "org.gradle.sample.Main"

And then simply gradle run.

As Teresa points out, you can also configure mainClassName as a system property and run with a command line argument.

What is the size limit of a post request?

By default, the post request has maximum size of 8mb. But you can modify it according to your requirements. The modification can be done by opening php.ini file (php configuration setting).

Find

post_max_size=8M  //for me, that was on line:771

replace 8 according to your requirements.

svn cleanup: sqlite: database disk image is malformed

Have you seen this post on the subversion site? You could also potentially try validating and "fixing" the database directly as described here. (Note that I'm no expert, I just did a quick google search. May not be related to your issues at all).

Personally, I'd try checking out the repo again and reapplying your changes. Not sure if this is possible though in your case?

Get GMT Time in Java

After java 8, you may want to get the formatted time as below:

DateTimeFormatter.ofPattern("HH:mm:ss.SSS").format(LocalTime.now(ZoneId.of("GMT")));

How to secure RESTful web services?

There's another, very secure method. It's client certificates. Know how servers present an SSL Cert when you contact them on https? Well servers can request a cert from a client so they know the client is who they say they are. Clients generate certs and give them to you over a secure channel (like coming into your office with a USB key - preferably a non-trojaned USB key).

You load the public key of the cert client certificates (and their signer's certificate(s), if necessary) into your web server, and the web server won't accept connections from anyone except the people who have the corresponding private keys for the certs it knows about. It runs on the HTTPS layer, so you may even be able to completely skip application-level authentication like OAuth (depending on your requirements). You can abstract a layer away and create a local Certificate Authority and sign Cert Requests from clients, allowing you to skip the 'make them come into the office' and 'load certs onto the server' steps.

Pain the neck? Absolutely. Good for everything? Nope. Very secure? Yup.

It does rely on clients keeping their certificates safe however (they can't post their private keys online), and it's usually used when you sell a service to clients rather then letting anyone register and connect.

Anyway, it may not be the solution you're looking for (it probably isn't to be honest), but it's another option.

XPath to select Element by attribute value

Try doing this :

/Employees/Employee[@id=4]/*/text()

echo key and value of an array without and with loop

How to echo key and value of an array without and with loop

$keys = array_keys($page);
implode(',',$keys);
echo $keys[0].' is at '.$page['Home'];

How to make CREATE OR REPLACE VIEW work in SQL Server?

SQL Server 2016 Answer

With SQL Server 2016 you can now do (MSDN Source):

DROP VIEW IF EXISTS dbo.MyView

regular expression for anything but an empty string

What about?

/.*\S.*/

This means

/ = delimiter
.* = zero or more of anything but newline
\S = anything except a whitespace (newline, tab, space)

so you get
match anything but newline + something not whitespace + anything but newline

How do I convert a String to an InputStream in Java?

There are two ways we can convert String to InputStream in Java,

  1. Using ByteArrayInputStream

Example :-

String str = "String contents";
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
  1. Using Apache Commons IO

Example:-

String str = "String contents"
InputStream is = IOUtils.toInputStream(str, StandardCharsets.UTF_8);

How to sum a variable by group

Since dplyr 1.0.0, the across() function could be used:

df %>%
 group_by(Category) %>%
 summarise(across(Frequency, sum))

  Category Frequency
  <chr>        <int>
1 First           30
2 Second           5
3 Third           34

If interested in multiple variables:

df %>%
 group_by(Category) %>%
 summarise(across(c(Frequency, Frequency2), sum))

  Category Frequency Frequency2
  <chr>        <int>      <int>
1 First           30         55
2 Second           5         29
3 Third           34        190

And the selection of variables using select helpers:

df %>%
 group_by(Category) %>%
 summarise(across(starts_with("Freq"), sum))

  Category Frequency Frequency2 Frequency3
  <chr>        <int>      <int>      <dbl>
1 First           30         55        110
2 Second           5         29         58
3 Third           34        190        380

Sample data:

df <- read.table(text = "Category Frequency Frequency2 Frequency3
                 1    First        10         10         20
                 2    First        15         30         60
                 3    First         5         15         30
                 4   Second         2          8         16
                 5    Third        14         70        140
                 6    Third        20        120        240
                 7   Second         3         21         42",
                 header = TRUE,
                 stringsAsFactors = FALSE)

UILabel - auto-size label to fit text?

This is not as complicated as some of the other answers make it.

enter image description here

Pin the left and top edges

Just use auto layout to add constraints to pin the left and top sides of the label.

enter image description here

After that it will automatically resize.

Notes

  • Don't add constraints for the width and height. Labels have an intrinsic size based on their text content.
  • Thanks to this answer for help with this.
  • No need to set sizeToFit when using auto layout. My complete code for the example project is here:

    import UIKit
    class ViewController: UIViewController {
    
        @IBOutlet weak var myLabel: UILabel!
    
        @IBAction func changeTextButtonTapped(sender: UIButton) {
            myLabel.text = "my name is really long i want it to fit in this box"
        }
    }
    
  • If you want your label to line wrap then set the number of lines to 0 in IB and add myLabel.preferredMaxLayoutWidth = 150 // or whatever in code. (I also pinned my button to the bottom of the label so that it would move down when the label height increased.)

enter image description here

  • If you are looking for dynamically sizing labels inside a UITableViewCell then see this answer.

enter image description here

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

Android ADB devices unauthorized

This worked for me:

rm ~/.android/adbkey.pub

sudo ./adb kill-server

sudo ./adb start-server

sudo ./adb -s emulator-5554 install ~/apk_to_install.apk

I'm not sure if is a good idea run adb with sudo privileges,but it was the only way I get it works. Regards.

Dynamic constant assignment

Your problem is that each time you run the method you are assigning a new value to the constant. This is not allowed, as it makes the constant non-constant; even though the contents of the string are the same (for the moment, anyhow), the actual string object itself is different each time the method is called. For example:

def foo
  p "bar".object_id
end

foo #=> 15779172
foo #=> 15779112

Perhaps if you explained your use case—why you want to change the value of a constant in a method—we could help you with a better implementation.

Perhaps you'd rather have an instance variable on the class?

class MyClass
  class << self
    attr_accessor :my_constant
  end
  def my_method
    self.class.my_constant = "blah"
  end
end

p MyClass.my_constant #=> nil
MyClass.new.my_method

p MyClass.my_constant #=> "blah"

If you really want to change the value of a constant in a method, and your constant is a String or an Array, you can 'cheat' and use the #replace method to cause the object to take on a new value without actually changing the object:

class MyClass
  BAR = "blah"

  def cheat(new_bar)
    BAR.replace new_bar
  end
end

p MyClass::BAR           #=> "blah"
MyClass.new.cheat "whee"
p MyClass::BAR           #=> "whee"

How to change the default background color white to something else in twitter bootstrap

You can overwrite Bootstraps default CSS by adding your own rules.

<style type="text/css">
   body { background: navy !important; } /* Adding !important forces the browser to overwrite the default style applied by Bootstrap */
</style>

How to delete a row from GridView?

Please try this code.....

DataRow dr = dtPrf_Mstr.NewRow();
dtPrf_Mstr.Rows.Add(dr);
GVGLCode.DataSource = dtPrf_Mstr;
GVGLCode.DataBind();
int iCount = GVGLCode.Rows.Count;
for (int i = 0; i < iCount; i++)
{
   GVGLCode.Rows.Remove(GVGLCode.Rows[i]);
}
GVGLCode.DataBind();

How to close an iframe within iframe itself

Use this to remove iframe from parent within iframe itself

frameElement.parentNode.removeChild(frameElement)

It works with same origin only(not allowed with cross origin)

How to reload page every 5 seconds?

A decent alternative if you're using firefox is the XRefresh plugin. It will reload your page everytime it detect the file has been modified. So rather than just refreshing every 5 seconds, it will just refresh when you hit save in your HTML editor.

Express-js wildcard routing to cover everything under and including a path

It is not necessary to have two routes.

Simply add (/*)? at the end of your path string.

For example, app.get('/hello/world(/*)?' /* ... */)

Here is a fully working example, feel free to copy and paste this into a .js file to run with node, and play with it in a browser (or curl):

const app = require('express')()

// will be able to match all of the following
const test1 = 'http://localhost:3000/hello/world'
const test2 = 'http://localhost:3000/hello/world/'
const test3 = 'http://localhost:3000/hello/world/with/more/stuff'

// but fail at this one
const failTest = 'http://localhost:3000/foo/world'

app.get('/hello/world(/*)?', (req, res) => res.send(`
    This will match at example endpoints: <br><br>
    <pre><a href="${test1}">${test1}</a></pre>
    <pre><a href="${test2}">${test2}</a></pre>
    <pre><a href="${test3}">${test3}</a></pre>

    <br><br> Will NOT match at: <pre><a href="${failTest}">${failTest}</a></pre>
`))

app.listen(3000, () => console.log('Check this out in a browser at http://localhost:3000/hello/world!'))

Arduino error: does not name a type?

Don't know it this is your problem but it was mine.

Void setup() does not name a type

BUT

void setup() is ok.

I found that the sketch I copied for another project was full of 'wrong case' letters. Onc efixed, it ran smoothly.emphasized text

Real mouse position in canvas

The Simple 1:1 Scenario

For situations where the canvas element is 1:1 compared to the bitmap size, you can get the mouse positions by using this snippet:

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
}

Just call it from your event with the event and canvas as arguments. It returns an object with x and y for the mouse positions.

As the mouse position you are getting is relative to the client window you'll have to subtract the position of the canvas element to convert it relative to the element itself.

Example of integration in your code:

//put this outside the event loop..
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");

function draw(evt) {
    var pos = getMousePos(canvas, evt);

    context.fillStyle = "#000000";
    context.fillRect (pos.x, pos.y, 4, 4);
}

Note: borders and padding will affect position if applied directly to the canvas element so these needs to be considered via getComputedStyle() - or apply those styles to a parent div instead.

When Element and Bitmap are of different sizes

When there is the situation of having the element at a different size than the bitmap itself, for example, the element is scaled using CSS or there is pixel-aspect ratio etc. you will have to address this.

Example:

function  getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect(), // abs. size of element
      scaleX = canvas.width / rect.width,    // relationship bitmap vs. element for X
      scaleY = canvas.height / rect.height;  // relationship bitmap vs. element for Y

  return {
    x: (evt.clientX - rect.left) * scaleX,   // scale mouse coordinates after they have
    y: (evt.clientY - rect.top) * scaleY     // been adjusted to be relative to element
  }
}

With transformations applied to context (scale, rotation etc.)

Then there is the more complicated case where you have applied transformation to the context such as rotation, skew/shear, scale, translate etc. To deal with this you can calculate the inverse matrix of the current matrix.

Newer browsers let you read the current matrix via the currentTransform property and Firefox (current alpha) even provide a inverted matrix through the mozCurrentTransformInverted. Firefox however, via mozCurrentTransform, will return an Array and not DOMMatrix as it should. Neither Chrome, when enabled via experimental flags, will return a DOMMatrix but a SVGMatrix.

In most cases however you will have to implement a custom matrix solution of your own (such as my own solution here - free/MIT project) until this get full support.

When you eventually have obtained the matrix regardless of path you take to obtain one, you'll need to invert it and apply it to your mouse coordinates. The coordinates are then passed to the canvas which will use its matrix to convert it to back wherever it is at the moment.

This way the point will be in the correct position relative to the mouse. Also here you need to adjust the coordinates (before applying the inverse matrix to them) to be relative to the element.

An example just showing the matrix steps

function draw(evt) {
    var pos = getMousePos(canvas, evt);        // get adjusted coordinates as above
    var imatrix = matrix.inverse();            // get inverted matrix somehow
    pos = imatrix.applyToPoint(pos.x, pos.y);  // apply to adjusted coordinate

    context.fillStyle = "#000000";
    context.fillRect(pos.x-1, pos.y-1, 2, 2);
}

An example of using currentTransform when implemented would be:

    var pos = getMousePos(canvas, e);          // get adjusted coordinates as above
    var matrix = ctx.currentTransform;         // W3C (future)
    var imatrix = matrix.invertSelf();         // invert

    // apply to point:
    var x = pos.x * imatrix.a + pos.y * imatrix.c + imatrix.e;
    var y = pos.x * imatrix.b + pos.y * imatrix.d + imatrix.f;

Update I made a free solution (MIT) to embed all these steps into a single easy-to-use object that can be found here and also takes care of a few other nitty-gritty things most ignore.

How to increase buffer size in Oracle SQL Developer to view all records?

https://forums.oracle.com/forums/thread.jspa?threadID=447344

The pertinent section reads:

There's no setting to fetch all records. You wouldn't like SQL Developer to fetch for minutes on big tables anyway. If, for 1 specific table, you want to fetch all records, you can do Control-End in the results pane to go to the last record. You could time the fetching time yourself, but that will vary on the network speed and congestion, the program (SQL*Plus will be quicker than SQL Dev because it's more simple), etc.

There is also a button on the toolbar which is a "Fetch All" button.

FWIW Be careful retrieving all records, for a very large recordset it could cause you to have all sorts of memory issues etc.

As far as I know, SQL Developer uses JDBC behind the scenes to fetch the records and the limit is set by the JDBC setMaxRows() procedure, if you could alter this (it would prob be unsupported) then you might be able to change the SQL Developer behaviour.

Reset Excel to default borders

If you have applied border and/or fill on a cell, you need to clear both to go back to the default borders.

You may apply 'None' as the border option and expect the default borders to show, but it will not when the cell fill is white. It's not immediately obvious that it has a white fill, as unfilled cells are also white.

In this case, apply a 'No Fill' on the cells, and you will get the default borders back.

Screenshot of Excel indicating locations of No Border and No Fill options

That's it. No messy format painting, no 'Clear Formats', none of those destructive methods. Easy, quick and painless.

How to find the lowest common ancestor of two nodes in any binary tree?

Here is the C++ way of doing it. Have tried to keep the algorithm as much easy as possible to understand:

// Assuming that `BinaryNode_t` has `getData()`, `getLeft()` and `getRight()`
class LowestCommonAncestor
{
  typedef char type;    
  // Data members which would behave as place holders
  const BinaryNode_t* m_pLCA;
  type m_Node1, m_Node2;

  static const unsigned int TOTAL_NODES = 2;

  // The core function which actually finds the LCA; It returns the number of nodes found
  // At any point of time if the number of nodes found are 2, then it updates the `m_pLCA` and once updated, we have found it!
  unsigned int Search (const BinaryNode_t* const pNode)
  {
    if(pNode == 0)
      return 0;

    unsigned int found = 0;

    found += (pNode->getData() == m_Node1);
    found += (pNode->getData() == m_Node2);

    found += Search(pNode->getLeft()); // below condition can be after this as well
    found += Search(pNode->getRight());

    if(found == TOTAL_NODES && m_pLCA == 0)
      m_pLCA = pNode;  // found !

    return found;
  }

public:
  // Interface method which will be called externally by the client
  const BinaryNode_t* Search (const BinaryNode_t* const pHead,
                              const type node1,
                              const type node2)
  {
    // Initialize the data members of the class
    m_Node1 = node1;
    m_Node2 = node2;
    m_pLCA = 0;

    // Find the LCA, populate to `m_pLCANode` and return
    (void) Search(pHead);
    return m_pLCA;
  }
};

How to use it:

LowestCommonAncestor lca;
BinaryNode_t* pNode = lca.Search(pWhateverBinaryTreeNodeToBeginWith);
if(pNode != 0)
  ...

How do you return the column names of a table?

CREATE PROCEDURE [dbo].[Usp_GetColumnName]      
        @TableName varchar(50)
AS
BEGIN   
    BEGIN
        SET NOCOUNT ON
        IF (@TableName IS NOT NULL) 
            select ORDINAL_POSITION OrderPosition,COLUMN_NAME ColumnName from information_schema.columns 
             where table_name =@TableName
             order by ORDINAL_POSITION
    END
END

Xcode 6 Storyboard the wrong size?

On your storyboard page, go to File Inspector and uncheck 'Use Size Classes'. This should shrink your view controller to regular IPhone size you were familiar with. Note that using 'size classes' will let you design your project across many devices. Once you uncheck this the Xcode will give you a warning dialogue as follows. This should be self-explainatory.

"Disabling size classes will limit this document to storing data for a single device family. The data for the size class best representing the targeted device will be retained, and all other data will be removed. In addition, segues will be converted to their non-adaptive equivalents."

Entity framework self referencing loop detected

I know this is an old question but here is the solution I found to a very similar coding issue in my own code:

var response = ApiDB.Persons.Include(y => y.JobTitle).Include(b => b.Discipline).Include(b => b.Team).Include(b => b.Site).OrderBy(d => d.DisplayName).ToArray();
        foreach (var person in response)
        {
            person.JobTitle = new JobTitle()
            {
                JobTitle_ID = person.JobTitle.JobTitle_ID,
                JobTitleName = person.JobTitle.JobTitleName,
                PatientInteraction = person.JobTitle.PatientInteraction,
                Active = person.JobTitle.Active,
                IsClinical = person.JobTitle.IsClinical
            };
        }

Since the person object contains everything from the person table and the job title object contains a list of persons with that job title, the database kept self referencing. I thought disabling proxy creation and lazy loading would fix this but unfortunately it didn't.

For the that aren't able to do that, try the solution above. Explicitly creating a new object for each object that self references, but leave out the list of objects or object that goes back to the previous entity will fix it since disabling lazy loading does not appear to work for me.

How do I import a .sql file in mysql database using PHP?

Solution special chars

 $link=mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());

//charset important
mysql_set_charset('utf8',$link);

Regular expression to limit number of characters to 10

/^[a-z]{0,10}$/ should work. /^[a-z]{1,10}$/ if you want to match at least one character, like /^[a-z]+$/ does.

Check if enum exists in Java

If I need to do this, I sometimes build a Set<String> of the names, or even my own Map<String,MyEnum> - then you can just check that.

A couple of points worth noting:

  • Populate any such static collection in a static initializer. Don't use a variable initializer and then rely on it having been executed when the enum constructor runs - it won't have been! (The enum constructors are the first things to be executed, before the static initializer.)
  • Try to avoid using values() frequently - it has to create and populate a new array each time. To iterate over all elements, use EnumSet.allOf which is much more efficient for enums without a large number of elements.

Sample code:

import java.util.*;

enum SampleEnum {
    Foo,
    Bar;

    private static final Map<String, SampleEnum> nameToValueMap =
        new HashMap<String, SampleEnum>();

    static {
        for (SampleEnum value : EnumSet.allOf(SampleEnum.class)) {
            nameToValueMap.put(value.name(), value);
        }
    }

    public static SampleEnum forName(String name) {
        return nameToValueMap.get(name);
    }
}

public class Test {
    public static void main(String [] args)
        throws Exception { // Just for simplicity!
        System.out.println(SampleEnum.forName("Foo"));
        System.out.println(SampleEnum.forName("Bar"));
        System.out.println(SampleEnum.forName("Baz"));
    }
}

Of course, if you only have a few names this is probably overkill - an O(n) solution often wins over an O(1) solution when n is small enough. Here's another approach:

import java.util.*;

enum SampleEnum {
    Foo,
    Bar;

    // We know we'll never mutate this, so we can keep
    // a local copy.
    private static final SampleEnum[] copyOfValues = values();

    public static SampleEnum forName(String name) {
        for (SampleEnum value : copyOfValues) {
            if (value.name().equals(name)) {
                return value;
            }
        }
        return null;
    }
}

public class Test {
    public static void main(String [] args)
        throws Exception { // Just for simplicity!
        System.out.println(SampleEnum.forName("Foo"));
        System.out.println(SampleEnum.forName("Bar"));
        System.out.println(SampleEnum.forName("Baz"));
    }
}

How to remove focus without setting focus to another control?

android:descendantFocusability="beforeDescendants"

using the following in the activity with some layout options below seemed to work as desired.

 getWindow().getDecorView().findViewById(android.R.id.content).clearFocus();

in connection with the following parameters on the root view.

<?xml
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:descendantFocusability="beforeDescendants" />

https://developer.android.com/reference/android/view/ViewGroup#attr_android:descendantFocusability

Answer thanks to: https://forums.xamarin.com/discussion/1856/how-to-disable-auto-focus-on-edit-text

About windowSoftInputMode

There's yet another point of contention to be aware of. By default, Android will automatically assign initial focus to the first EditText or focusable control in your Activity. It naturally follows that the InputMethod (typically the soft keyboard) will respond to the focus event by showing itself. The windowSoftInputMode attribute in AndroidManifest.xml, when set to stateAlwaysHidden, instructs the keyboard to ignore this automatically-assigned initial focus.

<activity
    android:name=".MyActivity"
    android:windowSoftInputMode="stateAlwaysHidden"/>

great reference

How to submit form on change of dropdown list?

To those in the answer above. It's definitely JavaScript. It's just inline.

BTW the jQuery equivalent if you want to apply to all selects:

$('form select').on('change', function(){
    $(this).closest('form').submit();
});

How to add an image in Tkinter?

Your actual code may return an error based on the format of the file path points to. That being said, some image formats such as .gif, .pgm (and .png if tk.TkVersion >= 8.6) is already supported by the PhotoImage class.

Below is an example displaying:

Lenna (.png)

or if tk.TkVersion < 8.6:

Lenna (.gif)

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def download_images():
    # In order to fetch the image online
    try:
        import urllib.request as url
    except ImportError:
        import urllib as url
    url.urlretrieve("https://i.stack.imgur.com/IgD2r.png", "lenna.png")
    url.urlretrieve("https://i.stack.imgur.com/sML82.gif", "lenna.gif")


if __name__ == '__main__':
    download_images()
    root = tk.Tk()
    widget = tk.Label(root, compound='top')
    widget.lenna_image_png = tk.PhotoImage(file="lenna.png")
    widget.lenna_image_gif = tk.PhotoImage(file="lenna.gif")
    try:
        widget['text'] = "Lenna.png"
        widget['image'] = widget.lenna_image_png
    except:
        widget['text'] = "Lenna.gif"
        widget['image'] = widget.lenna_image_gif
    widget.pack()
    root.mainloop()

How to download source in ZIP format from GitHub?

In chrome, if you hover your cursor on Download ZIP it will give you the link at the bottom of the browser

enter image description here

ALTER TABLE to add a composite primary key

You may simply want a UNIQUE CONSTRAINT. Especially if you already have a surrogate key. (example of an already existing surrogate key would be a single column that is an AUTO_INCREMENT )

Below is the sql code for a Unique Constraint

ALTER TABLE `MyDatabase`.`Provider`
    ADD CONSTRAINT CK_Per_Place_Thing_Unique UNIQUE (person,place,thing)
;

How to put/get multiple JSONObjects to JSONArray?

Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.

Something like this maybe:

jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);

Then create new JSONObject, put the other values into it and add it to the JSONArray:

jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);

Converting file size in bytes to human-readable string

Solution as ReactJS Component

Bytes = React.createClass({
    formatBytes() {
        var i = Math.floor(Math.log(this.props.bytes) / Math.log(1024));
        return !this.props.bytes && '0 Bytes' || (this.props.bytes / Math.pow(1024, i)).toFixed(2) + " " + ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][i]
    },
    render () {
        return (
            <span>{ this.formatBytes() }</span>
        );
    }
});

UPDATE For those using es6 here is a stateless version of this same component

const sufixes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const getBytes = (bytes) => {
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return !bytes && '0 Bytes' || (bytes / Math.pow(1024, i)).toFixed(2) + " " + sufixes[i];
};

const Bytes = ({ bytes }) => (<span>{ getBytes(bytes) }</span>);

Bytes.propTypes = {
  bytes: React.PropTypes.number,
};

Css Move element from left to right animated

Try this

_x000D_
_x000D_
div_x000D_
{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:red;_x000D_
  transition: all 1s ease-in-out;_x000D_
  -webkit-transition: all 1s ease-in-out;_x000D_
  -moz-transition: all 1s ease-in-out;_x000D_
  -o-transition: all 1s ease-in-out;_x000D_
  -ms-transition: all 1s ease-in-out;_x000D_
  position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
  transform: translate(3em,0);_x000D_
  -webkit-transform: translate(3em,0);_x000D_
  -moz-transform: translate(3em,0);_x000D_
  -o-transform: translate(3em,0);_x000D_
  -ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

DEMO

How do you join on the same table, twice, in mysql?

Given the following tables..

Domain Table
dom_id | dom_url

Review Table
rev_id | rev_dom_from | rev_dom_for

Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.

Select d1.dom_url, d2.dom_id from
review r, domain d1, domain d2
where d1.dom_id = r.rev_dom_from
and d2.dom_id = r.rev_dom_for

If you are still stuck, please be more specific with exactly it is that you don't understand.

No Android SDK found - Android Studio

Try make New Project, and then choose same android version that you've installed sdk verions on "Target Android Device" dialog. In my case, error message gone.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Here it is as a single formula:

=(RIGHT(D2,3))+(MID(D2,7,2)*1000)+(MID(D2,4,2)*60000)+(LEFT(D2,2)*3600000)

How to hide command output in Bash

You should not use bash in this case to get rid of the output. Yum does have an option -q which suppresses the output.

You'll most certainly also want to use -y

echo "Installing nano..."
yum -y -q install nano

To see all the options for yum, use man yum.

How can I remove a child node in HTML using JavaScript?

Modern Solution - child.remove()

For your use case:

document.getElementById("FirstDiv").remove()

This is recommended by W3C since late 2015, and is vanilla JS. All major browsers support it.

Mozilla Docs

Supported Browsers - 96% May 2020

Sort an ArrayList based on an object field

You can use the Bean Comparator to sort on any property in your custom class.

Submitting the value of a disabled input field

you can also use the Readonly attribute: the input is not gonna be grayed but it won't be editable

<input type="text" name="lat" value="22.2222" readonly="readonly" />

SQL alias for SELECT statement

Yes, but you can select only one column in your subselect

SELECT (SELECT id FROM bla) AS my_select FROM bla2

How to delete last character in a string in C#?

It's good practice to use a StringBuilder when concatenating a lot of strings and you can then use the Remove method to get rid of the final character.

StringBuilder paramBuilder = new StringBuilder();

foreach (var item in itemsToAdd)
{
    paramBuilder.AppendFormat(("productID={0}&", item.prodID.ToString());
}

if (paramBuilder.Length > 1)
    paramBuilder.Remove(paramBuilder.Length-1, 1);

string s = paramBuilder.ToString();

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

FFmpeg: How to split video efficiently?

Didn't test ist, but this looks promising:

Basic stream segmenter

It is obviously splitting AVI into segments of same size, which implies these chunks don't loose quality or increase memory or must be recalculated.

It also uses the codec copy - does that mean it can handle very large streams ? Because this is my problem, i want to break down my avi so i could use a filter to get rid of the distorsion. But a whole avi runs for hours.

Add item to Listview control

Simple one, just do like this..

ListViewItem lvi = new ListViewItem(pet.Name);
    lvi.SubItems.Add(pet.Type);
    lvi.SubItems.Add(pet.Age);
    listView.Items.Add(lvi);

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

[Joke mode on]

You can fix this by adding this:

https://github.com/donavon/undefined-is-a-function

import { undefined } from 'undefined-is-a-function';
// Fixed! undefined is now a function.

[joke mode off]

Is it possible to use Java 8 for Android development?

Android uses a Java that branches off of Java 6.

As of Android SDK version 19, you can use Java 7 features by doing this. No full support for Java 8 (yet).

How to use setprecision in C++

std::cout.precision(2);
std::cout<<std::fixed;

when you are using operator overloading try this.

Static linking vs dynamic linking

I agree with the points dnmckee mentions, plus:

  • Statically linked applications might be easier to deploy, since there are fewer or no additional file dependencies (.dll / .so) that might cause problems when they're missing or installed in the wrong place.

ActionBarActivity cannot resolve a symbol

Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.

Count number of occurences for each unique value

table() function is a good way to go, as Chase suggested. If you are analyzing a large dataset, an alternative way is to use .N function in datatable package.

Make sure you installed the data table package by

install.packages("data.table")

Code:

# Import the data.table package
library(data.table)

# Generate a data table object, which draws a number 10^7 times  
# from 1 to 10 with replacement
DT<-data.table(x=sample(1:10,1E7,TRUE))

# Count Frequency of each factor level
DT[,.N,by=x]

jQuery UI autocomplete with item and id

You need to use the ui.item.label (the text) and ui.item.value (the id) properties

$('#selector').autocomplete({
    source: url,
    select: function (event, ui) {
        $("#txtAllowSearch").val(ui.item.label); // display the selected text
        $("#txtAllowSearchID").val(ui.item.value); // save selected id to hidden input
    }
});

$('#button').click(function() {
    alert($("#txtAllowSearchID").val()); // get the id from the hidden input
}); 

[Edit] You also asked how to create the multi-dimensional array...

You should be able create the array like so:

var $local_source = [[0,"c++"], [1,"java"], [2,"php"], [3,"coldfusion"], 
                     [4,"javascript"], [5,"asp"], [6,"ruby"]];

Read more about how to work with multi-dimensional arrays here: http://www.javascriptkit.com/javatutors/literal-notation2.shtml

How do I print uint32_t and uint16_t variables value?

You need to include inttypes.h if you want all those nifty new format specifiers for the intN_t types and their brethren, and that is the correct (ie, portable) way to do it, provided your compiler complies with C99. You shouldn't use the standard ones like %d or %u in case the sizes are different to what you think.

It includes stdint.h and extends it with quite a few other things, such as the macros that can be used for the printf/scanf family of calls. This is covered in section 7.8 of the ISO C99 standard.

For example, the following program:

#include <stdio.h>
#include <inttypes.h>
int main (void) {
    uint32_t a=1234;
    uint16_t b=5678;
    printf("%" PRIu32 "\n",a);
    printf("%" PRIu16 "\n",b);
    return 0;
}

outputs:

1234
5678

How do you run a SQL Server query from PowerShell?

To avoid SQL Injection with varchar parameters you could use

function sqlExecuteRead($connectionString, $sqlCommand, $pars) {

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $connection.Open()
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection)

    if ($pars -and $pars.Keys) {
        foreach($key in $pars.keys) {
            # avoid injection in varchar parameters
            $par = $command.Parameters.Add("@$key", [system.data.SqlDbType]::VarChar, 512);
            $par.Value = $pars[$key];
        }
    }

    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataset) | Out-Null
    $connection.Close()
    return $dataset.tables[0].rows

}

$connectionString = "connectionstringHere"
$sql = "select top 10 Message, TimeStamp, Level from dbo.log " +
    "where Message = @MSG and Level like @LEVEL"
$pars = @{
    MSG = 'this is a test from powershell'
    LEVEL = 'aaa%'
};
sqlExecuteRead $connectionString $sql $pars

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

or if you have VS 2012 you can goto the package manager console and type Install-Package Microsoft.AspNet.WebApi.Client

This would download the latest version of the package

How is the default submit button on an HTML form determined?

I had a form with 11 submit buttons on it, and it would always use the first submit button when the user pressed enter. I read elsewhere that it is not a good idea (bad practice) to have more than one submit button on a form, and the best way to do this is have the button you want as default, as the only submit button on the form. The other buttons should be made into "TYPE=BUTTON" and an onClick event added that calls your own submit routine in Javascript. Something like this :-

<SCRIPT Language="JavaScript">
function validform()
{
  // do whatever you need to validate the form, and return true or false accordingly
}

function mjsubmit()
{
  if (validform()) { document.form1.submit(); return true;}
  return false;
}
</SCRIPT>
<INPUT TYPE=BUTTON NAME="button1" VALUE="button1" onClick="document.form1.submitvalue='button1'; return mjsubmit();">
<INPUT TYPE=BUTTON NAME="button2" VALUE="button2" onClick="document.form1.submitvalue='button2'; return mjsubmit();">
<INPUT TYPE=SUBMIT NAME="button3" VALUE="button3" onClick="document.form1.submitvalue='button3'; return validform();">
<INPUT TYPE=BUTTON NAME="button4" VALUE="button4" onClick="document.form1.submitvalue='button4'; return mjsubmit();">

Here, button3 is the default, and although you are programmatically submitting the form with the other buttons, the mjsubmit routine validates them. HTH.

Load a Bootstrap popover content with AJAX. Is this possible?

This works for me, this code fix possibles alignment issues:

<a class="ajax-popover" data-container="body" data-content="Loading..." data-html="data-html" data-placement="bottom" data-title="Title" data-toggle="popover" data-trigger="focus" data-url="your_url" role="button" tabindex="0" data-original-title="" title="">
  <i class="fa fa-info-circle"></i>
</a>

$('.ajax-popover').click(function() {
  var e = $(this);
  if (e.data('loaded') !== true) {
    $.ajax({
      url: e.data('url'),
      dataType: 'html',
      success: function(data) {
        e.data('loaded', true);
        e.attr('data-content', data);
        var popover = e.data('bs.popover');
        popover.setContent();
        popover.$tip.addClass(popover.options.placement);
        var calculated_offset = popover.getCalculatedOffset(popover.options.placement, popover.getPosition(), popover.$tip[0].offsetWidth, popover.$tip[0].offsetHeight);
        popover.applyPlacement(calculated_offset, popover.options.placement);
      },
      error: function(jqXHR, textStatus, errorThrown) {
        return instance.content('Failed to load data');
      }
    });
  }
});

Just in case, the endpoint I'm using returns html (a rails partial)

I took some part of the code from here https://stackoverflow.com/a/13565154/3984542

JQuery, select first row of table

Can't you use the first selector ?

something like: tr:first

How to install php-curl in Ubuntu 16.04

sudo apt-get install php5.6-curl

and restart the web browser.

You can check the modules by running php -m | grep curl

Change image size with JavaScript

You can change the actual width/height attributes like this:

var theImg = document.getElementById('theImgId');
theImg.height = 150;
theImg.width = 150;

Extract Google Drive zip from Google colab notebook

First create a new directory:

!mkdir file_destination

Now, it's the time to inflate the directory with the unzipped files with this:

!unzip file_location -d file_destination

Two div blocks on same line

Use below Css:

#bloc1,
#bloc2 {
display:inline
} 

body {
text-align:center
}

It will make the mentioned 2 divs in the center on the same line.

What are the most useful Intellij IDEA keyboard shortcuts?

Here are the Intellij IDEA keyboard shortcuts I find most useful (listed in roughly the order of usage for me):

The shortcut I use the most is Ctrl + B (Go to declaration), to see what a method does, where a variable is declared etc. This is almost always followed by Ctrl + Alt + Left to get back to where I was (Ctrl + Alt + Right works to “go forward” again).

A related navigation shortcut is Ctrl + Alt + B, (Go to implementation). Press it when the caret is at the method name of an interface, and you get a pop-up list of all the places where this method is implemented, and you can select which one you want to go to (if there is only one implementation, you go straight there). The same goes for overridden methods.

The opposite of this is Ctrl + U (Go to super-method/super-class). If the caret is at the implementation of a method in an interface (indicated by the little green interface-symbol in the left gutter), this shortcut takes you to the interface itself.

When I want to see all the places where a method or variable is used (which I want to do a lot), I use Ctrl + Alt + F7 (Show usages). This gives you a pop-up list of all the usages, and you can easily navigate to each one. I prefer this over Alt + F7 (Find usages), which gives you the same information, but in a separate pane below.

To find classes, I use Ctrl + N (Go to class), which lets you search using only the capital letters in the class name (“camel humps”), and * as wildcard.

Yet another shortcut I use, both when reading and writing code, is Ctrl + P (Parameter info) at the arguments of methods and constructors, to see the types and names of the parameters.

When it comes to writing code, I use Ctrl + space (Basic code completion) a lot to auto-complete method names, variable names etc (or simply to see which methods are available for a certain object, by trying to auto-complete directly at the dot following the name of the object).

For searching in the current file I use Ctrl-F (Find - probably the least surprising shortcut in this list), F3/Shift + F3 (Find next/previous) to repeat the search, and Ctrl + Shift + F (Find in path) to search in the whole project.

Ctrl + W (Select successively increasing code blocks) is handy when selecting chunks of code. Repeatedly pressing it selects more and more of the code. Useful when searching, indenting, commenting out code etc.

If there are errors in the file, F2/Shift + F2 (Next/previous highlighted error) will jump to them.

I use the sequence Alt + C, N (Show Changes View) to see which files in the project I have modified compared to the subversion repository. To diff the current file against the version in the subversion repository, I use the sequence Alt + C, S, Y (Compare with the Same Repository Version). In the diff view, I use F7/Shift + F7 to navigate between the changes.

When not in the diff view, I use Ctrl + Shift + Alt + Up/Ctrl + Shift + Alt + Down to jump to the parts of the file that have been changed compared to the checked-out version. At each modification point, you see the corresponding part in the checked-out version in a pop-up window.

Finally, I run JUnit tests using Ctrl + Shift + F10.

Edit: One really useful shortcut that I've only started using in the last few months is Ctrl + E. It brings up a pop-up with the 15 most recently used files, and you just arrow down to the one you want and hit enter to navigate to it.

Pycharm: run only part of my Python file

Pycharm shortcut for running "Selection" in the console is ALT + SHIFT + e

For this to work properly, you'll have to run everything this way.

enter image description here

Open file with associated application

In .Net Core (as of v2.2) it should be:

new Process
{
    StartInfo = new ProcessStartInfo(@"file path")
    {
        UseShellExecute = true
    }
}.Start();

Related github issue can be found here

Reverse Singly Linked List Java

I know the recursive solution is not the optimal one, but just wanted to add one here:

public class LinkedListDemo {

    static class Node {
        int val;
        Node next;

        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "" + val;
        }
    }

    public static void main(String[] args) {
        Node n = new Node(1, new Node(2, new Node(3, new Node(20, null))));
        display(n);
        n = reverse(n);
        display(n);
    }

    static Node reverse(Node n) {
        Node tail = n;
        while (tail.next != null) {
            tail = tail.next;
        }
        reverseHelper(n);
        return (tail);
    }

    static Node reverseHelper(Node n) {
        if (n.next != null) {
            Node reverse = reverseHelper(n.next);
            reverse.next = n;
            n.next = null;
            return (n);
        }
        return (n);
    }

    static void display(Node n) {
        for (; n != null; n = n.next) {
            System.out.println(n);
        }
    }
}

How to call a method in MainActivity from another class?

You can make this method static.

public static void startChronometer(){
        mChronometer.start();
        showElapsedTime();
    } 

you can call this function in other class as below:

MainActivity.startChronometer();

OR

You can make an object of the main class in second class like,

MainActivity mActivity = new MainActivity();
mActivity.startChronometer();

Setting maxlength of textbox with JavaScript or jQuery

set the attribute, not a property

$("#ms_num").attr("maxlength", 6);

Can I pass parameters in computed properties in Vue.Js

Well, technically speaking we can pass a parameter to a computed function, the same way we can pass a parameter to a getter function in vuex. Such a function is a function that returns a function.

For instance, in the getters of a store:

{
  itemById: function(state) {
    return (id) => state.itemPool[id];
  }
}

This getter can be mapped to the computed functions of a component:

computed: {
  ...mapGetters([
    'ids',
    'itemById'
  ])
}

And we can use this computed function in our template as follows:

<div v-for="id in ids" :key="id">{{itemById(id).description}}</div>

We can apply the same approach to create a computed method that takes a parameter.

computed: {
  ...mapGetters([
    'ids',
    'itemById'
  ]),
  descriptionById: function() {
    return (id) => this.itemById(id).description;
  }
}

And use it in our template:

<div v-for="id in ids" :key="id">{{descriptionById(id)}}</div>

This being said, I'm not saying here that it's the right way of doing things with Vue.

However, I could observe that when the item with the specified ID is mutated in the store, the view does refresh its contents automatically with the new properties of this item (the binding seems to be working just fine).

How can I use MS Visual Studio for Android Development?

Microsoft Visual Studio 2015 now has options for Android development: C++, Cordova, and C# with Xamarin. When choosing one of those Android development options, Visual Studio will also install the brand new Visual Studio Emulator for Android to use as a target for debugging your app. You can also download the emulator without needing to install Visual Studio. For more details see

Visuals Studio 2015 https://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs

Visual Studio Emulator https://www.visualstudio.com/en-us/features/msft-android-emulator-vs.aspx

Video of features https://channel9.msdn.com/Events/Visual-Studio/Visual-Studio-2015-Final-Release-Event/Visual-Studio-Emulator-for-Android

Java Extension for Visuals Studio 2012, 2013. 2015 https://visualstudiogallery.msdn.microsoft.com/bc561769-36ff-4a40-9504-e266e8706f93

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

Adding headers when using httpClient.GetAsync

Following the greenhoorn's answer, you can use "Extensions" like this:

  public static class HttpClientExtensions
    {
        public static HttpClient AddTokenToHeader(this HttpClient cl, string token)
        {
            //int timeoutSec = 90;
            //cl.Timeout = new TimeSpan(0, 0, timeoutSec);
            string contentType = "application/json";
            cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
            cl.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token));
            var userAgent = "d-fens HttpClient";
            cl.DefaultRequestHeaders.Add("User-Agent", userAgent);
            return cl;
        }
    }

And use:

string _tokenUpdated = "TOKEN";
HttpClient _client;
_client.AddTokenToHeader(_tokenUpdated).GetAsync("/api/values")

What is duck typing?

I think it's confused to mix up dynamic typing, static typing and duck typing. Duck typing is an independent concept and even static typed language like Go, could have a type checking system which implements duck typing. If a type system will check the methods of a (declared) object but not the type, it could be called a duck typing language.

Dynamically update values of a chartjs chart

You also can use destroy() function. Like this

 if( window.myBar!==undefined)
     window.myBar.destroy();
 var ctx = document.getElementById("canvas").getContext("2d");
 window.myBar = new Chart(ctx).Bar(barChartData, {
     responsive : true,
 });

How can I get the Windows last reboot reason

This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:

  1. Press the Windows + R keys to open the Run dialog, type eventvwr.msc, and press Enter.

  2. If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).

  3. In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.

  4. Do either step 5 or 6 below for what shutdown events you would like to see.

  5. To See the Dates and Times of All User Shut Downs of the Computer

    A) In Event sources, click/tap on the drop down arrow and check the USER32 box.

    B) In the All Event IDs field, type 1074, then click/tap on OK.

    C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.

    D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.

    E) Go to step 7.

  6. To See the Dates and Times of All Unexpected Shut Downs of the Computer

    A) In the All Event IDs field, type 6008, then click/tap on OK.

    B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

When we are going to migrate JQuery from 1.x to 2x or 3.x in our old existing application , then we will use .done,.fail instead of success,error as JQuery up gradation is going to be deprecated these methods.For example when we make a call to server web methods then server returns promise objects to the calling methods(Ajax methods) and this promise objects contains .done,.fail..etc methods.Hence we will the same for success and failure response. Below is the example(it is for POST request same way we can construct for request type like GET...)

 $.ajax({
            type: "POST",
            url: url,
            data: '{"name" :"sheo"}',
            contentType: "application/json; charset=utf-8",
            async: false,
            cache: false
            }).done(function (Response) {
                  //do something when get response            })
           .fail(function (Response) {
                    //do something when any error occurs.
                });

pandas: find percentile stats of a given column

I figured out below would work:

my_df.dropna().quantile([0.0, .9])

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes it is possible but you can better use a div #mydiv and use both

$(document).ready(function(){});

//and

$("#mydiv").ready(function(){});

file_get_contents behind a proxy?

Use stream_context_set_default function. It is much easier to use as you can directly use file_get_contents or similar functions without passing any additional parameters

This blog post explains how to use it. Here is the code from that page.

<?php
// Edit the four values below
$PROXY_HOST = "proxy.example.com"; // Proxy server address
$PROXY_PORT = "1234";    // Proxy server port
$PROXY_USER = "LOGIN";    // Username
$PROXY_PASS = "PASSWORD";   // Password
// Username and Password are required only if your proxy server needs basic authentication

$auth = base64_encode("$PROXY_USER:$PROXY_PASS");
stream_context_set_default(
 array(
  'http' => array(
   'proxy' => "tcp://$PROXY_HOST:$PROXY_PORT",
   'request_fulluri' => true,
   'header' => "Proxy-Authorization: Basic $auth"
   // Remove the 'header' option if proxy authentication is not required
  )
 )
);

$url = "http://www.pirob.com/";

print_r( get_headers($url) );

echo file_get_contents($url);
?>

Call a stored procedure with parameter in c#

As an alternative, I have a library that makes it easy to work with procs: https://www.nuget.org/packages/SprocMapper/

SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
    sqlAccess.Procedure()
         .AddSqlParameter("@FirstName", SqlDbType.VarChar, txtFirstName.Text)
         .AddSqlParameter("@FirstName", SqlDbType.VarChar, txtLastName.Text)
         .ExecuteNonQuery("StoredProcedureName");

What is pipe() function in Angular

You have to look to official ReactiveX documentation: https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md.

This is a good article about piping in RxJS: https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44.

In short .pipe() allows chaining multiple pipeable operators.

Starting in version 5.5 RxJS has shipped "pipeable operators" and renamed some operators:

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

PreparedStatement with list of parameters in a IN clause

Using Java 8 APIs, 

    List<Long> empNoList = Arrays.asList(1234, 7678, 2432, 9756556, 3354646);

    List<String> parameters = new ArrayList<>();
    empNoList.forEach(empNo -> parameters.add("?"));   //Use forEach to add required no. of '?'
    String commaSepParameters = String.join(",", parameters); //Use String to join '?' with ','

StringBuilder selectQuery = new StringBuilder().append("SELECT COUNT(EMP_ID) FROM EMPLOYEE WHERE EMP_ID IN (").append(commaSepParameters).append(")");

Better way to find index of item in ArrayList?

Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

Sometimes VS2010 switches my configuration from Any CPU to Mixed Platforms. When this happens I get this error message.

To resolve it I switch back to Any CPU:
1. Right click on the solution and select properties.
2. Click on Configuration Properties and then the Configuration Manager... button.
3. Under Active solution platform select Any CPU

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

How to use HTML to print header and footer on every printed page of a document?

Try this, for me it's working on Chrome, Firefox and Safari. You will get header and footer fixed to each page without overlapping the page content

CSS

<style>
  @page {
    margin: 10mm;
  }

  body {
    font: 9pt sans-serif;
    line-height: 1.3;

    /* Avoid fixed header and footer to overlap page content */
    margin-top: 100px;
    margin-bottom: 50px;
  }

  #header {
    position: fixed;
    top: 0;
    width: 100%;
    height: 100px;
    /* For testing */
    background: yellow; 
    opacity: 0.5;
  }

  #footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 50px;
    font-size: 6pt;
    color: #777;
    /* For testing */
    background: red; 
    opacity: 0.5;
  }

  /* Print progressive page numbers */
  .page-number:before {
    /* counter-increment: page; */
    content: "Pagina " counter(page);
  }

</style>

HTML

<body>

  <header id="header">Header</header>

  <footer id="footer">footer</footer>

  <div id="content">
    Here your long long content...
    <p style="page-break-inside: avoid;">This text will not be broken between the pages</p>
  </div>

</body>

What does a question mark represent in SQL queries?

The ? is an unnamed parameter which can be filled in by a program running the query to avoid SQL injection.

IIS Manager in Windows 10

To install the IIS Management Console under Windows 10 using Powershell with RSAT installed:

Enable-WindowsOptionalFeature -Online -FeatureName IIS-ManagementConsole -All

Credit and thanks to Mikhail's comment above.

How to import cv2 in python3?

There is a problem with pylint, which I do not completely understood yet.

You can just import OpenCV with: from cv2 import cv2

enter image description here

How to remove package using Angular CLI?

npm uninstal @angular/material

and also clear file custom-theme.scss

ASP.net Repeater get current index, pointer, or counter

Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.

ASPX

<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
    <ItemTemplate>
        <div id="width:50%;height:30px;background:#0f0a0f;">
            <asp:Label ID="lblSr" runat="server" 
               style="width:30%;float:left;text-align:right;text-indent:-2px;" />
            <span 
               style="width:65%;float:right;text-align:left;text-indent:-2px;" >
            <%# Eval("Item") %>
            </span>
        </div>
    </ItemTemplate>
</asp:Repeater>

Code Behind:

    protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
    {
        Label l = e.Item.FindControl("lblSr") as Label;
        if (l != null)
            l.Text = e.Item.ItemIndex + 1+"";
    }

How to check all checkboxes using jQuery?

function checkAll(class_name) {
    $("." + class_name).each(function () { 
        if (this.checked == true) 
            this.checked = false; 
        else 
            this.checked = true; 
    }); 
}

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

All of the functionality of our lightweight IDEs can be found within IntelliJ IDEA (you need to install the corresponding plug-ins from the repository).

It includes support for all technologies developed for our more specific products such as Web/PhpStorm, RubyMine and PyCharm.

The specific feature missing from IntelliJ IDEA is simplified project creation ("Open Directory") used in lighter products as it is not applicable to the IDE that support such a wide range of languages and technologies. It also means that you can't create projects directly from the remote hosts in IDEA.

If you are missing any other feature that is available in lighter products, but is not available in IntelliJ IDEA Ultimate, you are welcome to report it and we'll consider adding it.

While PHP, Python and Ruby IDEA plug-ins are built from the same source code as used in PhpStorm, PyCharm and RubyMine, product release cycles are not synchronized. It means that some features may be already available in the lighter products, but not available in IDEA plug-ins at certain periods, they are added with the plug-in and IDEA updates later.

Simple bubble sort c#

I wanted to add to the accepted answer something different: Number of iterations can be reduced as well, as below.

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;
int arrLength = arr.Length;

for (int write = 0; write < arr.Length - 1; write++, arrLength--)
{
    for (int sort = 0; sort < arrLength - 1; sort++)
    {
        if (arr[sort] > arr[sort + 1])
        {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

foreach (var item in arr)
{
    Console.WriteLine(item);
}

Difference between HashMap, LinkedHashMap and TreeMap

HashMap

  • It has pair values(keys,values)
  • NO duplication key values
  • unordered unsorted
  • it allows one null key and more than one null values

HashTable

  • same as hash map
  • it does not allows null keys and null values

LinkedHashMap

  • It is ordered version of map implementation
  • Based on linked list and hashing data structures

TreeMap

  • Ordered and sortered version
  • based on hashing data structures

Difference between Groovy Binary and Source release?

The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.

Where does R store packages?

This is documented in the 'R Installation and Administration' manual that came with your installation.

On my Linux box:

R> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"      
[3] "/usr/lib/R/library"           
R> 

meaning that the default path is the first of these. You can override that via an argument to both install.packages() (from inside R) or R CMD INSTALL (outside R).

You can also override by setting the R_LIBS_USER variable.

How to Copy Text to Clip Board in Android?

Yesterday I made this class. Take it, it's for all API Levels

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.util.Log;
import de.lochmann.nsafirewall.R;

public class MyClipboardManager {

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    public boolean copyToClipboard(Context context, String text) {
        try {
            int sdk = android.os.Build.VERSION.SDK_INT;
            if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
                        .getSystemService(context.CLIPBOARD_SERVICE);
                clipboard.setText(text);
            } else {
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
                        .getSystemService(context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData
                        .newPlainText(
                                context.getResources().getString(
                                        R.string.message), text);
                clipboard.setPrimaryClip(clip);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @SuppressLint("NewApi")
    public String readFromClipboard(Context context) {
        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
                    .getSystemService(context.CLIPBOARD_SERVICE);
            return clipboard.getText().toString();
        } else {
            ClipboardManager clipboard = (ClipboardManager) context
                    .getSystemService(Context.CLIPBOARD_SERVICE);

            // Gets a content resolver instance
            ContentResolver cr = context.getContentResolver();

            // Gets the clipboard data from the clipboard
            ClipData clip = clipboard.getPrimaryClip();
            if (clip != null) {

                String text = null;
                String title = null;

                // Gets the first item from the clipboard data
                ClipData.Item item = clip.getItemAt(0);

                // Tries to get the item's contents as a URI pointing to a note
                Uri uri = item.getUri();

                // If the contents of the clipboard wasn't a reference to a
                // note, then
                // this converts whatever it is to text.
                if (text == null) {
                    text = coerceToText(context, item).toString();
                }

                return text;
            }
        }
        return "";
    }

    @SuppressLint("NewApi")
    public CharSequence coerceToText(Context context, ClipData.Item item) {
        // If this Item has an explicit textual value, simply return that.
        CharSequence text = item.getText();
        if (text != null) {
            return text;
        }

        // If this Item has a URI value, try using that.
        Uri uri = item.getUri();
        if (uri != null) {

            // First see if the URI can be opened as a plain text stream
            // (of any sub-type). If so, this is the best textual
            // representation for it.
            FileInputStream stream = null;
            try {
                // Ask for a stream of the desired type.
                AssetFileDescriptor descr = context.getContentResolver()
                        .openTypedAssetFileDescriptor(uri, "text/*", null);
                stream = descr.createInputStream();
                InputStreamReader reader = new InputStreamReader(stream,
                        "UTF-8");

                // Got it... copy the stream into a local string and return it.
                StringBuilder builder = new StringBuilder(128);
                char[] buffer = new char[8192];
                int len;
                while ((len = reader.read(buffer)) > 0) {
                    builder.append(buffer, 0, len);
                }
                return builder.toString();

            } catch (FileNotFoundException e) {
                // Unable to open content URI as text... not really an
                // error, just something to ignore.

            } catch (IOException e) {
                // Something bad has happened.
                Log.w("ClippedData", "Failure loading text", e);
                return e.toString();

            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                    }
                }
            }

            // If we couldn't open the URI as a stream, then the URI itself
            // probably serves fairly well as a textual representation.
            return uri.toString();
        }

        // Finally, if all we have is an Intent, then we can just turn that
        // into text. Not the most user-friendly thing, but it's something.
        Intent intent = item.getIntent();
        if (intent != null) {
            return intent.toUri(Intent.URI_INTENT_SCHEME);
        }

        // Shouldn't get here, but just in case...
        return "";
    }

}

How can I check if a directory exists in a Bash shell script?

Git Bash + Dropbox + Windows:

None of the other solutions worked for my Dropbox folder, which was weird because I can Git push to a Dropbox symbolic path.

#!/bin/bash

dbox="~/Dropbox/"
result=0
prv=$(pwd) && eval "cd $dbox" && result=1 && cd "$prv"
echo $result

read -p "Press Enter To Continue:"

You'll probably want to know how to successfully navigate to Dropbox from Bash as well. So here is the script in its entirety.

https://pastebin.com/QF2Exmpn

How should I edit an Entity Framework connection string?

If you remove the connection string from the app.config file, re-running the entity Data Model wizard will guide you to build a new connection.

Media query to detect if device is touchscreen

I was able to resolve this issue using this

@media (hover:none), (hover:on-demand) { 
Your class or ID{
attributes
}    
}

Getting multiple selected checkbox values in a string in javascript and PHP

var fav = [];
$.each($("input[name='name']:checked"), function(){            
    fav.push($(this).val());
});

It will give you the value separeted by commas

Duplicate AssemblyVersion Attribute

This usually happens for me if I compiled the project in Visual Studio 2017 & then I try to rebuild & run it with .NET Core with the command line command "dotnet run".

Simply deleting all the "bin" & "obj" folders - both inside "ClientApp" & directly in the project folder - allowed the .NET Core command "dotnet run" to rebuild & run successfully.

Formula to determine brightness of RGB color

The "Accepted" Answer is Incorrect and Incomplete

The only answers that are accurate are the @jive-dadson and @EddingtonsMonkey answers, and in support @nils-pipenbrinck. The other answers (including the accepted) are linking to or citing sources that are either wrong, irrelevant, obsolete, or broken.

Briefly:

  • sRGB must be LINEARIZED before applying the coefficients.
  • Luminance (L or Y) is linear as is light.
  • Perceived lightness (L*) is nonlinear as is human perception.
  • HSV and HSL are not even remotely accurate in terms of perception.
  • The IEC standard for sRGB specifies a threshold of 0.04045 it is NOT 0.03928 (that was from an obsolete early draft).
  • The be useful (i.e. relative to perception), Euclidian distances require a perceptually uniform Cartesian vector space such as CIELAB. sRGB is not one.

What follows is a correct and complete answer:

Because this thread appears highly in search engines, I am adding this answer to clarify the various misconceptions on the subject.

Luminance is a linear measure of light, spectrally weighted for normal vision but not adjusted for the non-linear perception of lightness. It can be a relative measure, Y as in CIEXYZ, or as L, an absolute measure in cd/m2 (not to be confused with L*).

Perceived lightness is used by some vision models such as CIELAB, here L* (Lstar) is a value of perceptual lightness, and is non-linear to approximate the human vision non-linear response curve.

Brightness is a perceptual attribute, it does not have a "physical" measure. However some color appearance models do have a value, usualy denoted as "Q" for perceived brightness, which is different than perceived lightness.

Luma ( prime) is a gamma encoded, weighted signal used in some video encodings (Y´I´Q´). It is not to be confused with linear luminance.

Gamma or transfer curve (TRC) is a curve that is often similar to the perceptual curve, and is commonly applied to image data for storage or broadcast to reduce perceived noise and/or improve data utilization (and related reasons).

To determine perceived lightness, first convert gamma encoded R´G´B´ image values to linear luminance (L or Y ) and then to non-linear perceived lightness (L*)


TO FIND LUMINANCE:

...Because apparently it was lost somewhere...

Step One:

Convert all sRGB 8 bit integer values to decimal 0.0-1.0

  vR = sR / 255;
  vG = sG / 255;
  vB = sB / 255;

Step Two:

Convert a gamma encoded RGB to a linear value. sRGB (computer standard) for instance requires a power curve of approximately V^2.2, though the "accurate" transform is:

sRGB to Linear

Where V´ is the gamma-encoded R, G, or B channel of sRGB.
Pseudocode:

function sRGBtoLin(colorChannel) {
        // Send this function a decimal sRGB gamma encoded color value
        // between 0.0 and 1.0, and it returns a linearized value.

    if ( colorChannel <= 0.04045 ) {
            return colorChannel / 12.92;
        } else {
            return pow((( colorChannel + 0.055)/1.055),2.4));
        }
    }

Step Three:

To find Luminance (Y) apply the standard coefficients for sRGB:

Apply coefficients Y = R * 0.2126 + G * 0.7152 + B *  0.0722

Pseudocode using above functions:

Y = (0.2126 * sRGBtoLin(vR) + 0.7152 * sRGBtoLin(vG) + 0.0722 * sRGBtoLin(vB))

TO FIND PERCEIVED LIGHTNESS:

Step Four:

Take luminance Y from above, and transform to L*

L* from Y equation
Pseudocode:

function YtoLstar(Y) {
        // Send this function a luminance value between 0.0 and 1.0,
        // and it returns L* which is "perceptual lightness"

    if ( Y <= (216/24389) {       // The CIE standard states 0.008856 but 216/24389 is the intent for 0.008856451679036
            return Y * (24389/27);  // The CIE standard states 903.3, but 24389/27 is the intent, making 903.296296296296296
        } else {
            return pow(Y,(1/3)) * 116 - 16;
        }
    }

L* is a value from 0 (black) to 100 (white) where 50 is the perceptual "middle grey". L* = 50 is the equivalent of Y = 18.4, or in other words an 18% grey card, representing the middle of a photographic exposure (Ansel Adams zone V).

References:

IEC 61966-2-1:1999 Standard
Wikipedia sRGB
Wikipedia CIELAB
Wikipedia CIEXYZ
Charles Poynton's Gamma FAQ

Deprecation warning in Moment.js - Not in a recognized ISO format

I ran into this error because I was trying to pass in a date from localStorage. Passing the date into a new Date object, and then calling .toISOString() did the trick for me:

const dateFromStorage = localStorage.getItem('someDate');
const date = new Date(dateFromStorage);
const momentDate = moment(date.toISOString());

This suppressed any warnings in the console.

AngularJS dynamic routing

angular.module('myapp', ['myapp.filters', 'myapp.services', 'myapp.directives']).
        config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/page/:name*', {
            templateUrl: function(urlattr){
                return '/pages/' + urlattr.name + '.html';
            },
            controller: 'CMSController'
        });
    }
]);
  • Adding * let you work with multiple levels of directories dynamically. Example: /page/cars/selling/list will be catch on this provider

From the docs (1.3.0):

"If templateUrl is a function, it will be called with the following parameters:

{Array.} - route parameters extracted from the current $location.path() by applying the current route"

Also

when(path, route) : Method

  • path can contain named groups starting with a colon and ending with a star: e.g.:name*. All characters are eagerly stored in $routeParams under the given name when the route matches.

Entity Framework Timeouts

Usually I handle my operations within a transaction. As I've experienced, it is not enough to set the context command timeout, but the transaction needs a constructor with a timeout parameter. I had to set both time out values for it to work properly.

int? prevto = uow.Context.Database.CommandTimeout;
uow.Context.Database.CommandTimeout = 900;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(900))) {
...
}

At the end of the function I set back the command timeout to the previous value in prevto.

Using EF6

How can I view live MySQL queries?

In addition to previous answers describing how to enable general logging, I had to modify one additional variable in my vanilla MySql 5.6 installation before any SQL was written to the log:

SET GLOBAL log_output = 'FILE';

The default setting was 'NONE'.

How to comment lines in rails html.erb files?

Note that if you want to comment out a single line of printing erb you should do like this

<%#= ["Buck", "Papandreou"].join(" you ") %>

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html

How to show full object in Chrome console?

With modern browsers, console.log(functor) works perfectly (behaves the same was a console.dir).

npm ERR! network getaddrinfo ENOTFOUND

Take a look at your HTTP_PROXY and HTTPS_PROXY environment variables.

I thought mine were set correctly, as http://username:password@proxyhost:proxyport, but it turned out that they were actually causing the problem! After deleting those variables, and restarting the commant prompt, the npm commands worked again.

how to write value into cell with vba code without auto type conversion?

Cells(1,1).Value2 = "'123,456"

note the single apostrophe before the number - this will signal to excel that whatever follows has to be interpreted as text.

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

That's how I would handle different images (sizes and proportions) in a flexible grid.

_x000D_
_x000D_
.images {_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
  margin: -20px;_x000D_
}_x000D_
_x000D_
.imagewrapper {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  width: calc(50% - 20px);_x000D_
  height: 300px;_x000D_
  margin: 10px;_x000D_
}_x000D_
_x000D_
.image {_x000D_
  display: block;_x000D_
  object-fit: cover;_x000D_
  width: 100%;_x000D_
  height: 100%; /* set to 'auto' in IE11 to avoid distortions */_x000D_
}
_x000D_
<div class="images">_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/800x600" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/1024x768" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/1000x800" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/500x800" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/800x600" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/1024x768" />_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I turn a DataTable to a CSV?

I wrapped this up into an extension class, which allows you to call:

myDataTable.WriteToCsvFile("C:\\MyDataTable.csv");

on any DataTable.

public static class DataTableExtensions 
{
    public static void WriteToCsvFile(this DataTable dataTable, string filePath) 
    {
        StringBuilder fileContent = new StringBuilder();

        foreach (var col in dataTable.Columns) 
        {
            fileContent.Append(col.ToString() + ",");
        }

        fileContent.Replace(",", System.Environment.NewLine, fileContent.Length - 1, 1);

        foreach (DataRow dr in dataTable.Rows) 
        {
            foreach (var column in dr.ItemArray) 
            {
                fileContent.Append("\"" + column.ToString() + "\",");
            }

            fileContent.Replace(",", System.Environment.NewLine, fileContent.Length - 1, 1);
        }

        System.IO.File.WriteAllText(filePath, fileContent.ToString());
    }
}

Delete the 'first' record from a table in SQL Server, without a WHERE condition

WITH  q AS
        (
        SELECT TOP 1 *
        FROM    mytable
        /* You may want to add ORDER BY here */
        )
DELETE
FROM    q

Note that

DELETE TOP (1)
FROM   mytable

will also work, but, as stated in the documentation:

The rows referenced in the TOP expression used with INSERT, UPDATE, or DELETE are not arranged in any order.

Therefore, it's better to use WITH and an ORDER BY clause, which will let you specify more exactly which row you consider to be the first.

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Select2 for Bootstrap 3 native plugin

https://fk.github.io/select2-bootstrap-css/index.html

this plugin uses select2 jquery plugin

nuget

PM> Install-Package Select2-Bootstrap

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar problem but it had to do with the structure and class of the object. I would check how dih_y2$MemberID is formatted.

How to enable Logger.debug() in Log4j

I like to use a rolling file appender to write the logging info to a file. My log4j properties file typically looks something like this. I prefer this way since I like to make package specific logging in case I need varying degrees of logging for different packages. Only one package is mentioned in the example.

log4j.appender.RCS=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RCS.File.DateFormat='.'yyyy-ww
#define output location
log4j.appender.RCS.File=C:temp/logs/MyService.log
#define the file layout
log4j.appender.RCS.layout=org.apache.log4j.PatternLayout
log4j.appender.RCS.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm a} %5 %c{1}: Line#%L - %m%n
log4j.rootLogger=warn
#Define package specific logging
log4j.logger.MyService=debug, RCS

Run JavaScript code on window close or page refresh?

jQuery version:

$(window).unload(function(){
    // Do Something
});

Update: jQuery 3:

$(window).on("unload", function(e) {
    // Do Something
});

Thanks Garrett

What is *.o file?

A file ending in .o is an object file. The compiler creates an object file for each source file, before linking them together, into the final executable.

How to run Spyder in virtual environment?

Additional to tomaskazemekas's answer: you should install spyder in that virtual environment by:

conda install -n myenv spyder

(on Windows, for Linux or MacOS, you can search for similar commands)

Merge trunk to branch in Subversion

It is “old-fashioned” way to specify ranges of revisions you wish to merge. With 1.5+ you can use:

svn merge HEAD url/of/trunk path/to/branch/wc

Is there a MySQL option/feature to track history of changes to records?

You could create triggers to solve this. Here is a tutorial to do so (archived link).

Setting constraints and rules in the database is better than writing special code to handle the same task since it will prevent another developer from writing a different query that bypasses all of the special code and could leave your database with poor data integrity.

For a long time I was copying info to another table using a script since MySQL didn’t support triggers at the time. I have now found this trigger to be more effective at keeping track of everything.

This trigger will copy an old value to a history table if it is changed when someone edits a row. Editor ID and last mod are stored in the original table every time someone edits that row; the time corresponds to when it was changed to its current form.

DROP TRIGGER IF EXISTS history_trigger $$

CREATE TRIGGER history_trigger
BEFORE UPDATE ON clients
    FOR EACH ROW
    BEGIN
        IF OLD.first_name != NEW.first_name
        THEN
                INSERT INTO history_clients
                    (
                        client_id    ,
                        col          ,
                        value        ,
                        user_id      ,
                        edit_time
                    )
                    VALUES
                    (
                        NEW.client_id,
                        'first_name',
                        NEW.first_name,
                        NEW.editor_id,
                        NEW.last_mod
                    );
        END IF;

        IF OLD.last_name != NEW.last_name
        THEN
                INSERT INTO history_clients
                    (
                        client_id    ,
                        col          ,
                        value        ,
                        user_id      ,
                        edit_time
                    )
                    VALUES
                    (
                        NEW.client_id,
                        'last_name',
                        NEW.last_name,
                        NEW.editor_id,
                        NEW.last_mod
                    );
        END IF;

    END;
$$

Another solution would be to keep an Revision field and update this field on save. You could decide that the max is the newest revision, or that 0 is the most recent row. That's up to you.

Tree data structure in C#

If you would like to write your own, you can start with this six-part document detailing effective usage of C# 2.0 data structures and how to go about analyzing your implementation of data structures in C#. Each article has examples and an installer with samples you can follow along with.

“An Extensive Examination of Data Structures Using C# 2.0” by Scott Mitchell

Grouping into interval of 5 minutes within a time range

For postgres, I found it easier and more accurate to use the

date_trunc

function, like:

select name, sum(count), date_trunc('minute',timestamp) as timestamp
FROM table
WHERE xxx
GROUP BY name,date_trunc('minute',timestamp)
ORDER BY timestamp

You can provide various resolutions like 'minute','hour','day' etc... to date_trunc.

How set maximum date in datepicker dialog in android?

You can create Custom date picker, that is work for all api levels.

public class CustomDatePickerDialog extends DatePickerDialog {

    int maxYear;
    int maxMonth;
    int maxDay;

    public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
        super(context, callBack, year, monthOfYear, dayOfMonth);
    }

    public void setMaxDate(long maxDate) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getDatePicker().setMaxDate(System.currentTimeMillis());
        } else {
            final Calendar c = Calendar.getInstance();
            c.setTimeInMillis(maxDate);
            maxYear = c.get(Calendar.YEAR);
            maxMonth = c.get(Calendar.MONTH);
            maxDay = c.get(Calendar.DAY_OF_MONTH);
        }
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            super.onDateChanged(view, year, monthOfYear, dayOfMonth);
        } else {
            if (year > maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

            if (monthOfYear > maxMonth && year == maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

            if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
                view.updateDate(maxYear, maxMonth, maxDay);
        }
    }

set max date

final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(getActivity(),
        myDateListener, year, month, day);
pickerDialog.setMaxDate(System.currentTimeMillis());
pickerDialog.show();

How to call a Parent Class's method from Child Class in Python?

class department:
    campus_name="attock"
    def printer(self):
        print(self.campus_name)

class CS_dept(department):
    def overr_CS(self):
        department.printer(self)
        print("i am child class1")

c=CS_dept()
c.overr_CS()

change cursor from block or rectangle to line?

please Press fn +ins key together

How to build a Debian/Ubuntu package from source?

you can use the special package "checkinstall" for all packages which are not even in debian/ubuntu yet.

You can use "uupdate" (apt-get install devscripts) to build a package from source with existing debian sources:

Example for libdrm2:

apt-get build-dep libdrm2
apt-get source libdrm2
cd libdrm-2.3.1
uupdate ~/Downloads/libdrm-2.4.1.tar.gz
cd ../libdrm-2.4.1
dpkg-buildpackage -us -uc -nc

pandas dataframe convert column type to string or categorical

With pandas >= 1.0 there is now a dedicated string datatype:

1) You can convert your column to this pandas string datatype using .astype('string'):

df['zipcode'] = df['zipcode'].astype('string')

2) This is different from using str which sets the pandas object datatype:

df['zipcode'] = df['zipcode'].astype(str)

3) For changing into categorical datatype use:

df['zipcode'] = df['zipcode'].astype('category')

You can see this difference in datatypes when you look at the info of the dataframe:

df = pd.DataFrame({
    'zipcode_str': [90210, 90211] ,
    'zipcode_string': [90210, 90211],
    'zipcode_category': [90210, 90211],
})

df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')

df.info()

# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
 #   Column            Non-Null Count  Dtype   
---  ------            --------------  -----   
 0   zipcode_str       2 non-null      object  
 1   zipcode_string    2 non-null      string  
 2   zipcode_category  2 non-null      category
dtypes: category(1), object(1), string(1)

From the docs:

The 'string' extension type solves several issues with object-dtype NumPy arrays:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than string.

More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html

The default for KeyValuePair

Try this:

if (getResult.Equals(new KeyValuePair<T,U>()))

or this:

if (getResult.Equals(default(KeyValuePair<T,U>)))

Remove title in Toolbar in appcompat-v7

if your using default toolbar then you can add this line of code

Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);

Iterating through a list in reverse order in java

You could use the concrete class LinkedList instead of the general interface List. Then you have a descendingIterator for iterating with the reverse direction.

LinkedList<String > linkedList;
for( Iterator<String > it = linkedList.descendingIterator(); it.hasNext(); ) {
    String text = it.next();
}

Don't know why there is no descendingIterator with ArrayList...

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

How to delete a column from a table in MySQL

ALTER TABLE tbl_Country DROP COLUMN IsDeleted;

Here's a working example.

Note that the COLUMN keyword is optional, as MySQL will accept just DROP IsDeleted. Also, to drop multiple columns, you have to separate them by commas and include the DROP for each one.

ALTER TABLE tbl_Country
  DROP COLUMN IsDeleted,
  DROP COLUMN CountryName;

This allows you to DROP, ADD and ALTER multiple columns on the same table in the one statement. From the MySQL reference manual:

You can issue multiple ADD, ALTER, DROP, and CHANGE clauses in a single ALTER TABLE statement, separated by commas. This is a MySQL extension to standard SQL, which permits only one of each clause per ALTER TABLE statement.

Web scraping with Java

You might look into jwht-scrapper!

This is a complete scrapping framework that has all the features a developper could expect from a web scrapper:

It works with (jwht-htmltopojo)[https://github.com/whimtrip/jwht-htmltopojo) lib which itsef uses Jsoup mentionned by several other people here.

Together they will help you built awesome scrappers mapping directly HTML to POJOs and bypassing any classical scrapping problems in only a matter of minutes!

Hope this might help some people here!

Disclaimer, I am the one who developed it, feel free to let me know your remarks!

jQuery: Scroll down page a set increment (in pixels) on click?

Pure js solution for newcomers or anyone else.

var scrollAmount = 150;
var element = document.getElementById("elem");

element.addEventListener("click", scrollPage);

function scrollPage() {
    var currentPositionOfPage = window.scrollY;
    window.scrollTo(0, currentPositionOfPage + scrollAmount);
}

What is the best way to ensure only one instance of a Bash script is running?

If the script is the same across all users, you can use a lockfile approach. If you acquire the lock, proceed else show a message and exit.

As an example:

[Terminal #1] $ lockfile -r 0 /tmp/the.lock
[Terminal #1] $ 

[Terminal #2] $ lockfile -r 0 /tmp/the.lock
[Terminal #2] lockfile: Sorry, giving up on "/tmp/the.lock"

[Terminal #1] $ rm -f /tmp/the.lock
[Terminal #1] $ 

[Terminal #2] $ lockfile -r 0 /tmp/the.lock
[Terminal #2] $ 

After /tmp/the.lock has been acquired your script will be the only one with access to execution. When you are done, just remove the lock. In script form this might look like:

#!/bin/bash

lockfile -r 0 /tmp/the.lock || exit 1

# Do stuff here

rm -f /tmp/the.lock

Count items in a folder with PowerShell

To count the number of a specific filetype in a folder. The example is to count mp3 files on F: drive.

( Get-ChildItme F: -Filter *.mp3 - Recurse | measure ).Count

Tested in 6.2.3, but should work >4.

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

Maybe a bit late, but I found this answer looking over the internet. It could help others with the same problem.

$sudo mysql -u root
[mysql] use mysql;
[mysql] update user set plugin='' where User='root';
[mysql] flush privileges;
[mysql] \q

Now you should be able to log in as root in phpmyadmin.

(Found here.)

Finish all activities at a time

There are three solution for clear activity history.

1) You can write finish() at the time of start new activity through intent.

2) Write android:noHistory="true" in all <activity> tag in Androidmanifest.xml file, using this if you are open new activity and you don't write finish() at that time previous activity is always finished, after write your activity look like this.

<activity
    android:name=".Splash_Screen_Activity"
    android:label="@string/app_name"
    android:noHistory="true">

</activity>

3) write system.exit(0) for exit from the application.

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

I also ran into this problem. My situation was a little different. I was using 'working sets' to group my projects inside of eclipse. What I had done was attempt to delete a project and received errors while deleting. Ignoring the errors I removed the project from my working set and thus didn't see that I even had the project anymore. When I received my error I didn't think to look through my package explorer with 'projects', opposed to working sets, as my top view. After switching to a top level view of projects I found the project that was half deleted and was able to delete its contents from both my workspace and the hard drive.

I haven't had the error since.

button image as form input submit button?

<div class="container-fluid login-container">
    <div class="row">
        <form (ngSubmit)="login('da')">
            <div class="col-md-4">
                    <div class="login-text">
                        Login
                    </div>
                    <div class="form-signin">
                            <input type="text" class="form-control" placeholder="Email" required>
                            <input type="password" class="form-control" placeholder="Password" required>
                    </div>
            </div>
            <div class="col-md-4">
                <div class="login-go-div">
                    <input type="image" src="../../../assets/images/svg/login-go-initial.svg" class="login-go"
                         onmouseover="this.src='../../../assets/images/svg/login-go.svg'"
                         onmouseout="this.src='../../../assets/images/svg/login-go-initial.svg'"/>
                </div>
            </div>
        </form>
    </div>
</div>

This is the working code for it.

Shell command to sum integers, one per line?

Pure and short bash.

f=$(cat numbers.txt)
echo $(( ${f//$'\n'/+} ))

printf format specifiers for uint32_t and size_t

Sounds like you're expecting size_t to be the same as unsigned long (possibly 64 bits) when it's actually an unsigned int (32 bits). Try using %zu in both cases.

I'm not entirely certain though.

Is it safe to use Project Lombok?

I'm not recommend it. I used to use it, but then when I work with NetBeans 7.4 it was messing my codes. I've to remove lombok in all of files in my projects. There is delombok, but how can I be sure it would not screw my codes. I have to spends days just to remove lombok and back to ordinary Java styles. I just too spicy...

Should I use JSLint or JSHint JavaScript validation?

Well, Instead of doing manual lint settings we can include all the lint settings at the top of our JS file itself e.g.

Declare all the global var in that file like:

/*global require,dojo,dojoConfig,alert */

Declare all the lint settings like:

/*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */

Hope this will help you :)

How can I make a TextBox be a "password box" and display stars when using MVVM?

Thanks Cody, that was very helpful. I've just added an example for guys using the Delegate Command in C#

<PasswordBox x:Name="PasswordBox"
             Grid.Row="1" Grid.Column="1"
             HorizontalAlignment="Left" 
             Width="300" Height="25"
             Margin="6,7,0,7" />
<Button Content="Login"
        Grid.Row="4" Grid.Column="1"
        Style="{StaticResource StandardButton}"
        Command="{Binding LoginCommand}"
        CommandParameter="{Binding ElementName=PasswordBox}"
        Height="31" Width="92"
        Margin="5,9,0,0" />

 

public ICommand LoginCommand
{
   get
   {
        return new DelegateCommand<object>((args) =>
        {
            // Get Password as Binding not supported for control-type PasswordBox
            LoginPassword = ((PasswordBox) args).Password;

            // Rest of code here
        });
   }
}

What is the most efficient string concatenation method in python?

Probably "new f-strings in Python 3.6" is the most efficient way of concatenating strings.

Using %s

>>> timeit.timeit("""name = "Some"
... age = 100
... '%s is %s.' % (name, age)""", number = 10000)
0.0029734770068898797

Using .format

>>> timeit.timeit("""name = "Some"
... age = 100
... '{} is {}.'.format(name, age)""", number = 10000)
0.004015227983472869

Using f

>>> timeit.timeit("""name = "Some"
... age = 100
... f'{name} is {age}.'""", number = 10000)
0.0019175919878762215

Source: https://realpython.com/python-f-strings/

Extracting a parameter from a URL in WordPress

You can try this function

/**
 * Gets the request parameter.
 *
 * @param      string  $key      The query parameter
 * @param      string  $default  The default value to return if not found
 *
 * @return     string  The request parameter.
 */

function get_request_parameter( $key, $default = '' ) {
    // If not request set
    if ( ! isset( $_REQUEST[ $key ] ) || empty( $_REQUEST[ $key ] ) ) {
        return $default;
    }

    // Set so process it
    return strip_tags( (string) wp_unslash( $_REQUEST[ $key ] ) );
}

Here is what is happening in the function

Here three things are happening.

  • First we check if the request key is present or not. If not, then just return a default value.
  • If it is set, then we first remove slashes by doing wp_unslash. Read here why it is better than stripslashes_deep.
  • Then we sanitize the value by doing a simple strip_tags. If you expect rich text from parameter, then run it through wp_kses or similar functions.

All of this information plus more info on the thinking behind the function can be found on this link https://www.intechgrity.com/correct-way-get-url-parameter-values-wordpress/

How to concatenate strings in twig

To mix strings, variables and translations I simply do the following:

    {% set add_link = '
    <a class="btn btn-xs btn-icon-only" 
       title="' ~ 'string.to_be_translated'|trans ~ '" 
       href="' ~ path('acme_myBundle_link',{'link':link.id})  ~ '">
    </a>
    ' %}

Despite everything being mixed up, it works like a charm.

Insert a background image in CSS (Twitter Bootstrap)

body {
    background-image: url(your image link);
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment:fixed;
    background-size: cover;
    background-color: #464646;
}

How to remove entry from $PATH on mac

On MAC OS X Leopard and higher

cd /etc/paths.d

There may be a text file in the above directory that contains the path you are trying to remove.

vim textfile //check and see what is in it when you are done looking type :q 
//:q just quits, no saves

If its the one you want to remove do this

rm textfile //remove it, delete it

Here is a link to a site that has more info on it, even though it illustrates 'adding' the path. However, you may gain some insight.

Move / Copy File Operations in Java

Here's how to do this with java.nio operations:

public static void copyFile(File sourceFile, File destFile) throws IOException {
    if(!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();

        // previous code: destination.transferFrom(source, 0, source.size());
        // to avoid infinite loops, should be:
        long count = 0;
        long size = source.size();              
        while((count += destination.transferFrom(source, count, size-count))<size);
    }
    finally {
        if(source != null) {
            source.close();
        }
        if(destination != null) {
            destination.close();
        }
    }
}

Please initialize the log4j system properly warning

Try doing something like the following in main:

public static void main(String[] args) {
     PropertyConfigurator.configure(args[0]);
    //... your code

you need to tell log4j what its configuration should be.

How to set a cookie for another domain

You can't, but... If you own both pages then...

1) You can send the data via query params (http://siteB.com/?key=value)

2) You can create an iframe of Site B inside site A and you can send post messages from one place to the other. As Site B is the owner of site B cookies it will be able to set whatever value you need by processing the correct post message. (You should prevent other unwanted senders to send messages to you! that is up to you and the mechanism you decide to use to prevent that from happening)

Putting a password to a user in PhpMyAdmin in Wamp

Search your installation of PhpMyAdmin for a file called Documentation.txt. This describes how to create a file called config.inc.php and how you can configure the username and password.

Populating a ComboBox using C#

Define a class

public class Language
{
     public string Name { get; set; }
     public string Value { get; set; }
}

then...

//Build a list
var dataSource = new List<Language>();
dataSource.Add(new Language() { Name = "blah", Value = "blah" });
dataSource.Add(new Language() { Name = "blah", Value = "blah" });
dataSource.Add(new Language() { Name = "blah", Value = "blah" });

//Setup data binding
this.comboBox1.DataSource = dataSource;
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "Value";

// make it readonly
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

How to make sure docker's time syncs with that of the host?

For whatever reason none of these answers solved my problem.

It had nothing to do with the docker date/time for the images I was creating. It had to do with my local WSL date time.

Once I ran sudo ntpdate-debian everything worked.

If you don't have ntp just install it and run the command. If you aren't using debian then you probably won't have the shell script ntpdate-debian, but you can use ntpd -gq as well. Basically just update the date for your main WSL distro.

how to get all markers on google-maps-v3

The one way found is to use the geoXML3 library which is suitable for usage along with KML processor Version 3 of the Google Maps JavaScript API.

How can I multiply and divide using only bit shifting and adding?

Try this. https://gist.github.com/swguru/5219592

import sys
# implement divide operation without using built-in divide operator
def divAndMod_slow(y,x, debug=0):
    r = 0
    while y >= x:
            r += 1
            y -= x
    return r,y 


# implement divide operation without using built-in divide operator
def divAndMod(y,x, debug=0):

    ## find the highest position of positive bit of the ratio
    pos = -1
    while y >= x:
            pos += 1
            x <<= 1
    x >>= 1
    if debug: print "y=%d, x=%d, pos=%d" % (y,x,pos)

    if pos == -1:
            return 0, y

    r = 0
    while pos >= 0:
            if y >= x:
                    r += (1 << pos)                        
                    y -= x                
            if debug: print "y=%d, x=%d, r=%d, pos=%d" % (y,x,r,pos)

            x >>= 1
            pos -= 1

    return r, y


if __name__ =="__main__":
    if len(sys.argv) == 3:
        y = int(sys.argv[1])
        x = int(sys.argv[2])
     else:
            y = 313271356
            x = 7

print "=== Slow Version ...."
res = divAndMod_slow( y, x)
print "%d = %d * %d + %d" % (y, x, res[0], res[1])

print "=== Fast Version ...."
res = divAndMod( y, x, debug=1)
print "%d = %d * %d + %d" % (y, x, res[0], res[1])

How to perform a fade animation on Activity transition?

you can also use this code in your style.xml file so you don't need to write anything else in your activity.java

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>

<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>

Set folder browser dialog start location

To set the directory selected path and the retrieve the new directory:

dlgBrowseForLogDirectory.SelectedPath = m_LogDirectory;
if (dlgBrowseForLogDirectory.ShowDialog() == DialogResult.OK)
{
     txtLogDirectory.Text = dlgBrowseForLogDirectory.SelectedPath;
}

How to display Woocommerce product price by ID number on a custom page?

Other answers work, but

To get the full/default price:

$product->get_price_html();

Cross-Origin Request Headers(CORS) with PHP headers

add this code in .htaccess

add custom authentication key's in header like app_key,auth_key..etc

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers: "customKey1,customKey2, headers, Origin, X-Requested-With, Content-Type, Accept, Authorization"

When to use the different log levels

I totally agree with the others, and think that GrayWizardx said it best.

All that I can add is that these levels generally correspond to their dictionary definitions, so it can't be that hard. If in doubt, treat it like a puzzle. For your particular project, think of everything that you might want to log.

Now, can you figure out what might be fatal? You know what fatal means, don't you? So, which items on your list are fatal.

Ok, that's fatal dealt with, now let's look at errors ... rinse and repeat.

Below Fatal, or maybe Error, I would suggest that more information is always better than less, so err "upwards". Not sure if it's Info or Warning? Then make it a warning.

I do think that Fatal and error ought to be clear to all of us. The others might be fuzzier, but it is arguably less vital to get them right.

Here are some examples:

Fatal - can't allocate memory, database, etc - can't continue.

Error - no reply to message, transaction aborted, can't save file, etc.

Warning - resource allocation reaches X% (say 80%) - that is a sign that you might want to re-dimension your.

Info - user logged in/out, new transaction, file crated, new d/b field, or field deleted.

Debug - dump of internal data structure, Anything Trace level with file name & line number.
Trace - action succeeded/failed, d/b updated.

How to differentiate single click event and double click event?

You need to use a timeout to check if there is an another click after the first click.

Here is the trick:

// Author:  Jacek Becela
// Source:  http://gist.github.com/399624
// License: MIT

jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
  return this.each(function(){
    var clicks = 0, self = this;
    jQuery(this).click(function(event){
      clicks++;
      if (clicks == 1) {
        setTimeout(function(){
          if(clicks == 1) {
            single_click_callback.call(self, event);
          } else {
            double_click_callback.call(self, event);
          }
          clicks = 0;
        }, timeout || 300);
      }
    });
  });
}

Usage:

$("button").single_double_click(function () {
  alert("Try double-clicking me!")
}, function () {
  alert("Double click detected, I'm hiding")
  $(this).hide()
})
<button>Click Me!</button>

EDIT:

As stated below, prefer using the native dblclick event: http://www.quirksmode.org/dom/events/click.html

Or the one provided by jQuery: http://api.jquery.com/dblclick/

How to apply a CSS filter to a background image

Of course, this is not a CSS-solution, but you can use the CDN Proton with filter:

body {
    background: url('https://i0.wp.com/IMAGEURL?w=600&filter=blurgaussian&smooth=1');
}

It is from https://developer.wordpress.com/docs/photon/api/#filter

Difference between abstract class and interface in Python

For completeness, we should mention PEP3119 where ABC was introduced and compared with interfaces, and original Talin's comment.

The abstract class is not perfect interface:

  • belongs to the inheritance hierarchy
  • is mutable

But if you consider writing it your own way:

def some_function(self):
     raise NotImplementedError()

interface = type(
    'your_interface', (object,),
    {'extra_func': some_function,
     '__slots__': ['extra_func', ...]
     ...
     '__instancecheck__': your_instance_checker,
     '__subclasscheck__': your_subclass_checker
     ...
    }
)

ok, rather as a class
or as a metaclass
and fighting with python to achieve the immutable object
and doing refactoring
...

you'll quite fast realize that you're inventing the wheel to eventually achieve abc.ABCMeta

abc.ABCMeta was proposed as a useful addition of the missing interface functionality, and that's fair enough in a language like python.

Certainly, it was able to be enhanced better whilst writing version 3, and adding new syntax and immutable interface concept ...

Conclusion:

The abc.ABCMeta IS "pythonic" interface in python

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

Guava Documentation

The JDK provides Collections.unmodifiableXXX methods, but in our opinion, these can be unwieldy and verbose; unpleasant to use everywhere you want to make defensive copies unsafe: the returned collections are only truly immutable if nobody holds a reference to the original collection inefficient: the data structures still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

In the introduction of Bootstrap it states which imports you need to add. https://getbootstrap.com/docs/4.0/getting-started/introduction/#quick-start

You have to add some scripts in order to get bootstrap fully working. It's important that you include them in this exact order. Popper.js is one of them:

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>

What's the difference between a mock & stub?

I was reading The Art of Unit Testing, and stumbled upon the following definition:

A fake is a generic term that can be used to describe either a stub or a mock object (handwritten or otherwise), because they both look like the real object. Whether a fake is a stub or a mock depends on how it's used in the current test. if it's used to check an interaction (asserted against), it's a mock object. Otherwise, it's a stub.

Adding backslashes without escaping [Python]

The extra backslash is not actually added; it's just added by the repr() function to indicate that it's a literal backslash. The Python interpreter uses the repr() function (which calls __repr__() on the object) when the result of an expression needs to be printed:

>>> '\\'
'\\'
>>> print '\\'
\
>>> print '\\'.__repr__()
'\\'

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

Hive: Convert String to Integer

If the value is between –2147483648 and 2147483647, cast(string_filed as int) will work. else cast(string_filed as bigint) will work

    hive> select cast('2147483647' as int);
    OK
    2147483647
    
    hive> select cast('2147483648' as int);
    OK
    NULL
    
    hive> select cast('2147483648' as bigint);
    OK
    2147483648

How do I make HttpURLConnection use a proxy?

Since java 1.5 you can also pass a java.net.Proxy instance to the openConnection(proxy) method:

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

If your proxy requires authentication it will give you response 407.

In this case you'll need the following code:

    Authenticator authenticator = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication("user",
                    "password".toCharArray()));
        }
    };
    Authenticator.setDefault(authenticator);

How to check if a char is equal to an empty space?

Character.isSpaceChar(c) || Character.isWhitespace(c) worked for me.

SQL User Defined Function Within Select

Yes, you can do almost that:

SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...

Multi-gradient shapes

I don't think you can do this in XML (at least not in Android), but I've found a good solution posted here that looks like it'd be a great help!

ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
    @Override
    public Shader resize(int width, int height) {
        LinearGradient lg = new LinearGradient(0, 0, width, height,
            new int[]{Color.GREEN, Color.GREEN, Color.WHITE, Color.WHITE},
            new float[]{0,0.5f,.55f,1}, Shader.TileMode.REPEAT);
        return lg;
    }
};

PaintDrawable p=new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);

Basically, the int array allows you to select multiple color stops, and the following float array defines where those stops are positioned (from 0 to 1). You can then, as stated, just use this as a standard Drawable.

Edit: Here's how you could use this in your scenario. Let's say you have a Button defined in XML like so:

<Button
    android:id="@+id/thebutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Press Me!"
    />

You'd then put something like this in your onCreate() method:

Button theButton = (Button)findViewById(R.id.thebutton);
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
    @Override
    public Shader resize(int width, int height) {
        LinearGradient lg = new LinearGradient(0, 0, 0, theButton.getHeight(),
            new int[] { 
                Color.LIGHT_GREEN, 
                Color.WHITE, 
                Color.MID_GREEN, 
                Color.DARK_GREEN }, //substitute the correct colors for these
            new float[] {
                0, 0.45f, 0.55f, 1 },
            Shader.TileMode.REPEAT);
         return lg;
    }
};
PaintDrawable p = new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);
theButton.setBackground((Drawable)p);

I cannot test this at the moment, this is code from my head, but basically just replace, or add stops for the colors that you need. Basically, in my example, you would start with a light green, fade to white slightly before the center (to give a fade, rather than a harsh transition), fade from white to mid green between 45% and 55%, then fade from mid green to dark green from 55% to the end. This may not look exactly like your shape (Right now, I have no way of testing these colors), but you can modify this to replicate your example.

Edit: Also, the 0, 0, 0, theButton.getHeight() refers to the x0, y0, x1, y1 coordinates of the gradient. So basically, it starts at x = 0 (left side), y = 0 (top), and stretches to x = 0 (we're wanting a vertical gradient, so no left to right angle is necessary), y = the height of the button. So the gradient goes at a 90 degree angle from the top of the button to the bottom of the button.

Edit: Okay, so I have one more idea that works, haha. Right now it works in XML, but should be doable for shapes in Java as well. It's kind of complex, and I imagine there's a way to simplify it into a single shape, but this is what I've got for now:

green_horizontal_gradient.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
    <corners
        android:radius="3dp"
        />
    <gradient
        android:angle="0"
        android:startColor="#FF63a34a"
        android:endColor="#FF477b36"
        android:type="linear"
        />    
</shape>

half_overlay.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
    <solid
        android:color="#40000000"
        />
</shape>

layer_list.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <item
        android:drawable="@drawable/green_horizontal_gradient"
        android:id="@+id/green_gradient"
        />
    <item
        android:drawable="@drawable/half_overlay"
        android:id="@+id/half_overlay"
        android:top="50dp"
        />
</layer-list>

test.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    >
    <TextView
        android:id="@+id/image_test"
        android:background="@drawable/layer_list"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:gravity="center"
        android:text="Layer List Drawable!"
        android:textColor="@android:color/white"
        android:textStyle="bold"
        android:textSize="26sp"     
        />
</RelativeLayout>

Okay, so basically I've created a shape gradient in XML for the horizontal green gradient, set at a 0 degree angle, going from the top area's left green color, to the right green color. Next, I made a shape rectangle with a half transparent gray. I'm pretty sure that could be inlined into the layer-list XML, obviating this extra file, but I'm not sure how. But okay, then the kind of hacky part comes in on the layer_list XML file. I put the green gradient as the bottom layer, then put the half overlay as the second layer, offset from the top by 50dp. Obviously you'd want this number to always be half of whatever your view size is, though, and not a fixed 50dp. I don't think you can use percentages, though. From there, I just inserted a TextView into my test.xml layout, using the layer_list.xml file as my background. I set the height to 100dp (twice the size of the offset of the overlay), resulting in the following:

alt text

Tada!

One more edit: I've realized you can just embed the shapes into the layer list drawable as items, meaning you don't need 3 separate XML files any more! You can achieve the same result combining them like so:

layer_list.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <item>
        <shape
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle"
            >
            <corners
                android:radius="3dp"
                />
            <gradient
                android:angle="0"
                android:startColor="#FF63a34a"
                android:endColor="#FF477b36"
                android:type="linear"
                />    
        </shape>
    </item>
    <item
        android:top="50dp" 
        >
        <shape
            android:shape="rectangle"
            >
            <solid
                android:color="#40000000"
                />
        </shape>            
    </item>
</layer-list>

You can layer as many items as you like this way! I may try to play around and see if I can get a more versatile result through Java.

I think this is the last edit...: Okay, so you can definitely fix the positioning through Java, like the following:

    TextView tv = (TextView)findViewById(R.id.image_test);
    LayerDrawable ld = (LayerDrawable)tv.getBackground();
    int topInset = tv.getHeight() / 2 ; //does not work!
    ld.setLayerInset(1, 0, topInset, 0, 0);
    tv.setBackgroundDrawable(ld);

However! This leads to yet another annoying problem in that you cannot measure the TextView until after it has been drawn. I'm not quite sure yet how you can accomplish this...but manually inserting a number for topInset does work.

I lied, one more edit

Okay, found out how to manually update this layer drawable to match the height of the container, full description can be found here. This code should go in your onCreate() method:

final TextView tv = (TextView)findViewById(R.id.image_test);
        ViewTreeObserver vto = tv.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                LayerDrawable ld = (LayerDrawable)tv.getBackground();
                ld.setLayerInset(1, 0, tv.getHeight() / 2, 0, 0);
            }
        });

And I'm done! Whew! :)

How to display and hide a div with CSS?

Html Code :

    <a id="f">Show First content!</a>
    <br/>
    <a id="s">Show Second content!!</a>
    <div class="a">Default Content</div>
    <div class="ab hideDiv">First content</div>
    <div class="abc hideDiv">Second content</div>

Script code:

$(document).ready(function() {
    $("#f").mouseover(function(){
        $('.a,.abc').addClass('hideDiv');
        $('.ab').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });

    $("#s").mouseover(function(){
        $('.a,.ab').addClass('hideDiv');
        $('.abc').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });
});

css code:

.hideDiv
{
    display:none;
}

Create a folder if it doesn't already exist

You can try also:

$dirpath = "path/to/dir";
$mode = "0764";
is_dir($dirpath) || mkdir($dirpath, $mode, true);

Regular expression to match characters at beginning of line only

^CTR

or

^CTR.*

edit:

To be more clear: ^CTR will match start of line and those chars. If all you want to do is match for a line itself (and already have the line to use), then that is all you really need. But if this is the case, you may be better off using a prefab substr() type function. I don't know, what language are you are using. But if you are trying to match and grab the line, you will need something like .* or .*$ or whatever, depending on what language/regex function you are using.