Programs & Examples On #Roboguice

Roboguice brings the power and testability of using the Google Guice dependency injection framework to Android application development.

Communicating between a fragment and an activity - best practices

It is implemented by a Callback interface:

First of all, we have to make an interface:

public interface UpdateFrag {
     void updatefrag();
}

In the Activity do the following code:

UpdateFrag updatfrag ;

public void updateApi(UpdateFrag listener) {
        updatfrag = listener;
}

from the event from where the callback has to fire in the Activity:

updatfrag.updatefrag();

In the Fragment implement the interface in CreateView do the following code:

 ((Home)getActivity()).updateApi(new UpdateFrag() {
        @Override
        public void updatefrag() {
              .....your stuff......
        }
 });

Changing background colour of tr element on mouseover

Try it

<!- HTML -->
<tr onmouseover="mOvr(this,'#ffa');" onmouseout="mOut(this,'#FFF');">

<script>
function mOvr(src,clrOver) { 
  if (!src.contains(event.fromElement)) { 
  src.bgColor = clrOver; 
  } 
} 
function mOut(src,clrIn) { 
  if (!src.contains(event.toElement)) { 
  src.bgColor = clrIn; 
  } 
} 
</script>

How to upgrade docker container after its image changed

This is something I've also been struggling with for my own images. I have a server environment from which I create a Docker image. When I update the server, I'd like all users who are running containers based on my Docker image to be able to upgrade to the latest server.

Ideally, I'd prefer to generate a new version of the Docker image and have all containers based on a previous version of that image automagically update to the new image "in place." But this mechanism doesn't seem to exist.

So the next best design I've been able to come up with so far is to provide a way to have the container update itself--similar to how a desktop application checks for updates and then upgrades itself. In my case, this will probably mean crafting a script that involves Git pulls from a well-known tag.

The image/container doesn't actually change, but the "internals" of that container change. You could imagine doing the same with apt-get, yum, or whatever is appropriate for you environment. Along with this, I'd update the myserver:latest image in the registry so any new containers would be based on the latest image.

I'd be interested in hearing whether there is any prior art that addresses this scenario.

Reportviewer tool missing in visual studio 2017 RC

If you're like me and tried a few of these methods and are stuck at the point that you have the control in the toolbox and can draw it on the form but it disappears from the form and puts it down in the components, then simply edit the designer and add the following in the appropriate area of InitializeComponent() to make it visible:

this.Controls.Add(this.reportViewer1);

or

[ContainerControl].Controls.Add(this.reportViewer1);

You'll also need to make adjustments to the location and size manually after you've added the control.

Not a great answer for sure, but if you're stuck and just need to get work done for now until you have more time to figure it out, it should help.

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

how to set select element as readonly ('disabled' doesnt pass select value on server)

see this answer - HTML form readonly SELECT tag/input

You should keep the select element disabled but also add another hidden input with the same name and value.

If you reenable your SELECT, you should copy it's value to the hidden input in an onchange event.

see this fiddle to demnstrate how to extract the selected value in a disabled select into a hidden field that will be submitted in the form.

<select disabled="disabled" id="sel_test">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

<input type="hidden" id="hdn_test" />
<div id="output"></div>

$(function(){
    var select_val = $('#sel_test option:selected').val();
    $('#hdn_test').val(select_val);
    $('#output').text('Selected value is: ' + select_val);
});

hope that helps.

How do I pick randomly from an array?

myArray.sample(x) can also help you to get x random elements from the array.

Redirect from asp.net web api post action

You can check this

[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{

   string url = "https://localhost:44305/Templates/ReportPage.html";

   System.Uri uri = new System.Uri(url);

   return Redirect(uri);
}

Force index use in Oracle

You can use:

WITH index = ...

more info

How to frame two for loops in list comprehension python

This should do it:

[entry for tag in tags for entry in entries if tag in entry]

Determine what attributes were changed in Rails after_save callback?

You just add an accessor who define what you change

class Post < AR::Base
  attr_reader :what_changed

  before_filter :what_changed?

  def what_changed?
    @what_changed = changes || []
  end

  after_filter :action_on_changes

  def action_on_changes
    @what_changed.each do |change|
      p change
    end
  end
end

How to deal with persistent storage (e.g. databases) in Docker

As of Docker Compose 1.6, there is now improved support for data volumes in Docker Compose. The following compose file will create a data image which will persist between restarts (or even removal) of parent containers:

Here is the blog announcement: Compose 1.6: New Compose file for defining networks and volumes

Here's an example compose file:

version: "2"

services:
  db:
    restart: on-failure:10
    image: postgres:9.4
    volumes:
      - "db-data:/var/lib/postgresql/data"
  web:
    restart: on-failure:10
    build: .
    command: gunicorn mypythonapp.wsgi:application -b :8000 --reload
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    links:
      - db

volumes:
  db-data:

As far as I can understand: This will create a data volume container (db_data) which will persist between restarts.

If you run: docker volume ls you should see your volume listed:

local               mypthonapp_db-data
...

You can get some more details about the data volume:

docker volume inspect mypthonapp_db-data
[
  {
    "Name": "mypthonapp_db-data",
    "Driver": "local",
    "Mountpoint": "/mnt/sda1/var/lib/docker/volumes/mypthonapp_db-data/_data"
  }
]

Some testing:

# Start the containers
docker-compose up -d

# .. input some data into the database
docker-compose run --rm web python manage.py migrate
docker-compose run --rm web python manage.py createsuperuser
...

# Stop and remove the containers:
docker-compose stop
docker-compose rm -f

# Start it back up again
docker-compose up -d

# Verify the data is still there
...
(it is)

# Stop and remove with the -v (volumes) tag:

docker-compose stop
docker=compose rm -f -v

# Up again ..
docker-compose up -d

# Check the data is still there:
...
(it is).

Notes:

  • You can also specify various drivers in the volumes block. For example, You could specify the Flocker driver for db_data:

    volumes:
      db-data:
        driver: flocker
    
  • As they improve the integration between Docker Swarm and Docker Compose (and possibly start integrating Flocker into the Docker eco-system (I heard a rumor that Docker has bought Flocker), I think this approach should become increasingly powerful.

Disclaimer: This approach is promising, and I'm using it successfully in a development environment. I would be apprehensive to use this in production just yet!

How can I get customer details from an order in WooCommerce?

2017-2020 WooCommerce versions 3+ and CRUD Objects

1). You can use getter methods from WC_Order and WC_Abstract_Order classes on the WC_Order object instance like:

// Get an instance of the WC_Order Object from the Order ID (if required)
$order = wc_get_order( $order_id );

// Get the Customer ID (User ID)
$customer_id = $order->get_customer_id(); // Or $order->get_user_id();

// Get the WP_User Object instance
$user = $order->get_user();

// Get the WP_User roles and capabilities
$user_roles = $user->roles;

// Get the Customer billing email
$billing_email  = $order->get_billing_email();

// Get the Customer billing phone
$billing_phone  = $order->get_billing_phone();

// Customer billing information details
$billing_first_name = $order->get_billing_first_name();
$billing_last_name  = $order->get_billing_last_name();
$billing_company    = $order->get_billing_company();
$billing_address_1  = $order->get_billing_address_1();
$billing_address_2  = $order->get_billing_address_2();
$billing_city       = $order->get_billing_city();
$billing_state      = $order->get_billing_state();
$billing_postcode   = $order->get_billing_postcode();
$billing_country    = $order->get_billing_country();

// Customer shipping information details
$shipping_first_name = $order->get_shipping_first_name();
$shipping_last_name  = $order->get_shipping_last_name();
$shipping_company    = $order->get_shipping_company();
$shipping_address_1  = $order->get_shipping_address_1();
$shipping_address_2  = $order->get_shipping_address_2();
$shipping_city       = $order->get_shipping_city();
$shipping_state      = $order->get_shipping_state();
$shipping_postcode   = $order->get_shipping_postcode();
$shipping_country    = $order->get_shipping_country();

2). You can also use the WC_Order get_data() method, to get an unprotected data array from Order meta data like:

// Get an instance of the WC_Order Object from the Order ID (if required)
$order = wc_get_order( $order_id );

// Get the Order meta data in an unprotected array
$data  = $order->get_data(); // The Order data

$order_id        = $data['id'];
$order_parent_id = $data['parent_id'];

// Get the Customer ID (User ID)
$customer_id     = $data['customer_id'];

## BILLING INFORMATION:

$billing_email      = $data['billing']['email'];
$billing_phone      = $order_data['billing']['phone'];

$billing_first_name = $data['billing']['first_name'];
$billing_last_name  = $data['billing']['last_name'];
$billing_company    = $data['billing']['company'];
$billing_address_1  = $data['billing']['address_1'];
$billing_address_2  = $data['billing']['address_2'];
$billing_city       = $data['billing']['city'];
$billing_state      = $data['billing']['state'];
$billing_postcode   = $data['billing']['postcode'];
$billing_country    = $data['billing']['country'];

## SHIPPING INFORMATION:

$shipping_first_name = $data['shipping']['first_name'];
$shipping_last_name  = $data['shipping']['last_name'];
$shipping_company    = $data['shipping']['company'];
$shipping_address_1  = $data['shipping']['address_1'];
$shipping_address_2  = $data['shipping']['address_2'];
$shipping_city       = $data['shipping']['city'];
$shipping_state      = $data['shipping']['state'];
$shipping_postcode   = $data['shipping']['postcode'];
$shipping_country    = $data['shipping']['country'];

Now to get the user account data (from an Order ID):

1). You can use the methods from WC_Customer Class:

// Get the user ID from an Order ID
$user_id = get_post_meta( $order_id, '_customer_user', true );

// Get an instance of the WC_Customer Object from the user ID
$customer = new WC_Customer( $user_id );

$username     = $customer->get_username(); // Get username
$user_email   = $customer->get_email(); // Get account email
$first_name   = $customer->get_first_name();
$last_name    = $customer->get_last_name();
$display_name = $customer->get_display_name();

// Customer billing information details (from account)
$billing_first_name = $customer->get_billing_first_name();
$billing_last_name  = $customer->get_billing_last_name();
$billing_company    = $customer->get_billing_company();
$billing_address_1  = $customer->get_billing_address_1();
$billing_address_2  = $customer->get_billing_address_2();
$billing_city       = $customer->get_billing_city();
$billing_state      = $customer->get_billing_state();
$billing_postcode   = $customer->get_billing_postcode();
$billing_country    = $customer->get_billing_country();

// Customer shipping information details (from account)
$shipping_first_name = $customer->get_shipping_first_name();
$shipping_last_name  = $customer->get_shipping_last_name();
$shipping_company    = $customer->get_shipping_company();
$shipping_address_1  = $customer->get_shipping_address_1();
$shipping_address_2  = $customer->get_shipping_address_2();
$shipping_city       = $customer->get_shipping_city();
$shipping_state      = $customer->get_shipping_state();
$shipping_postcode   = $customer->get_shipping_postcode();
$shipping_country    = $customer->get_shipping_country();

2). The WP_User object (WordPress):

// Get the user ID from an Order ID
$user_id = get_post_meta( $order_id, '_customer_user', true );

// Get the WP_User instance Object
$user = new WP_User( $user_id );

$username     = $user->username; // Get username
$user_email   = $user->email; // Get account email
$first_name   = $user->first_name;
$last_name    = $user->last_name;
$display_name = $user->display_name;

// Customer billing information details (from account)
$billing_first_name = $user->billing_first_name;
$billing_last_name  = $user->billing_last_name;
$billing_company    = $user->billing_company;
$billing_address_1  = $user->billing_address_1;
$billing_address_2  = $user->billing_address_2;
$billing_city       = $user->billing_city;
$billing_state      = $user->billing_state;
$billing_postcode   = $user->billing_postcode;
$billing_country    = $user->billing_country;

// Customer shipping information details (from account)
$shipping_first_name = $user->shipping_first_name;
$shipping_last_name  = $user->shipping_last_name;
$shipping_company    = $user->shipping_company;
$shipping_address_1  = $user->shipping_address_1;
$shipping_address_2  = $user->shipping_address_2;
$shipping_city       = $user->shipping_city;
$shipping_state      = $user->shipping_state;
$shipping_postcode   = $user->shipping_postcode;
$shipping_country    = $user->shipping_country;

Related: How to get WooCommerce order details

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Based on the hint and link provided in Simone Giannis answer, this is my hack to fix this.

I am testing on uri.getAuthority(), because UNC path will report an Authority. This is a bug - so I rely on the existence of a bug, which is evil, but it apears as if this will stay forever (since Java 7 solves the problem in java.nio.Paths).

Note: In my context I will receive absolute paths. I have tested this on Windows and OS X.

(Still looking for a better way to do it)

package com.christianfries.test;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

public class UNCPathTest {

    public static void main(String[] args) throws MalformedURLException, URISyntaxException {
        UNCPathTest upt = new UNCPathTest();

        upt.testURL("file://server/dir/file.txt");  // Windows UNC Path

        upt.testURL("file:///Z:/dir/file.txt");     // Windows drive letter path

        upt.testURL("file:///dir/file.txt");        // Unix (absolute) path
    }

    private void testURL(String urlString) throws MalformedURLException, URISyntaxException {
        URL url = new URL(urlString);
        System.out.println("URL is: " + url.toString());

        URI uri = url.toURI();
        System.out.println("URI is: " + uri.toString());

        if(uri.getAuthority() != null && uri.getAuthority().length() > 0) {
            // Hack for UNC Path
            uri = (new URL("file://" + urlString.substring("file:".length()))).toURI();
        }

        File file = new File(uri);
        System.out.println("File is: " + file.toString());

        String parent = file.getParent();
        System.out.println("Parent is: " + parent);

        System.out.println("____________________________________________________________");
    }

}

How to get base url with jquery or javascript?

Here's a short one:

_x000D_
_x000D_
const base = new URL('/', location.href).href;

console.log(base);
_x000D_
_x000D_
_x000D_

How to get PID of process I've just started within java program?

Include jna (both "JNA" and "JNA Platform") in your library and use this function:

import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinNT;
import java.lang.reflect.Field;

public static long getProcessID(Process p)
    {
        long result = -1;
        try
        {
            //for windows
            if (p.getClass().getName().equals("java.lang.Win32Process") ||
                   p.getClass().getName().equals("java.lang.ProcessImpl")) 
            {
                Field f = p.getClass().getDeclaredField("handle");
                f.setAccessible(true);              
                long handl = f.getLong(p);
                Kernel32 kernel = Kernel32.INSTANCE;
                WinNT.HANDLE hand = new WinNT.HANDLE();
                hand.setPointer(Pointer.createConstant(handl));
                result = kernel.GetProcessId(hand);
                f.setAccessible(false);
            }
            //for unix based operating systems
            else if (p.getClass().getName().equals("java.lang.UNIXProcess")) 
            {
                Field f = p.getClass().getDeclaredField("pid");
                f.setAccessible(true);
                result = f.getLong(p);
                f.setAccessible(false);
            }
        }
        catch(Exception ex)
        {
            result = -1;
        }
        return result;
    }

You can also download JNA from here and JNA Platform from here.

What is the use of DesiredCapabilities in Selenium WebDriver?

I know I am very late to answer this question.
But would like to add for further references to the give answers.
DesiredCapabilities are used like setting your config with key-value pair.
Below is an example related to Appium used for Automating Mobile platforms like Android and IOS.
So we generally set DesiredCapabilities for conveying our WebDriver for specific things we will be needing to run our test to narrow down the performance and to increase the accuracy.

So we set our DesiredCapabilities as:

// Created object of DesiredCapabilities class.
DesiredCapabilities capabilities = new DesiredCapabilities();

// Set android deviceName desired capability. Set your device name.
capabilities.setCapability("deviceName", "your Device Name");

// Set BROWSER_NAME desired capability.
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome");

// Set android VERSION desired capability. Set your mobile device's OS version.
capabilities.setCapability(CapabilityType.VERSION, "5.1");

// Set android platformName desired capability. It's Android in our case here.
capabilities.setCapability("platformName", "Android");

// Set android appPackage desired capability.

//You need to check for your appPackage Name for your app, you can use this app for that APK INFO

// Set your application's appPackage if you are using any other app. 
capabilities.setCapability("appPackage", "com.android.appPackageName");

// Set android appActivity desired capability. You can use the same app for finding appActivity of your app
capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

This DesiredCapabilities are very specific to Appium on Android Platform. For more you can refer to the official site of Selenium desiredCapabilities class

Concatenate a vector of strings/character

Here is a little utility function that collapses a named or unnamed list of values to a single string for easier printing. It will also print the code line itself. It's from my list examples in R page.

Generate some lists named or unnamed:

# Define Lists
ls_num <- list(1,2,3)
ls_str <- list('1','2','3')
ls_num_str <- list(1,2,'3')

# Named Lists
ar_st_names <- c('e1','e2','e3')
ls_num_str_named <- ls_num_str
names(ls_num_str_named) <- ar_st_names

# Add Element to Named List
ls_num_str_named$e4 <- 'this is added'

Here is the a function that will convert named or unnamed list to string:

ffi_lst2str <- function(ls_list, st_desc, bl_print=TRUE) {

  # string desc
  if(missing(st_desc)){
    st_desc <- deparse(substitute(ls_list))
  }

  # create string
  st_string_from_list = paste0(paste0(st_desc, ':'), 
                               paste(names(ls_list), ls_list, sep="=", collapse=";" ))

  if (bl_print){
    print(st_string_from_list)
  }
}

Testing the function with the lists created prior:

> ffi_lst2str(ls_num)
[1] "ls_num:=1;=2;=3"
> ffi_lst2str(ls_str)
[1] "ls_str:=1;=2;=3"
> ffi_lst2str(ls_num_str)
[1] "ls_num_str:=1;=2;=3"
> ffi_lst2str(ls_num_str_named)
[1] "ls_num_str_named:e1=1;e2=2;e3=3;e4=this is added"

Testing the function with subset of list elements:

> ffi_lst2str(ls_num_str_named[c('e2','e3','e4')])
[1] "ls_num_str_named[c(\"e2\", \"e3\", \"e4\")]:e2=2;e3=3;e4=this is added"
> ffi_lst2str(ls_num[2:3])
[1] "ls_num[2:3]:=2;=3"
> ffi_lst2str(ls_str[2:3])
[1] "ls_str[2:3]:=2;=3"
> ffi_lst2str(ls_num_str[2:4])
[1] "ls_num_str[2:4]:=2;=3;=NULL"
> ffi_lst2str(ls_num_str_named[c('e2','e3','e4')])
[1] "ls_num_str_named[c(\"e2\", \"e3\", \"e4\")]:e2=2;e3=3;e4=this is added"

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

Array of PHP Objects

Another intuitive solution could be:

class Post
{
    public $title;
    public $date;
}

$posts = array();

$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';

$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';

foreach ($posts as $post) {
  echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}

How can I specify the required Node.js version in package.json?

A Mocha test case example:

describe('Check version of node', function () {
    it('Should test version assert', async function () {

            var version = process.version;
            var check = parseFloat(version.substr(1,version.length)) > 12.0;
            console.log("version: "+version);
            console.log("check: " +check);         
            assert.equal(check, true);
    });});

INSERT ... ON DUPLICATE KEY (do nothing)

Use ON DUPLICATE KEY UPDATE ...,
Negative : because the UPDATE uses resources for the second action.

Use INSERT IGNORE ...,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.

SELECT using 'CASE' in SQL

Try this.

SELECT 
  CASE 
     WHEN FRUIT = 'A' THEN 'APPLE'
     WHEN FRUIT = 'B' THEN 'BANANA'
     ELSE 'UNKNOWN FRUIT'
  END AS FRUIT
FROM FRUIT_TABLE;

apache ProxyPass: how to preserve original IP address

This has a more elegant explanation and more than one possible solutions. http://kasunh.wordpress.com/2011/10/11/preserving-remote-iphost-while-proxying/

The post describes how to use one popular and one lesser known Apache modules to preserve host/ip while in a setup involving proxying.

Use mod_rpaf module, install and enable it in the backend server and add following directives in the module’s configuration. RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1

(2017 edit) Current location of mod_rpaf: https://github.com/gnif/mod_rpaf

how to write procedure to insert data in to the table in phpmyadmin?

This method work for me:

DELIMITER $$
DROP PROCEDURE IF EXISTS db.test $$
CREATE PROCEDURE db.test(IN id INT(12),IN NAME VARCHAR(255))
 BEGIN
 INSERT INTO USER VALUES(id,NAME);
 END$$
DELIMITER ;

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

From what I've learned with Alex Cowan in the course Continuous Delivery & DevOps, CI and CD is part of a product pipeline that consists in the time it goes from an Observations to a Released Product.

Alex Cowan's Product Pipeline, 2018

From Observations to Designs the goal is to get high quality testable ideas. This part of the process is considered Continuous Design.

What happens after, when we go from the Code onwards, it's considered a Continuous Delivery capability whose aim is to execute the ideas and release to the customer very fast (you can read Jez Humble's book Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation for more details). The following pipeline explains which steps Continuous Integration (CI) and Continuous Delivery (CD) consist of.

Alex Cowan's CI/CD

Continuous Integration, as Mattias Petter Johansson explains,

is when a software team has habit of doing multiple merges per day and they have an automated verification system in place to check those merges for problems.

(you can watch the following two videos for a more pratical overview using CircleCI - Getting started with CircleCI - Continuous Integration P2 and Running CircleCI on Pull Request).

One can specify the CI/CD pipeline as following, that goes from New Code to a released Product.

Alex Cowan's Continuous Delivery Pipeline, 2018

The first three steps have to do with Tests, extending the boundary of what's being tested.

Continuous Deployment, on the other hand, is to handle the Deployment automatically. So, any code commit that passes the automated testing phase is automatically released into the production.

Note: This isn't necessarily what your pipelines should look like, yet they can serve as reference.

Separators for Navigation

Simply use the separator image as a background image on the li.

To get it to only appear in between list items, position the image to the left of the li, but not on the first one.

For example:

#nav li + li {
    background:url('seperator.gif') no-repeat top left;
    padding-left: 10px
}

This CSS adds the image to every list item that follows another list item - in other words all of them but the first.

NB. Be aware the adjacent selector (li + li) doesn't work in IE6, so you will have to just add the background image to the conventional li (with a conditional stylesheet) and perhaps apply a negative margin to one of the edges.

Android TextView Justify Text

While still not complete justified text, you can now balance line lengths using android:breakStrategy="balanced" from API 23 onwards

http://developer.android.com/reference/android/widget/TextView.html#attr_android:breakStrategy

"Non-static method cannot be referenced from a static context" error

Instance methods need to be called from an instance. Your setLoanItem method is an instance method (it doesn't have the modifier static), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this)).

You need to create an instance of the class before you can call the method on it:

Media media = new Media();
media.setLoanItem("Yes");

(Btw it would be better to use a boolean instead of a string containing "Yes".)

MySQL: Fastest way to count number of rows

If you need to get the count of the entire result set you can take following approach:

SELECT SQL_CALC_FOUND_ROWS * FROM table_name LIMIT 5;
SELECT FOUND_ROWS();

This isn't normally faster than using COUNT albeit one might think the opposite is the case because it's doing the calculation internally and doesn't send the data back to the user thus the performance improvement is suspected.

Doing these two queries is good for pagination for getting totals but not particularly for using WHERE clauses.

jQuery hide and show toggle div with plus and minus icon

Try something like this

jQuery

$('#toggle_icon').toggle(function() {

    $('#toggle_icon').text('-');
    $('#toggle_text').slideToggle();

}, function() {

    $('#toggle_icon').text('+');
    $('#toggle_text').slideToggle();

});

HTML

<a href="#" id="toggle_icon">+</a>

<div id="toggle_text" style="display: none">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
</div>

DEMO

Concatenating two one-dimensional NumPy arrays

There are several possibilities for concatenating 1D arrays, e.g.,

numpy.r_[a, a],
numpy.stack([a, a]).reshape(-1),
numpy.hstack([a, a]),
numpy.concatenate([a, a])

All those options are equally fast for large arrays; for small ones, concatenate has a slight edge:

enter image description here

The plot was created with perfplot:

import numpy
import perfplot

perfplot.show(
    setup=lambda n: numpy.random.rand(n),
    kernels=[
        lambda a: numpy.r_[a, a],
        lambda a: numpy.stack([a, a]).reshape(-1),
        lambda a: numpy.hstack([a, a]),
        lambda a: numpy.concatenate([a, a]),
    ],
    labels=["r_", "stack+reshape", "hstack", "concatenate"],
    n_range=[2 ** k for k in range(19)],
    xlabel="len(a)",
)

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

Being new to this myself, here's what I did:

I'm using MS Visual Studio 2010 Pro.

  1. Download and install the OpenXML SDK
  2. Within my project in Visual Studio, select "Project" then "Add Reference"
  3. Select the "Browse" tab
  4. In the "Look in:" pull down, navigate to: C:\Program Files(x86)\Open XML SDK\V2.0\lib and select the "DocumentFormat.OpenXml.dll
  5. Hit OK
  6. In the "Solution Explorer" (on the right for me), the "References" folder now shows the DocumentFormat.OpenXML library.
  7. Right-click on it and select Properties
  8. In the Properties panel, change "Copy Local" to "True".

You should be off and running now using the DocumentFormat classes.

Correct way to pause a Python program

So, I found this to work very well in my coding endeavors. I simply created a function at the very beginning of my program,

def pause():
    programPause = raw_input("Press the <ENTER> key to continue...")

and now I can use the pause() function whenever I need to just as if I was writing a batch file. For example, in a program such as this:

import os
import system

def pause():
    programPause = raw_input("Press the <ENTER> key to continue...")

print("Think about what you ate for dinner last night...")
pause()

Now obviously this program has no objective and is just for example purposes, but you can understand precisely what I mean.

NOTE: For Python 3, you will need to use input as opposed to raw_input

How to convert a Hibernate proxy to a real entity object

The another workaround is to call

Hibernate.initialize(extractedObject.getSubojbectToUnproxy());

Just before closing the session.

Why can't I find SQL Server Management Studio after installation?

It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

and the one for 64 bit WITH the management tools (management studio) is here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

Format the date using Ruby on Rails

Have a look at localize, or l

eg:

l Time.at(1100897479)

SQL command to display history of queries

You can see the history from ~/.mysql_history. However the content of the file is encoded by wctomb. To view the content:

shell> cat ~/.mysql_history | python2.7 -c "import sys; print(''.join([l.decode('unicode-escape') for l in sys.stdin]))"

Source:Check MySQL query history from command line

How can I run code on a background thread on Android?

Simple 3-Liner

A simple way of doing this that I found as a comment by @awardak in Brandon Rude's answer:

new Thread( new Runnable() { @Override public void run() { 
  // Run whatever background code you want here.
} } ).start();

I'm not sure if, or how , this is better than using AsyncTask.execute but it seems to work for us. Any comments as to the difference would be appreciated.

Thanks, @awardak!

How to implement onBackPressed() in Fragments?

I just use findFragmentById and cast to the fragment and call a method that handles onBackpressed. This sample shows checking if this is the first step in order process if it is pop up a dialog fragment to confirm exit order.

@Override
    public void onBackPressed() {
        //check if first fragment in wizard is loaded, if true get abandon confirmation before going back
        OrderFragment frag =(OrderFragment)getSupportFragmentManager().findFragmentById(R.id.fragContainer);
        if (frag==null || (frag!=null && frag.getOrderStage()<1)){
            AlertDialogFragment.show(getSupportFragmentManager(), R.string.dialog_cancel_order,R.string.dialog_cancel_order_msg, R.string.dialog_cancel_order_pos,R.string.dialog_order_quiz_neg, DIALOG_ID_CANCEL);
        }else {
            super.onBackPressed();
        }
    }

Append text using StreamWriter

Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.

http://logging.apache.org/log4net/

How to access child's state in React?

Its 2020 and lots of you will come here looking for a similar solution but with Hooks ( They are great! ) and with latest approaches in terms of code cleanliness and syntax.

So as previous answers had stated, the best approach to this kind of problem is to hold the state outside of child component fieldEditor. You could do that in multiple ways.

The most "complex" is with global context (state) that both parent and children could access and modify. Its a great solution when components are very deep in the tree hierarchy and so its costly to send props in each level.

In this case I think its not worth it, and more simple approach will bring us the results we want, just using the powerful React.useState().

Approach with React.useState() hook, way simpler than with Class components

As said we will deal with changes and store the data of our child component fieldEditor in our parent fieldForm. To do that we will send a reference to the function that will deal and apply the changes to the fieldForm state, you could do that with:

function FieldForm({ fields }) {
  const [fieldsValues, setFieldsValues] = React.useState({});
  const handleChange = (event, fieldId) => {
    let newFields = { ...fieldsValues };
    newFields[fieldId] = event.target.value;

    setFieldsValues(newFields);
  };

  return (
    <div>
      {fields.map(field => (
        <FieldEditor
          key={field}
          id={field}
          handleChange={handleChange}
          value={fieldsValues[field]}
        />
      ))}
      <div>{JSON.stringify(fieldsValues)}</div>
    </div>
  );
}

Note that React.useState({}) will return an array with position 0 being the value specified on call (Empty object in this case), and position 1 being the reference to the function that modifies the value.

Now with the child component, FieldEditor, you don't even need to create a function with a return statement, a lean constant with an arrow function will do!

const FieldEditor = ({ id, value, handleChange }) => (
  <div className="field-editor">
    <input onChange={event => handleChange(event, id)} value={value} />
  </div>
);

Aaaaand we are done, nothing more, with just these two slime functional components we have our end goal "access" our child FieldEditor value and show it off in our parent.

You could check the accepted answer from 5 years ago and see how Hooks made React code leaner (By a lot!).

Hope my answer helps you learn and understand more about Hooks, and if you want to check a working example here it is.

Remove pattern from string with gsub

Just to point out that there is an approach using functions from the tidyverse, which I find more readable than gsub:

a %>% stringr::str_remove(pattern = ".*_")

Can Twitter Bootstrap alerts fade in as well as out?

I don't agree with the way that Bootstrap uses fade in (as seen in their documentation - http://v4-alpha.getbootstrap.com/components/alerts/), and my suggestion is to avoid the class names fade and in, and to avoid that pattern in general (which is currently seen in the top-rated answer to this question).

(1) The semantics are wrong - transitions are temporary, but the class names live on. So why should we name our classes fade and fade in? It should be faded and faded-in, so that when developers read the markup, it's clear that those elements were faded or faded-in. The Bootstrap team has already done away with hide for hidden, why is fade any different?

(2) Using 2 classes fade and in for a single transition pollutes the class space. And, it's not clear that fade and in are associated with one another. The in class looks like a completely independent class, like alert and alert-success.

The best solution is to use faded when the element has been faded out, and to replace that class with faded-in when the element has been faded in.

Alert Faded

So to answer the question. I think the alert markup, style, and logic should be written in the following manner. Note: Feel free to replace the jQuery logic, if you're using vanilla javascript.

HTML

<div id="saveAlert" class="alert alert-success">
  <a class="close" href="#">×</a>
  <p><strong>Well done!</strong> You successfully read this alert message.</p>
</div>

CSS

.faded {
  opacity: 0;
  transition: opacity 1s;
}

JQuery

$('#saveAlert .close').on('click', function () {

  $("#saveAlert")
    .addClass('faded');

});

Adding a directory to PATH in Ubuntu

you can set it in .bashrc

PATH=$PATH:/opt/ActiveTcl-8.5/bin;export PATH;

C compile : collect2: error: ld returned 1 exit status

generally this problem occurred when we have called a function which has not been define in the program file, so to sort out this problem check whether have you called such function which has not been define in the program file.

Make the current Git branch a master branch

If you are using eGit in Eclipse:

  • Right click on the project node.
  • Choose Team ? then Advanced ? then Rename branch
  • Then expand the remote tracking folder.
  • Choose the branch with the wrong name, then click the rename button, rename it to whatever the new name.
  • Choose the new master, then rename it to master.

how to count length of the JSON array element

First, there is no such thing as a JSON object. JSON is a string format that can be used as a representation of a Javascript object literal.

Since JSON is a string, Javascript will treat it like a string, and not like an object (or array or whatever you are trying to use it as.)

Here is a good JSON reference to clarify this difference:

http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/

So if you need accomplish the task mentioned in your question, you must convert the JSON string to an object or deal with it as a string, and not as a JSON array. There are several libraries to accomplish this. Look at http://www.json.org/js.html for a reference.

How do I properly 'printf' an integer and a string in C?

You're on the right track. Here's a corrected version:

char str[10];
int n;

printf("type a string: ");
scanf("%s %d", str, &n);

printf("%s\n", str);
printf("%d\n", n);

Let's talk through the changes:

  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.

How do I prevent 'git diff' from using a pager?

Use

git config --global core.pager cat

to get rid of a pager for all commands for all repositories.

You can also disable paging for single Git subcommands by using pager.<cmd> setting instead of core.pager, and you can change your settings per Git repository (omit --global).

See man git-config and search for pager.<cmd> for details.

What does "async: false" do in jQuery.ajax()?

One use case is to make an ajax call before the user closes the window or leaves the page. This would be like deleting some temporary records in the database before the user can navigate to another site or closes the browser.

 $(window).unload(
        function(){
            $.ajax({
            url: 'your url',
            global: false,
            type: 'POST',
            data: {},
            async: false, //blocks window close
            success: function() {}
        });
    });

Connection to SQL Server Works Sometimes

In my case, the parameter Persist Security Info=true with the user and password in connection string is causing the problem. Removing the parameter or set to false solve the problem.

What does the ??!??! operator do in C?

??! is a trigraph that translates to |. So it says:

!ErrorHasOccured() || HandleError();

which, due to short circuiting, is equivalent to:

if (ErrorHasOccured())
    HandleError();

Guru of the Week (deals with C++ but relevant here), where I picked this up.

Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.

From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):

The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.

Python: Number of rows affected by cursor.execute("SELECT ...)

From PEP 249, which is usually implemented by Python database APIs:

Cursor Objects should respond to the following methods and attributes:

[…]

.rowcount
This read-only attribute specifies the number of rows that the last .execute*() produced (for DQL statements like 'select') or affected (for DML statements like 'update' or 'insert').

But be careful—it goes on to say:

The attribute is -1 in case no .execute*() has been performed on the cursor or the rowcount of the last operation is cannot be determined by the interface. [7]

Note:
Future versions of the DB API specification could redefine the latter case to have the object return None instead of -1.

So if you've executed your statement, and it works, and you're certain your code will always be run against the same version of the same DBMS, this is a reasonable solution.

Zsh: Conda/Pip installs command not found

For Linux

  1. Open .bashrc
  2. Copy the code for conda initialize and paste it to .zshrc file
  3. Finally run source .zshrc

python: get directory two levels up

I don't yet see a viable answer for 2.7 which doesn't require installing additional dependencies and also starts from the file's directory. It's not nice as a single-line solution, but there's nothing wrong with using the standard utilities.

import os

grandparent_dir = os.path.abspath(  # Convert into absolute path string
    os.path.join(  # Current file's grandparent directory
        os.path.join(  # Current file's parent directory
            os.path.dirname(  # Current file's directory
                os.path.abspath(__file__)  # Current file path
            ),
            os.pardir
        ),
        os.pardir
    )
)

print grandparent_dir

And to prove it works, here I start out in ~/Documents/notes just so that I show the current directory doesn't influence outcome. I put the file grandpa.py with that script in a folder called "scripts". It crawls up to the Documents dir and then to the user dir on a Mac.

(testing)AlanSE-OSX:notes AlanSE$ echo ~/Documents/scripts/grandpa.py 
/Users/alancoding/Documents/scripts/grandpa.py
(testing)AlanSE-OSX:notes AlanSE$ python2.7 ~/Documents/scripts/grandpa.py 
/Users/alancoding

This is the obvious extrapolation of the answer for the parent dir. Better to use a general solution than a less-good solution in fewer lines.

Tools for making latex tables in R

Two utilities in package taRifx can be used in concert to produce multi-row tables of nested heirarchies.

library(datasets)
library(taRifx)
library(xtable)

test.by <- bytable(ChickWeight$weight, list( ChickWeight$Chick, ChickWeight$Diet) )
colnames(test.by) <- c('Diet','Chick','Mean Weight')
print(latex.table.by(test.by), include.rownames = FALSE, include.colnames = TRUE, sanitize.text.function = force)
#   then add \usepackage{multirow} to the preamble of your LaTeX document
#   for longtable support, add ,tabular.environment='longtable' to the print command (plus add in ,floating=FALSE), then \usepackage{longtable} to the LaTeX preamble

sample table output

How to inject JPA EntityManager using spring

Is it possible to have spring to inject the JPA entityManager object into my DAO class whitout extending JpaDaoSupport? if yes, does spring manage the transaction in this case?

This is documented black on white in 12.6.3. Implementing DAOs based on plain JPA:

It is possible to write code against the plain JPA without using any Spring dependencies, using an injected EntityManagerFactory or EntityManager. Note that Spring can understand @PersistenceUnit and @PersistenceContext annotations both at field and method level if a PersistenceAnnotationBeanPostProcessor is enabled. A corresponding DAO implementation might look like this (...)

And regarding transaction management, have a look at 12.7. Transaction Management:

Spring JPA allows a configured JpaTransactionManager to expose a JPA transaction to JDBC access code that accesses the same JDBC DataSource, provided that the registered JpaDialect supports retrieval of the underlying JDBC Connection. Out of the box, Spring provides dialects for the Toplink, Hibernate and OpenJPA JPA implementations. See the next section for details on the JpaDialect mechanism.

no module named urllib.parse (How should I install it?)

pip install -U websocket 

I just use this to fix my problem

python setup.py uninstall

For me, the following mostly works:

have pip installed, e.g.:

$ easy_install pip

Check, how is your installed package named from pip point of view:

$ pip freeze

This shall list names of all packages, you have installed (and which were detected by pip). The name can be sometime long, then use just the name of the package being shown at the and after #egg=. You can also in most cases ignore the version part (whatever follows == or -).

Then uninstall the package:

$ pip uninstall package.name.you.have.found

If it asks for confirmation about removing the package, then you are lucky guy and it will be removed.

pip shall detect all packages, which were installed by pip. It shall also detect most of the packages installed via easy_install or setup.py, but this may in some rare cases fail.

Here is real sample from my local test with package named ttr.rdstmc on MS Windows.

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev

$ python setup.py develop
.....
.....
Finished processing dependencies for ttr.rdstmc==0.0.1dev

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
-e hg+https://[email protected]/vlcinsky/ttr.rdstmc@d61a9922920c508862602f7f39e496f7b99315f0#egg=ttr.rdstmc-dev
ttr.utcutils==0.1.1dev

$ pip uninstall ttr.rdstmc
Uninstalling ttr.rdstmc:
  c:\python27\lib\site-packages\ttr.rdstmc.egg-link
Proceed (y/n)? y
  Successfully uninstalled ttr.rdstmc

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev

Edit 2015-05-20

All what is written above still applies, anyway, there are small modifications available now.

Install pip in python 2.7.9 and python 3.4

Recent python versions come with a package ensurepip allowing to install pip even when being offline:

$ python -m ensurepip --upgrade

On some systems (like Debian Jessie) this is not available (to prevent breaking system python installation).

Using grep or find

Examples above assume, you have grep installed. I had (at the time I had MS Windows on my machine) installed set of linux utilities (incl. grep). Alternatively, use native MS Windows find or simply ignore that filtering and find the name in a bit longer list of detected python packages.

What do pty and tty mean?

A tty is a physical terminal-teletype port on a computer (usually a serial port).

The word teletype is a shorting of the telegraph typewriter, or teletypewriter device from the 1930s - itself an electromagnetic device which replaced the telegraph encoding machines of the 1830s and 1840s.

Teletypewriter
TTY - Teletypewriter 1930s

A pty is a pseudo-teletype port provided by a computer Operating System Kernel to connect software programs emulating terminals, such as ssh, xterm, or screen.

enter image description here
PTY - PseudoTeletype

A terminal is simply a computer's user interface that uses text for input and output.


OS Implementations

These use pseudo-teletype ports however, their naming and implementations have diverged a little.

Linux mounts a special file system devpts on /dev (the 's' presumably standing for serial) that creates a corresponding entry in /dev/pts for every new terminal window you open, e.g. /dev/pts/0


macOS/FreeBSD also use the /dev file structure however, they use a numbered TTY naming convention ttys for every new terminal window you open e.g. /dev/ttys002


Microsoft Windows still has the concept of an LPT port for Line Printer Terminals within it's Command Shell for output to a printer.

Java: Static vs inner class

There are two differences between static inner and non static inner classes.

  1. In case of declaring member fields and methods, non static inner class cannot have static fields and methods. But, in case of static inner class, can have static and non static fields and method.

  2. The instance of non static inner class is created with the reference of object of outer class, in which it has defined, this means it has enclosing instance. But the instance of static inner class is created without the reference of Outer class, which means it does not have enclosing instance.

See this example

class A
{
    class B
    {
        // static int x; not allowed here
    }

    static class C
    {
        static int x; // allowed here
    }
}

class Test
{
    public static void main(String… str)
    {
        A a = new A();

        // Non-Static Inner Class
        // Requires enclosing instance
        A.B obj1 = a.new B(); 

        // Static Inner Class
        // No need for reference of object to the outer class
        A.C obj2 = new A.C(); 
    }
}

Get all attributes of an element using jQuery

My suggestion:

$.fn.attrs = function (fnc) {
    var obj = {};
    $.each(this[0].attributes, function() {
        if(this.name == 'value') return; // Avoid someone (optional)
        if(this.specified) obj[this.name] = this.value;
    });
    return obj;
}

var a = $(el).attrs();

how to get yesterday's date in C#

DateTime.Today as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1);

There are sufficient options available in DateTime to get the formatting like ToShortDateString depending on your culture and you have no need to concatenate them individually.

Also you can have a desirable format in the .ToString() version of the DateTime instance

Django download a file

Simple using html like this downloads the file mentioned using static keyword

<a href="{% static 'bt.docx' %}" class="btn btn-secondary px-4 py-2 btn-sm">Download CV</a>

Convert PDF to PNG using ImageMagick

Reducing the image size before output results in something that looks sharper, in my case:

convert -density 300 a.pdf -resize 25% a.png

Python webbrowser.open() to open Chrome browser

Worked for me in windows

Put the path of your chrome application and do not forget to put th %s at the end. I am still trying to open the browser with html code without saving the file... I will add the code when I'll find how.

import webbrowser
chromedir= "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
webbrowser.get(chromedir).open("http://pythonprogramming.altervista.org")

>>> link to: [a page from my blog where I explain this]<<<

How is the AND/OR operator represented as in Regular Expressions?

Or you can use this:

^(?:part[12]|(part)1,\12)$

What primitive data type is time_t?

You can use the function difftime. It returns the difference between two given time_t values, the output value is double (see difftime documentation).

time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0); 
printf("%g",actual_time_sec);

How can I get the file name from request.FILES?

request.FILES['filename'].name

From the request documentation.

If you don't know the key, you can iterate over the files:

for filename, file in request.FILES.iteritems():
    name = request.FILES[filename].name

How do I import/include MATLAB functions?

You have to set the path. See here.

python: how to check if a line is an empty line

line.strip() == ''

Or, if you don't want to "eat up" lines consisting of spaces:

line in ('\n', '\r\n')

Print PHP Call Stack

var_dump(debug_backtrace());

Does that do what you want?

Is there any way to have a fieldset width only be as wide as the controls in them?

i fixed my issue by override legend style as Below

.ui-fieldset-legend
{
  font-size: 1.2em;
  font-weight: bold;
  display: inline-block;
  width: auto;`enter code here`
}

R plot: size and resolution

If you'd like to use base graphics, you may have a look at this. An extract:

You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.

Jquery $.ajax fails in IE on cross domain calls

For IE8 & IE9 you need to use XDomainRequest (XDR). If you look below you'll see it's in a sort of similar formatting as $.ajax. As far as my research has got me I can't get this cross-domain working in IE6 & 7 (still looking for a work-around for this). XDR first came out in IE8 (it's in IE9 also). So basically first, I test for 6/7 and do no AJAX.

IE10+ is able to do cross-domain normally like all the other browsers (congrats Microsoft... sigh)

After that the else if tests for 'XDomainRequest in window (apparently better than browser sniffing) and does the JSON AJAX request that way, other wise the ELSE does it normally with $.ajax.

Hope this helps!! Took me forever to get this all figured out originally

Information on the XDomainRequest object

// call with your url (with parameters) 
// 2nd param is your callback function (which will be passed the json DATA back)

crossDomainAjax('http://www.somecrossdomaincall.com/?blah=123', function (data) {
    // success logic
});

function crossDomainAjax (url, successCallback) {

    // IE8 & 9 only Cross domain JSON GET request
    if ('XDomainRequest' in window && window.XDomainRequest !== null) {

        var xdr = new XDomainRequest(); // Use Microsoft XDR
        xdr.open('get', url);
        xdr.onload = function () {
            var dom  = new ActiveXObject('Microsoft.XMLDOM'),
                JSON = $.parseJSON(xdr.responseText);

            dom.async = false;

            if (JSON == null || typeof (JSON) == 'undefined') {
                JSON = $.parseJSON(data.firstChild.textContent);
            }

            successCallback(JSON); // internal function
        };

        xdr.onerror = function() {
            _result = false;  
        };

        xdr.send();
    } 

    // IE7 and lower can't do cross domain
    else if (navigator.userAgent.indexOf('MSIE') != -1 &&
             parseInt(navigator.userAgent.match(/MSIE ([\d.]+)/)[1], 10) < 8) {
       return false;
    }    

    // Do normal jQuery AJAX for everything else          
    else {
        $.ajax({
            url: url,
            cache: false,
            dataType: 'json',
            type: 'GET',
            async: false, // must be set to false
            success: function (data, success) {
                successCallback(data);
            }
        });
    }
}

What is the proper way to re-throw an exception in C#?

If you throw an exception without a variable (the second example) the StackTrace will include the original method that threw the exception.

In the first example the StackTrace will be changed to reflect the current method.

Example:

static string ReadAFile(string fileName) {
    string result = string.Empty;
    try {
        result = File.ReadAllLines(fileName);
    } catch(Exception ex) {
        throw ex; // This will show ReadAFile in the StackTrace
        throw;    // This will show ReadAllLines in the StackTrace
    }

How to define an enumerated type (enum) in C?

Tarc's answer is the best.

Much of the enum discussion is a red herring.

Compare this code snippet:-

int strategy;
strategy = 1;   
void some_function(void) 
{
}

which gives

error C2501: 'strategy' : missing storage-class or type specifiers
error C2086: 'strategy' : redefinition

with this one which compiles with no problem.

int strategy;
void some_function(void) 
{
    strategy = 1;   
}

The variable strategy needs to be set at declaration or inside a function etc. You cannot write arbitrary software - assignments in particular - at the global scope.

The fact that he used enum {RANDOM, IMMEDIATE, SEARCH} instead of int is only relevant to the extent that it has confused people that can't see beyond it. The redefinition error messages in the question show that this is what the author has done wrong.

So now you should be able to see why the first of the example below is wrong and the other three are okay.

Example 1. WRONG!

enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = IMMEDIATE;
void some_function(void) 
{
}

Example 2. RIGHT.

enum {RANDOM, IMMEDIATE, SEARCH} strategy = IMMEDIATE;
void some_function(void) 
{
}

Example 3. RIGHT.

enum {RANDOM, IMMEDIATE, SEARCH} strategy;
void some_function(void) 
{
    strategy = IMMEDIATE;
}

Example 4. RIGHT.

void some_function(void) 
{
    enum {RANDOM, IMMEDIATE, SEARCH} strategy;
    strategy = IMMEDIATE;
}

If you have a working program you should just be able to paste these snippets into your program and see that some compile and some do not.

How to Sort a List<T> by a property in the object

To do this without LINQ on .Net2.0:

List<Order> objListOrder = GetOrderList();
objListOrder.Sort(
    delegate(Order p1, Order p2)
    {
        return p1.OrderDate.CompareTo(p2.OrderDate);
    }
);

If you're on .Net3.0, then LukeH's answer is what you're after.

To sort on multiple properties, you can still do it within a delegate. For example:

orderList.Sort(
    delegate(Order p1, Order p2)
    {
        int compareDate = p1.Date.CompareTo(p2.Date);
        if (compareDate == 0)
        {
            return p2.OrderID.CompareTo(p1.OrderID);
        }
        return compareDate;
    }
);

This would give you ascending dates with descending orderIds.

However, I wouldn't recommend sticking delegates as it will mean lots of places without code re-use. You should implement an IComparer and just pass that through to your Sort method. See here.

public class MyOrderingClass : IComparer<Order>
{
    public int Compare(Order x, Order y)
    {
        int compareDate = x.Date.CompareTo(y.Date);
        if (compareDate == 0)
        {
            return x.OrderID.CompareTo(y.OrderID);
        }
        return compareDate;
    }
}

And then to use this IComparer class, just instantiate it and pass it to your Sort method:

IComparer<Order> comparer = new MyOrderingClass();
orderList.Sort(comparer);

Java - how do I write a file to a specified directory

The best practice is using File.separator in the paths.

How to run Spyder in virtual environment?

I just had the same problem trying to get Spyder to run in Virtual Environment.

The solution is simple:

Activate your virtual environment.

Then pip install Spyder and its dependencies (PyQt5) in your virtual environment.

Then launch Spyder3 from your virtual environment CLI.

It works fine for me now.

How to clone a Date object?

Simplified version:

Date.prototype.clone = function () {
    return new Date(this.getTime());
}

XML parsing of a variable string in JavaScript

You can also through the jquery function($.parseXML) to manipulate xml string

example javascript:

var xmlString = '<languages><language name="c"></language><language name="php"></language></languages>';
var xmlDoc = $.parseXML(xmlString);
$(xmlDoc).find('name').each(function(){
    console.log('name:'+$(this).attr('name'))
})

How to check the version of GitLab?

If you are using a self-hosted version of GitLab then you may consider running this command.

grep gitlab /opt/gitlab/version-manifest.txt

Convert string to buffer Node

Note: Just reposting John Zwinck's comment as answer.

One issue might be that you are using a older version of Node (for the moment, I cannot upgrade, codebase struck with v4.3.1). Simple solution here is, using the deprecated way:

new Buffer(bufferStr)

Note #2: This is for people struck in older version, for whom Buffer.from does not work

Using a Python subprocess call to invoke a Python script

def main(argv):
    host = argv[0]
    type = argv[1]
    val = argv[2]

    ping = subprocess.Popen(['python ftp.py %s %s %s'%(host,type,val)],stdout = subprocess.PIPE,stderr = subprocess.PIPE,shell=True)
    out = ping.communicate()[0]
    output = str(out)
    print output

Got a NumberFormatException while trying to parse a text file for objects

I changed Scanner fin = new Scanner(file); to Scanner fin = new Scanner(new File(file)); and it works perfectly now. I didn't think the difference mattered but there you go.

Javascript checkbox onChange

HTML:

<input type="checkbox" onchange="handleChange(event)">

JS:

function handleChange(e) {
     const {checked} = e.target;
}

Accept server's self-signed ssl certificate in Java client

Trust all SSL certificates:- You can bypass SSL if you want to test on the testing server. But do not use this code for production.

public static class NukeSSLCerts {
protected static final String TAG = "NukeSSLCerts";

public static void nuke() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[] { 
            new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    X509Certificate[] myTrustedAnchors = new X509Certificate[0];  
                    return myTrustedAnchors;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {}

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {}
            }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) { 
    }
}

}

Please call this function in onCreate() function in Activity or in your Application Class.

NukeSSLCerts.nuke();

This can be used for Volley in Android.

How to refresh Gridview after pressed a button in asp.net

I was totally lost on why my Gridview.Databind() would not refresh.

My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:

gvServerConfiguration.Databind()
uppServerConfiguration.Update()

uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.

Hope this helps someone.

MySQL Trigger: Delete From Table AFTER DELETE

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

Try this as the new trigger:

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

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

Pandas DataFrame: replace all values in a column, based on condition

df.loc[df['First season'] > 1990, 'First Season'] = 1

Explanation:

df.loc takes two arguments, 'row index' and 'column index'. We are checking if the value is greater than 1990 of each row value, under "First season" column and then we replacing it with 1.

How can I remove a style added with .css() function?

This will remove complete tag :

  $("body").removeAttr("style");

How can I pass a member function where a free function is expected?

If you actually don't need to use the instance a (i.e. you can make it static like @mathengineer 's answer) you can simply pass in a non-capture lambda. (which decay to function pointer)


#include <iostream>

class aClass
{
public:
   void aTest(int a, int b)
   {
      printf("%d + %d = %d", a, b, a + b);
   }
};

void function1(void (*function)(int, int))
{
    function(1, 1);
}

int main()
{
   //note: you don't need the `+`
   function1(+[](int a,int b){return aClass{}.aTest(a,b);}); 
}

Wandbox


note: if aClass is costly to construct or has side effect, this may not be a good way.

How to extract an assembly from the GAC?

Think I figured out a way to look inside the GAC without modifying the registry or using the command line, powershell, or any other programs:

Create a new shortcut (to anywhere). Then modify the shortcut to have the target be:

%windir%\assembly\GAC_MSIL\System

Opening this shortcut takes you to the System folder inside the GAC (which everyone should have) and has the wonderful side effect of letting you switch to a higher directory and then browsing into any other folder you want (and see the dll files, etc)

I tested this on windows 7 and windows server 2012.

Note: It will not let you use that target when creating the shortcut but it will let you edit it.

Enjoy!

Count all values in a matrix greater than a value

This is very straightforward with boolean arrays:

p31 = numpy.asarray(o31)
za = (p31 < 200).sum() # p31<200 is a boolean array, so `sum` counts the number of True elements

Accessing Google Account Id /username via Android

Retrieve profile information for a signed-in user Use the GoogleSignInResult.getSignInAccount method to request profile information for the currently signed in user. You can call the getSignInAccount method after the sign-in intent succeeds.

GoogleSignInResult result = 
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();

How to make the background image to fit into the whole page without repeating using plain css?

background:url(bgimage.jpg) no-repeat; background-size: cover;

This did the trick

How to get a list of column names on Sqlite3 database?

I know it's too late but this will help other.

To find the column name of the table, you should execute select * from tbl_name and you will get the result in sqlite3_stmt *. and check the column iterate over the total fetched column. Please refer following code for the same.

// sqlite3_stmt *statement ;
int totalColumn = sqlite3_column_count(statement);
for (int iterator = 0; iterator<totalColumn; iterator++) {
   NSLog(@"%s", sqlite3_column_name(statement, iterator));
}

This will print all the column names of the result set.

Use cases for the 'setdefault' dict method

As Muhammad said, there are situations in which you only sometimes wish to set a default value. A great example of this is a data structure which is first populated, then queried.

Consider a trie. When adding a word, if a subnode is needed but not present, it must be created to extend the trie. When querying for the presence of a word, a missing subnode indicates that the word is not present and it should not be created.

A defaultdict cannot do this. Instead, a regular dict with the get and setdefault methods must be used.

jQuery: how do I animate a div rotation?

If you want just a jQuery option, this will work:

$(el).stop().animate(
  {rotation: 360},
  {
    duration: 500,
    step: function(now, fx) {
      $(this).css({"transform": "rotate("+now+"deg)"});
    }
  }
);

This works with jQuery 1.8, which takes care of CSS prefixing automatically. jQuery doesn't animate rotation so I'm putting the transform:rotate() in the custom step function. It might only work starting from 0.

Demo: http://jsfiddle.net/forresto/ShUgD/

IE9 and Mobile Safari 4 support CSS transforms but not CSS transitions, so I came up with this simple shim, using Modernizr feature testing:

if (Modernizr.csstransitions) {
  $(el).css({
    "transition": "all 500ms ease-in-out"
  });
}

$(el).click(function(){
  var rotateTo = 360;
  if (Modernizr.csstransitions) {
    $(el).css({"transform": "rotate("+rotateTo+"deg)"});
  } else {
    $(el).stop().animate(
      {rotation: rotateTo},
      {
        duration: 500,
        step: function(now, fx) {
          $(this).css({"transform": "rotate("+now+"deg)"});
        }
      }
    );
  }
});

The above will use CSS transitions when available.

What process is listening on a certain port on Solaris?

If you have access to netstat, that can do precisely that.

Convert a SQL Server datetime to a shorter date format

If you have a datetime field that gives the results like this 2018-03-30 08:43:28.177

Proposed: and you want to change the datetime to date to appear like 2018-03-30

cast(YourDateField as Date)

Angular 2: import external js file into component

Here is a simple way i did it in my project.

lets say you need to use clipboard.min.js and for the sake of the example lets say that inside clipboard.min.js there is a function that called test2().

in order to use test2() function you need:

  1. make a reference to the .js file inside you index.html.
  2. import clipboard.min.js to your component.
  3. declare a variable that will use you to call the function.

here are only the relevant parts from my project (see the comments):

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Angular QuickStart</title>
    <base href="/src/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="/node_modules/core-js/client/shim.min.js"></script>


    <script src="/node_modules/zone.js/dist/zone.js"></script>
    <script src="/node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
        System.import('main.js').catch(function (err) { console.error(err); });
    </script>

    <!-- ************ HERE IS THE REFERENCE TO clipboard.min.js -->
    <script src="app/txtzone/clipboard.min.js"></script>
</head>

<body>
    <my-app>Loading AppComponent content here ...</my-app>
</body>
</html>

app.component.ts:

import '../txtzone/clipboard.min.js';
declare var test2: any; // variable as the name of the function inside clipboard.min.js

@Component({
    selector: 'txt-zone',
    templateUrl: 'app/txtzone/Txtzone.component.html',
    styleUrls: ['app/txtzone/TxtZone.css'],
})



export class TxtZoneComponent implements AfterViewInit {

    // call test2
    callTest2()
    {   
        new test2(); // the javascript function will execute
    }

}

WCF Exception: Could not find a base address that matches scheme http for the endpoint

Open IIS And right click on Default App Pool and Add Binding to make application work with HTTPS protocol.

type : https

IP address : All unassigned

port no : 443

SSL Certificate : WMSVC

then

Click on and restart IIS

Done

[Vue warn]: Property or method is not defined on the instance but referenced during render

It is most likely a spelling error of reserved vuejs variables. I got here because I misspelled computed: and vuejs would not recognize my computed property variables. So if you have an error like this, check your spelling first!

How do I rotate a picture in WinForms

This will work as long as the image you want to rotate is already in your Properties resources folder.

In Partial Class:

Bitmap bmp2;

OnLoad:

 bmp2 = new Bitmap(Tycoon.Properties.Resources.save2);
            pictureBox6.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox6.Image = bmp2;

Button or Onclick

private void pictureBox6_Click(object sender, EventArgs e)
        {
            if (bmp2 != null)
            {
                bmp2.RotateFlip(RotateFlipType.Rotate90FlipNone);
                pictureBox6.Image = bmp2;
            }
        }

Sleeping in a batch file

UPDATE

The timeout command, available from Windows Vista and onwards should be the command used, as described in another answer to this question. What follows here is an old answer.

Old answer

If you have Python installed, or don't mind installing it (it has other uses too :), just create the following sleep.py script and add it somewhere in your PATH:

import time, sys

time.sleep(float(sys.argv[1]))

It will allow sub-second pauses (for example, 1.5 sec, 0.1, etc.), should you have such a need. If you want to call it as sleep rather than sleep.py, then you can add the .PY extension to your PATHEXT environment variable. On Windows XP, you can edit it in:

My Computer ? Properties (menu) ? Advanced (tab) ? Environment Variables (button) ? System variables (frame)

Count number of rows within each group

Following @Joshua's suggestion, here's one way you might count the number of observations in your df dataframe where Year = 2007 and Month = Nov (assuming they are columns):

nrow(df[,df$YEAR == 2007 & df$Month == "Nov"])

and with aggregate, following @GregSnow:

aggregate(x ~ Year + Month, data = df, FUN = length)

sys.argv[1] meaning in script

sys.argv is a attribute of the sys module. It says the arguments passed into the file in the command line. sys.argv[0] catches the directory where the file is located. sys.argv[1] returns the first argument passed in the command line. Think like we have a example.py file.

example.py

import sys # Importing the main sys module to catch the arguments
print(sys.argv[1]) # Printing the first argument

Now here in the command prompt when we do this:

python example.py

It will throw a index error at line 2. Cause there is no argument passed yet. You can see the length of the arguments passed by user using if len(sys.argv) >= 1: # Code. If we run the example.py with passing a argument

python example.py args

It prints:

args

Because it was the first arguement! Let's say we have made it a executable file using PyInstaller. We would do this:

example argumentpassed

It prints:

argumentpassed

It's really helpful when you are making a command in the terminal. First check the length of the arguments. If no arguments passed, do the help text.

Get all child views inside LinearLayout at once

Get all views from any type of layout

public List<View> getAllViews(ViewGroup layout){
        List<View> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            views.add(layout.getChildAt(i));
        }
        return views;
}

Get all TextView from any type of layout

public List<TextView> getAllTextViews(ViewGroup layout){
        List<TextView> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            View v =layout.getChildAt(i);
            if(v instanceof TextView){
                views.add((TextView)v);
            }
        }
        return views;
}

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

You cannot use a select statement that assigns values to variables to also return data to the user The below code will work fine, because i have declared 1 local variable and that variable is used in select statement.

 Begin
    DECLARE @name nvarchar(max)
    select @name=PolicyHolderName from Table
    select @name
    END

The below code will throw error "A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations" Because we are retriving data(PolicyHolderAddress) from table, but error says data-retrieval operation is not allowed when you use some local variable as part of select statement.

 Begin
    DECLARE @name nvarchar(max)
    select 
       @name = PolicyHolderName,
       PolicyHolderAddress 
    from Table
 END

The the above code can be corrected like below,

Begin
    DECLARE @name nvarchar(max)
    DECLARE @address varchar(100)
    select 
       @name = PolicyHolderName,
       @address = PolicyHolderAddress 
    from Table
END

So either remove the data-retrieval operation or add extra local variable. This will resolve the error.

CSS - how to make image container width fixed and height auto stretched

What you're looking for is min-height and max-height.

img {
    max-width: 100%;
    height: auto;
}

.item {
    width: 120px;
    min-height: 120px;
    max-height: auto;
    float: left;
    margin: 3px;
    padding: 3px;
}

How can I replace a newline (\n) using sed?

In order to replace all newlines with spaces using awk, without reading the whole file into memory:

awk '{printf "%s ", $0}' inputfile

If you want a final newline:

awk '{printf "%s ", $0} END {printf "\n"}' inputfile

You can use a character other than space:

awk '{printf "%s|", $0} END {printf "\n"}' inputfile

Missing XML comment for publicly visible type or member

Jon Skeet's answer works great for when you're building with VisualStudio. However, if you're building the sln via the command line (in my case it was via Ant) then you may find that msbuild ignores the sln supression requests.

Adding this to the msbuild command line solved the problem for me:

/p:NoWarn=1591

Take a list of numbers and return the average

If you have the numpy package:

In [16]: x = [1,2,3,4]    
    ...: import numpy
    ...: numpy.average(x)

Out[16]: 2.5

Exiting from python Command Line

This message is the __str__ attribute of exit

look at these examples :

1

>>> print exit
Use exit() or Ctrl-D (i.e. EOF) to exit

2

>>> exit.__str__()
'Use exit() or Ctrl-D (i.e. EOF) to exit'

3

>>> getattr(exit, '__str__')()
'Use exit() or Ctrl-D (i.e. EOF) to exit'

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

If this is a personal script, rather than one you're planning on distributing, it might be simpler to write a shell function for this:

function warextract { jar xf $1 $2 && mv $2 $3 }

which you could then call from python like so:

warextract /home/foo/bar/Portal.ear Binaries.war /home/foo/bar/baz/

If you really feel like it, you could use sed to parse out the filename from the path, so that you'd be able to call it with

warextract /home/foo/bar/Portal.ear /home/foo/bar/baz/Binaries.war

I'll leave that as an excercise to the reader, though.

Of course, since this will extract the .war out into the current directory first, and then move it, it has the possibility of overwriting something with the same name where you are.

Changing directory, extracting it, and cd-ing back is a bit cleaner, but I find myself using little one-line shell functions like this all the time when I want to reduce code clutter.

How to print all key and values from HashMap in Android?

With Java 8:

map.keySet().forEach(key -> System.out.println(key + "->" + map.get(key)));

UIImage: Resize, then Crop

There's a great piece of code related to the resizing of images + several other operations. I came around this one when trying to figure ou how to resize images... http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/

Doctrine2: Best way to handle many-to-many with extra columns in reference table

I've opened a similar question in the Doctrine user mailing list and got a really simple answer;

consider the many to many relation as an entity itself, and then you realize you have 3 objects, linked between them with a one-to-many and many-to-one relation.

http://groups.google.com/group/doctrine-user/browse_thread/thread/d1d87c96052e76f7/436b896e83c10868#436b896e83c10868

Once a relation has data, it's no more a relation !

Allowing Untrusted SSL Certificates with HttpClient

If you are using System.Net.Http.HttpClient I believe correct pattern is

var handler = new HttpClientHandler() 
{ 
    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};

var http = new HttpClient(handler);
var res = http.GetAsync(url);

check if file exists in php

You can also use PHP get_headers() function.

Example:

function check_file_exists_here($url){
   $result=get_headers($url);
   return stripos($result[0],"200 OK")?true:false; //check if $result[0] has 200 OK
}

if(check_file_exists_here("http://www.mywebsite.com/file.pdf"))
   echo "This file exists";
else
   echo "This file does not exist";

Is there an equivalent method to C's scanf in Java?

If one really wanted to they could make there own version of scanf() like so:

    import java.util.ArrayList;
    import java.util.Scanner;

public class Testies {

public static void main(String[] args) {
    ArrayList<Integer> nums = new ArrayList<Integer>();
    ArrayList<String> strings = new ArrayList<String>();

    // get input
    System.out.println("Give me input:");
    scanf(strings, nums);

    System.out.println("Ints gathered:");
    // print numbers scanned in
    for(Integer num : nums){
        System.out.print(num + " ");
    }
    System.out.println("\nStrings gathered:");
    // print strings scanned in
    for(String str : strings){
        System.out.print(str + " ");
    }

    System.out.println("\nData:");
    for(int i=0; i<strings.size(); i++){
        System.out.println(nums.get(i) + " " + strings.get(i));
    }
}

// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner getLine = new Scanner(System.in);
    Scanner input = new Scanner(getLine.nextLine());

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}

// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner input = (new Scanner(in));

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}


}

Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them. Also, hasNext() should probably be at the bottom of the if-else if sequence since hasNext() will return true for all of the data in the string.

Output:

Give me input: apples 8 9 pears oranges 5 Ints gathered: 8 9 5 Strings gathered: apples pears oranges Data: 8 apples 9 pears 5 oranges

Probably not the best example; but, the point is that Scanner implements the Iterator class. Making it easy to iterate through the scanners input using the hasNext<datatypehere>() methods; and then storing the input.

Sorting arraylist in alphabetical order (case insensitive)

try this code

Collections.sort(yourarraylist, new SortBasedOnName());



import java.util.Comparator;
import com.RealHelp.objects.FBFriends_Obj;
import com.RealHelp.ui.importFBContacts;

public class SortBasedOnName implements Comparator
{
public int compare(Object o1, Object o2) 
{

    FBFriends_Obj dd1 = (FBFriends_Obj)o1;// where FBFriends_Obj is your object class
    FBFriends_Obj dd2 = (FBFriends_Obj)o2;
    return dd1.uname.compareToIgnoreCase(dd2.uname);//where uname is field name
}

}

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

My real sample for MVC 3 is here:

<% using (Html.BeginForm()) { %>

<p>

Start Date: <%: Html.TextBox("datepicker1", DateTime.Now.ToString("MM/dd/yyyy"), new { style = "width:80px;", maxlength = 10 })%> 

End Date: <%: Html.TextBox("datepicker2", DateTime.Now.ToString("MM/dd/yyyy"), new { style = "width:80px;", maxlength = 10 })%> 

<input type="submit" name="btnSubmit" value="Search" /> 

</p>

<% } %>

So, we have following

"datepicker1" - ID of the control

DateTime.Now.ToString("MM/dd/yyyy") - value by default

style = "width:80px;" - width of the textbox

maxlength = 10 - we can input 10 characters only

Pass multiple parameters to rest API - Spring

Yes its possible to pass JSON object in URL

queryString = "{\"left\":\"" + params.get("left") + "}";
 httpRestTemplate.exchange(
                    Endpoint + "/A/B?query={queryString}",
                    HttpMethod.GET, entity, z.class, queryString);

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

It can also happen if your password policy or something else have changed your password in case your appPools are using the the user with changed password.

So, you should update the user password from the advanced settings of your appPool throught "Identity" property.

The reference is here

How to 'foreach' a column in a DataTable using C#?

This should work:

DataTable dtTable;

MySQLProcessor.DTTable(mysqlCommand, out dtTable);

// On all tables' rows
foreach (DataRow dtRow in dtTable.Rows)
{
    // On all tables' columns
    foreach(DataColumn dc in dtTable.Columns)
    {
      var field1 = dtRow[dc].ToString();
    }
}

npm not working - "read ECONNRESET"

Solution 1:

MAC + LINUX

run this command with sudo

sudo npm install -g yo

Windows

run cmd as administrator and then run this command again

Solution 2:

run this command and then try

npm config set registry http://registry.npmjs.org/

How to create a dump with Oracle PL/SQL Developer?

Just to keep this up to date:

The current version of SQLDeveloper has an export tool (Tools > Database Export) that will allow you to dump a schema to a file, with filters for object types, object names, table data etc.

It's a fair amount easier to set-up and use than exp and imp if you're used to working in a GUI environment, but not as versatile if you need to use it for scripting anything.

How to assign multiple classes to an HTML container?

To assign multiple classes to an html element, include both class names within the quotations of the class attribute and have them separated by a space:

<article class="column wrapper"> 

In the above example, column and wrapper are two separate css classes, and both of their properties will be applied to the article element.

PostgreSQL visual interface similar to phpMyAdmin?

I would also highly recommend Adminer - http://www.adminer.org/

It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.

How to access pandas groupby dataframe by key

Wes McKinney (pandas' author) in Python for Data Analysis provides the following recipe:

groups = dict(list(gb))

which returns a dictionary whose keys are your group labels and whose values are DataFrames, i.e.

groups['foo']

will yield what you are looking for:

     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14

Where can I find the Java SDK in Linux after installing it?

$ which java 

should give you something like

/usr/bin/java

Case insensitive access for generic dictionary

For you LINQers out there that never use a regular dictionary constructor

myCollection.ToDictionary(x => x.PartNumber, x => x.PartDescription, StringComparer.OrdinalIgnoreCase)

Console output in a Qt GUI app?

Easy

Step1: Create new project. Go File->New File or Project --> Other Project -->Empty Project

Step2: Use the below code.

In .pro file

QT +=widgets
CONFIG += console
TARGET = minimal
SOURCES += \ main.cpp

Step3: Create main.cpp and copy the below code.

#include <QApplication>
#include <QtCore>

using namespace  std;

QTextStream in(stdin);
QTextStream out(stdout);

int main(int argc, char *argv[]){
QApplication app(argc,argv);
qDebug() << "Please enter some text over here: " << endl;
out.flush();
QString input;
input = in.readLine();
out << "The input is " << input  << endl;
return app.exec();
}

I created necessary objects in the code for your understanding.

Just Run It

If you want your program to get multiple inputs with some conditions. Then past the below code in Main.cpp

#include <QApplication>
#include <QtCore>

using namespace  std;

QTextStream in(stdin);
QTextStream out(stdout);

int main(int argc, char *argv[]){
    QApplication app(argc,argv);
    qDebug() << "Please enter some text over here: " << endl;
    out.flush();
    QString input;
    do{
        input = in.readLine();
        if(input.size()==6){
            out << "The input is " << input  << endl;   
        }
        else
        {
            qDebug("Not the exact input man");
        }
    }while(!input.size()==0);

    qDebug(" WE ARE AT THE END");

    // endif
    return app.exec();
} // end main

Hope it educates you.

Good day,

Materialize CSS - Select Doesn't Seem to Render

I found myself in a situation where using the solution selected

$(document).ready(function() {
$('select').material_select();
}); 

for whatever reason was throwing errors because the material_select() function could not be found. It was not possible to just say <select class="browser-default... Because I was using a framework which auto-rendered the the forms. So my solution was to add the class using js(Jquery)

<script>
 $(document).ready(function() {
   $('select').attr("class", "browser-default")
});

How to wait for async method to complete?

Actually I found this more helpful for functions that return IAsyncAction.

            var task = asyncFunction();
            while (task.Status == AsyncStatus.Completed) ;

jQuery hover and class selector

Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:

HTML:

  <ul id="menu">
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
  </ul>

CSS:

#menu {
  margin: 0;
}
#menu li {
  float: left;
  list-style: none;
  margin: 0;
}
#menu li a {
  display: block;
  line-height:30px;
  width:100px;
  background-color:#000;
}
#menu li a:hover {
  background-color:#F00;
}

how to run vibrate continuously in iphone?

Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.

no target device found android studio 2.1.1

I have used a different USB cable and it started working. This is weird because the USB cable (which was not detected in android studio) was charging the phone. This made me feel like there was a problem on my Mac.

However changing the cable worked for me. Just check this option as well if you got stuck with this problem.

How can I read inputs as numbers?

In Python 3.x, raw_input was renamed to input and the Python 2.x input was removed.

This means that, just like raw_input, input in Python 3.x always returns a string object.

To fix the problem, you need to explicitly make those inputs into integers by putting them in int:

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

Unstage a deleted file in git

The answers to your two questions are related. I'll start with the second:

Once you have staged a file (often with git add, though some other commands implicitly stage the changes as well, like git rm) you can back out that change with git reset -- <file>.

In your case you must have used git rm to remove the file, which is equivalent to simply removing it with rm and then staging that change. If you first unstage it with git reset -- <file> you can then recover it with git checkout -- <file>.

How to check if a network port is open on linux?

If you want to use this in a more general context, you should make sure, that the socket that you open also gets closed. So the check should be more like this:

import socket
from contextlib import closing

def check_socket(host, port):
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        if sock.connect_ex((host, port)) == 0:
            print "Port is open"
        else:
            print "Port is not open"

Why does integer division in C# return an integer and not a float?

Since you don't use any suffix, the literals 13 and 4 are interpreted as integer:

Manual:

If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.

Thus, since you declare 13 as integer, integer division will be performed:

Manual:

For an operation of the form x / y, binary operator overload resolution is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.

The predefined division operators are listed below. The operators all compute the quotient of x and y.

Integer division:

int operator /(int x, int y);
uint operator /(uint x, uint y);
long operator /(long x, long y);
ulong operator /(ulong x, ulong y);

And so rounding down occurs:

The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.

If you do the following:

int x = 13f / 4f;

You'll receive a compiler error, since a floating-point division (the / operator of 13f) results in a float, which cannot be cast to int implicitly.

If you want the division to be a floating-point division, you'll have to make the result a float:

float x = 13 / 4;

Notice that you'll still divide integers, which will implicitly be cast to float: the result will be 3.0. To explicitly declare the operands as float, using the f suffix (13f, 4f).

Fix footer to bottom of page

Your footer element won't inherently be fixed to the bottom of your viewport unless you style it that way.
So if you happen to have a page that doesn't have enough content to push it all the way down it'll end up somewhere in the middle of the viewport; looking very awkward and not sure what to do with itself, like my first day of high school.

Positioning the element by declaring the fixed rule is great if you always want your footer visible regardless of initial page height - but then remember to set a bottom margin so that it doesn't overlay the last bit of content on that page. This becomes tricky if your footer has a dynamic height; which is often the case with responsive sites since it's in the nature of elements to stack.

You'll find a similar problem with absolute positioning. And although it does take the element in question out of the natural flow of the document, it still won't fix it to the bottom of the screen should you find yourself with a page that has little to no content to flesh it out.

Consider achieving this by:

  1. Declaring a height value for the <body> & <html> tags
  2. Declaring a minimum-height value to the nested wrapper element, usually the element which wraps all your descendant elements contained within the body structure (this wouldn't include your footer element)

Code Pen Example

_x000D_
_x000D_
$("#addBodyContent").on("click", function() {_x000D_
  $("<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>").appendTo(".flex-col:first-of-type");_x000D_
});_x000D_
_x000D_
$("#resetBodyContent").on("click", function() {_x000D_
  $(".flex-col p").remove();_x000D_
});_x000D_
_x000D_
$("#addFooterContent").on("click", function() {_x000D_
  $("<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>").appendTo("footer");_x000D_
});_x000D_
_x000D_
$("#resetFooterContent").on("click", function() {_x000D_
  $("footer p").remove();_x000D_
});
_x000D_
html, body {_x000D_
    height: 91%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
    width: 100%;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    box-sizing: border-box;_x000D_
    padding: 10px;_x000D_
    display: block;_x000D_
    min-height: 100%;_x000D_
}_x000D_
_x000D_
footer {_x000D_
    background: black;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    box-sizing: border-box;_x000D_
    padding: 10px;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
    display: flex;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.flex-col {_x000D_
    flex: 1 1;_x000D_
    background: #ccc;_x000D_
    margin: 0px 10px;_x000D_
    box-sizing: border-box;_x000D_
    padding: 20px;_x000D_
}_x000D_
_x000D_
.flex-btn-wrapper {_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    flex-direction: row;_x000D_
}_x000D_
_x000D_
.btn {_x000D_
    box-sizing: border-box;_x000D_
    padding: 10px;_x000D_
    transition: .7s;_x000D_
    margin: 10px 10px;_x000D_
    min-width: 200px;_x000D_
}_x000D_
_x000D_
.btn:hover {_x000D_
    background: transparent;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
.dark {_x000D_
    background: black;_x000D_
    color: white;_x000D_
    border: 3px solid black;_x000D_
}_x000D_
_x000D_
.light {_x000D_
    background: white;_x000D_
    border: 3px solid white;_x000D_
}_x000D_
_x000D_
.light:hover {_x000D_
    color: white;_x000D_
}_x000D_
_x000D_
.dark:hover {_x000D_
    color: black;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrapper">_x000D_
    <div class="flex-btn-wrapper">_x000D_
        <button id="addBodyContent" class="dark btn">Add Content</button>_x000D_
        <button id="resetBodyContent" class="dark btn">Reset Content</button>_x000D_
    </div>_x000D_
    <div class="flex">_x000D_
    <div class="flex-col">_x000D_
      lorem ipsum dolor..._x000D_
    </div>_x000D_
    <div class="flex-col">_x000D_
      lorem ipsum dolor..._x000D_
    </div>_x000D_
    </div>_x000D_
    </div>_x000D_
<footer>_x000D_
    <div class="flex-btn-wrapper">_x000D_
        <button id="addFooterContent" class="light btn">Add Content</button>_x000D_
        <button id="resetFooterContent" class="light btn">Reset Content</button>_x000D_
    </div>_x000D_
    lorem ipsum dolor..._x000D_
</footer>
_x000D_
_x000D_
_x000D_

Cache an HTTP 'Get' service response in AngularJS?

In Angular 8 we can do like this:

import { Injectable } from '@angular/core';
import { YourModel} from '../models/<yourModel>.model';
import { UserService } from './user.service';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class GlobalDataService {

  private me: <YourModel>;

  private meObservable: Observable<User>;

  constructor(private yourModalService: <yourModalService>, private http: HttpClient) {

  }

  ngOnInit() {

  }


  getYourModel(): Observable<YourModel> {

    if (this.me) {
      return of(this.me);
    } else if (this.meObservable) {
      return this.meObservable;
    }
    else {
      this.meObservable = this.yourModalService.getCall<yourModel>() // Your http call
      .pipe(
        map(data => {
          this.me = data;
          return data;
        })
      );
      return this.meObservable;
    }
  }
}

You can call it like this:

this.globalDataService.getYourModel().subscribe(yourModel => {


});

The above code will cache the result of remote API at first call so that it can be used on further requests to that method.

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

Angularjs simple file download causes router to redirect

We also had to develop a solution which would even work with APIs requiring authentication (see this article)

Using AngularJS in a nutshell here is how we did it:

Step 1: Create a dedicated directive

// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
    restrict: 'E',
    templateUrl: '/path/to/pdfDownload.tpl.html',
    scope: true,
    link: function(scope, element, attr) {
        var anchor = element.children()[0];

        // When the download starts, disable the link
        scope.$on('download-start', function() {
            $(anchor).attr('disabled', 'disabled');
        });

        // When the download finishes, attach the data to the link. Enable the link and change its appearance.
        scope.$on('downloaded', function(event, data) {
            $(anchor).attr({
                href: 'data:application/pdf;base64,' + data,
                download: attr.filename
            })
                .removeAttr('disabled')
                .text('Save')
                .removeClass('btn-primary')
                .addClass('btn-success');

            // Also overwrite the download pdf function to do nothing.
            scope.downloadPdf = function() {
            };
        });
    },
    controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
        $scope.downloadPdf = function() {
            $scope.$emit('download-start');
            $http.get($attrs.url).then(function(response) {
                $scope.$emit('downloaded', response.data);
            });
        };
    }] 
});

Step 2: Create a template

<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>

Step 3: Use it

<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>

This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.

Our example uses PDF files, but apparently you could provide any binary format given it's properly encoded.

How to use sed/grep to extract text between two words?

GNU grep can also support positive & negative look-ahead & look-back: For your case, the command would be:

echo "Here is a string" | grep -o -P '(?<=Here).*(?=string)'

If there are multiple occurrences of Here and string, you can choose whether you want to match from the first Here and last string or match them individually. In terms of regex, it is called as greedy match (first case) or non-greedy match (second case)

$ echo 'Here is a string, and Here is another string.' | grep -oP '(?<=Here).*(?=string)' # Greedy match
 is a string, and Here is another 
$ echo 'Here is a string, and Here is another string.' | grep -oP '(?<=Here).*?(?=string)' # Non-greedy match (Notice the '?' after '*' in .*)
 is a 
 is another 

Error message "No exports were found that match the constraint contract name"

This issue can be resolved by deleting or clearing all the folders and files from %AppData%\..\Local\Microsoft\VisualStudio\11.0\ComponentModelCache

This actually clears the Visual Studio component model cache.

On Windows 7 machines, the path is different. When you type %appdata% in Run dialog, it opens the folder C:\Users\<username>\AppData\Roaming.

Click the 'up' button to navigate to the parent folder and select the folder 'Local'.

Final path: C:\Users\<username>\AppData\Local\Microsoft\VisualStudio\11.0\ComponentModelCache

Get current scroll position of ScrollView in React Native

Use

<ScrollView 
 onMomentumScrollEnd={(event) => this.getscrollposition(event)} 
 scrollEventThrottle={16}>

Show Position

getscrollposition(e) {console.log('scroll y ', e.nativeEvent.contentOffset.y);}

How to make a progress bar

var myPer = 35;
$("#progressbar")
    .progressbar({ value: myPer })
    .children('.ui-progressbar-value')
    .html(myPer.toPrecision(3) + '%')
    .css("display", "block");

Date difference in years using C#

DateTime musteriDogum = new DateTime(dogumYil, dogumAy, dogumGun);

int additionalDays = ((DateTime.Now.Year - dogumYil) / 4); //Count of the years with 366 days

int extraDays = additionalDays + ((DateTime.Now.Year % 4 == 0 || musteriDogum.Year % 4 == 0) ? 1 : 0); //We add 1 if this year or year inserted has 366 days

int yearsOld = ((DateTime.Now - musteriDogum).Days - extraDays ) / 365; // Now we extract these extra days from total days and we can divide to 365

How do I change the default application icon in Java?

Try This write after

initcomponents();

setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("Your image address")));

How to fix apt-get: command not found on AWS EC2?

Check with "uname -a" and/or "lsb_release -a" to see which version of Linux you are actually running on your AWS instance. The default Amazon AMI image uses YUM for its package manager.

Cannot download Docker images behind a proxy

This doesn't exactly answer the question, but might help, especially if you don't want to deal with service files.

In case you are the one is hosting the image, one way is to convert the image as a tar archive instead, using something like the following at the server.

docker save <image-name> --output <archive-name>.tar

Simply download the archive and turn it back into an image.

docker load <archive-name>.tar

How do I get the IP address into a batch-file variable?

try something like this

echo "yours ip addresses are:"
ifconfig | grep "inet addr" | cut -d':' -f2 | cut -d' ' -f1

linux like systems

Calling @Html.Partial to display a partial view belonging to a different controller

As GvS said, but I also find it useful to use strongly typed views so that I can write something like

@Html.Partial(MVC.Student.Index(), model)

without magic strings.

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

How to get all subsets of a set? (powerset)

If you're looking for a quick answer, I just searched "python power set" on google and came up with this: Python Power Set Generator

Here's a copy-paste from the code in that page:

def powerset(seq):
    """
    Returns all the subsets of this set. This is a generator.
    """
    if len(seq) <= 1:
        yield seq
        yield []
    else:
        for item in powerset(seq[1:]):
            yield [seq[0]]+item
            yield item

This can be used like this:

 l = [1, 2, 3, 4]
 r = [x for x in powerset(l)]

Now r is a list of all the elements you wanted, and can be sorted and printed:

r.sort()
print r
[[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 4], [1, 3], [1, 3, 4], [1, 4], [2], [2, 3], [2, 3, 4], [2, 4], [3], [3, 4], [4]]

Get timezone from DateTime

Generally the practice would be to pass data as a DateTime with a "timezone" of UTC and then pass a TimeZoneInfo object and when you are ready to display the data, you use the TimeZoneInfo object to convert the UTC DateTime.

The other option is to set the DateTime with the current timezone, and then make sure the "timezone" is unknown for the DateTime object, then make sure the DateTime is again passed with a TimeZoneInfo that indicates the TimeZone of the DateTime passed.

As others have indicated here, it would be nice if Microsoft got on top of this and created one nice object to do it all, but for now you have to deal with two objects.

Make javascript alert Yes/No Instead of Ok/Cancel

You cannot do that with the native confirm() as it is the browser’s method.

You have to create a plugin for a confirm box (or try one created by someone else). And they often look better, too.

Additional Tip: Change your English sentence to something like

Really, Delete this Thing?

How do I execute a bash script in Terminal?

This is an old thread, but I happened across it and I'm surprised nobody has put up a complete answer yet. So here goes...

The Executing a Command Line Script Tutorial!

Q: How do I execute this in Terminal?

Confusions and Conflicts:

  • You do not need an 'extension' (like .sh or .py or anything else), but it helps to keep track of things. It won't hurt. If the script name contains an extension, however, you must use it.
  • You do not need to be in any certain directory at all for any reason.
  • You do not need to type out the name of the program that runs the file (BASH or Python or whatever) unless you want to. It won't hurt.
  • You do not need sudo to do any of this. This command is reserved for running commands as another user or a 'root' (administrator) user. Great post here.

(A person who is just learning how to execute scripts should not be using this command unless there is a real need, like installing a new program. A good place to put your scripts is in your ~/bin folder. You can get there by typing cd ~/bin or cd $HOME/bin from the terminal prompt. You will have full permissions in that folder.)

To "execute this script" from the terminal on a Unix/Linux type system, you have to do three things:

  1. Tell the system the location of the script. (pick one)

    • Type the full path with the script name (e.g. /path/to/script.sh). You can verify the full path by typing pwd or echo $PWD in the terminal.
    • Execute from the same directory and use ./ for the path (e.g. ./script.sh). Easy.
    • Place the script in a directory that is on the system PATH and just type the name (e.g. script.sh). You can verify the system PATH by typing echo $PATH or echo -e ${PATH//:/\\n} if you want a neater list.
  2. Tell the system that the script has permission to execute. (pick one)

    • Set the "execute bit" by typing chmod +x /path/to/script.sh in the terminal.
    • You can also use chmod 755 /path/to/script.sh if you prefer numbers. There is a great discussion with a cool chart here.
  3. Tell the system the type of script. (pick one)

    • Type the name of the program before the script. (e.g. BASH /path/to/script.sh or PHP /path/to/script.php) If the script has an extension, such as .php or .py, it is part of the script name and you must include it.
    • Use a shebang, which I see you have (#!/bin/bash) in your example. If you have that as the first line of your script, the system will use that program to execute the script. No need for typing programs or using extensions.
    • Use a "portable" shebang. You can also have the system choose the version of the program that is first in the PATH by using #!/usr/bin/env followed by the program name (e.g. #!/usr/bin/env bash or #!/usr/bin/env python3). There are pros and cons as thoroughly discussed here.

how to get a list of dates between two dates in java

Recommending date streams

In Java 9, you can use following new method, LocalDate::datesUntil:

LocalDate start = LocalDate.of(2017, 2, 1);
LocalDate end = LocalDate.of(2017, 2, 28);

Stream<LocalDate> dates = start.datesUntil(end.plusDays(1));
List<LocalDate> list = dates.collect(Collectors.toList());

The new method datesUntil(...) works with an exclusive end date, hence the shown hack to add a day.

Once you have obtained a stream you can exploit all the features offered by java.util.stream- or java.util.function-packages. Working with streams has become so simple compared with earlier approaches based on customized for- or while-loops.


Or if you look for a stream-based solution which operates on inclusive dates by default but can also be configured otherwise then you might find the class DateInterval in my library Time4J interesting because it offers a lot of special features around date streams including a performant spliterator which is faster than in Java-9:

PlainDate start = PlainDate.of(2017,  2, 1);
PlainDate end = start.with(PlainDate.DAY_OF_MONTH.maximized());
Stream<PlainDate> stream = DateInterval.streamDaily(start, end);

Or even simpler in case of full months:

Stream<PlainDate> februaryDates = CalendarMonth.of(2017, 2).streamDaily();
List<LocalDate> list = 
    februaryDates.map(PlainDate::toTemporalAccessor).collect(Collectors.toList());

Kotlin: How to get and set a text to TextView in Android using Kotlin?

The top post has 'as TextView' appended on the end. You might get other compiler errors if you leave this on. The following should be fine.

val text: TextView = findViewById(R.id.android_text) as TextView

Where 'android_text' is the ID of your textView

Converting user input string to regular expression

I suggest you also add separate checkboxes or a textfield for the special flags. That way it is clear that the user does not need to add any //'s. In the case of a replace, provide two textfields. This will make your life a lot easier.

Why? Because otherwise some users will add //'s while other will not. And some will make a syntax error. Then, after you stripped the //'s, you may end up with a syntactically valid regex that is nothing like what the user intended, leading to strange behaviour (from the user's perspective).

Appending a line to a file only if it does not already exist

another sed solution is to always append it on the last line and delete a pre existing one.

sed -e '$a\' -e '<your-entry>' -e "/<your-entry-properly-escaped>/d"

"properly-escaped" means to put a regex that matches your entry, i.e. to escape all regex controls from your actual entry, i.e. to put a backslash in front of ^$/*?+().

this might fail on the last line of your file or if there's no dangling newline, I'm not sure, but that could be dealt with by some nifty branching...

FIFO based Queue implementations?

Here is example code for usage of java's built-in FIFO queue:

public static void main(String[] args) {
    Queue<Integer> myQ = new LinkedList<Integer>();
    myQ.add(1);
    myQ.add(6);
    myQ.add(3);
    System.out.println(myQ);   // 1 6 3
    int first = myQ.poll();    // retrieve and remove the first element
    System.out.println(first); // 1
    System.out.println(myQ);   // 6 3
}

How do I get the width and height of a HTML5 canvas?

None of those worked for me. Try this.

console.log($(canvasjQueryElement)[0].width)

Create a new file in git bash

Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.

git add does not create any files. See also http://gitref.org/basic/#add

Github probably creates the file with touch and adds the file for tracking automatically. You can do this on the bash as well.

How to set alignment center in TextBox in ASP.NET?

To center align text

input[type='text'] { text-align:center;}

To center align the textbox in the container that it sits in, apply text-align:center to the container.

SELECT only rows that contain only alphanumeric characters in MySQL

There is also this:

select m from table where not regexp_like(m, '^[0-9]\d+$')

which selects the rows that contains characters from the column you want (which is m in the example but you can change).

Most of the combinations don't work properly in Oracle platforms but this does. Sharing for future reference.

MySQL timestamp select date range

This SQL query will extract the data for you. It is easy and fast.

SELECT *
  FROM table_name
  WHERE extract( YEAR_MONTH from timestamp)="201010";

Remove non-numeric characters (except periods and commas) from a string

Simplest way to truly remove all non-numeric characters:

echo preg_replace('/\D/', '', $string);

\D represents "any character that is not a decimal digit"

http://php.net/manual/en/regexp.reference.escape.php

Why is using onClick() in HTML a bad practice?

Revision

Unobtrusive JavaScript approach was good in the PAST - especially events handler bind in HTML was considered as bad practice (mainly because onclick events run in the global scope and may cause unexpected error what was mention by YiddishNinja)

However...

Currently it seems that this approach is a little outdated and needs some update. If someone want to be professional frontend developper and write large and complicated apps then he need to use frameworks like Angular, Vue.js, etc... However that frameworks usually use (or allow to use) HTML-templates where event handlers are bind in html-template code directly and this is very handy, clear and effective - e.g. in angular template usually people write:

<button (click)="someAction()">Click Me</button> 

In raw js/html the equivalent of this will be

<button onclick="someAction()">Click Me</button>

The difference is that in raw js onclick event is run in the global scope - but the frameworks provide encapsulation.

So where is the problem?

The problem is when novice programmer who always heard that html-onclick is bad and who always use btn.addEventListener("onclick", ... ) wants to use some framework with templates (addEventListener also have drawbacks - if we update DOM in dynamic way using innerHTML= (which is pretty fast) - then we loose events handlers bind in that way). Then he will face something like bad-habits or wrong-approach to framework usage - and he will use framework in very bad way - because he will focus mainly on js-part and no on template-part (and produce unclear and hard to maintain code). To change this habits he will loose a lot of time (and probably he will need some luck and teacher).

So in my opinion, based on experience with my students, better would be for them if they use html-handlers-bind at the beginning. As I say it is true that handlers are call in global scope but a this stage students usually create small applications which are easy to control. To write bigger applications they choose some frameworks.

So what to do?

We can UPDATE the Unobtrusive JavaScript approach and allow bind event handlers (eventually with simple parameters) in html (but only bind handler - not put logic into onclick like in OP quesiton). So in my opinion in raw js/html this should be allowed

<button onclick="someAction(3)">Click Me</button>

or

_x000D_
_x000D_
function popup(num,str,event) {_x000D_
   let re=new RegExp(str);  _x000D_
   // ... _x000D_
   event.preventDefault();_x000D_
   console.log("link was clicked");_x000D_
}
_x000D_
<a href="https://example.com" onclick="popup(300,'map',event)">link</a>
_x000D_
_x000D_
_x000D_

But below examples should NOT be allowed

<button onclick="console.log('xx'); someAction(); return true">Click Me</button>

<a href="#" onclick="popup('/map/', 300, 300, 'map'); return false;">link</a>

The reality changes, our point of view should too

How to get the Touch position in android?

@Override
    public boolean onTouch(View v, MotionEvent event) {
       float x = event.getX();
       float y = event.getY();
       return true;
    }

How to set top position using jquery

Just for reference, if you are using:

 $(el).offset().top 

To get the position, it can be affected by the position of the parent element. Thus you may want to be consistent and use the following to set it:

$(el).offset({top: pos});

As opposed to the CSS methods above.

How to truncate milliseconds off of a .NET DateTime

DateTime d = DateTime.Now;
d = d.AddMilliseconds(-d.Millisecond);

Hide text using css

This worked for me with span (knockout validation).

<span class="validationMessage">This field is required.</span>

.validationMessage {
    background-image: url('images/exclamation.png');
    background-repeat: no-repeat;
    margin-left: 5px;
    width: 16px;
    height: 16px;
    vertical-align: top;

    /* Hide the text. */
    display: inline-block;
    overflow: hidden;
    font-size: 0px;
}

How to delete an SMS from the inbox in Android programmatically?

Use this function to delete specific message thread or modify according your needs:

public void delete_thread(String thread) 
{ 
  Cursor c = getApplicationContext().getContentResolver().query(
  Uri.parse("content://sms/"),new String[] { 
  "_id", "thread_id", "address", "person", "date","body" }, null, null, null);

 try {
  while (c.moveToNext()) 
      {
    int id = c.getInt(0);
    String address = c.getString(2);
    if (address.equals(thread)) 
        {
     getApplicationContext().getContentResolver().delete(
     Uri.parse("content://sms/" + id), null, null);
    }

       }
} catch (Exception e) {

  }
}

Call this function simply below:

delete_thread("54263726");//you can pass any number or thread id here

Don't forget to add android mainfest permission below:

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

Where value in column containing comma delimited values

Where value in column containing comma delimited values search with multiple comma delimited

            declare @d varchar(1000)='-11,-12,10,121'

            set @d=replace(@d,',',',%'' or '',''+a+'','' like ''%,')

            print @d
            declare @d1 varchar(5000)=
            'select * from (
            select ''1,21,13,12'' as a
            union
            select ''11,211,131,121''
            union
            select ''411,211,131,1211'') as t
             where '',''+a+'','' like ''%,'+@d+ ',%'''

             print @d1
             exec (@d1)

Gradients in Internet Explorer 9

Opera will soon start having builds available with gradient support, as well as other CSS features.

The W3C CSS Working Group is not even finished with CSS 2.1, y'all know that, right? We intend to be finished very soon. CSS3 is modularized precisely so we can move modules through to implementation faster rather than an entire spec.

Every browser company uses a different software cycle methodology, testing, and so on. So the process takes time.

I'm sure many, many readers well know that if you're using anything in CSS3, you're doing what's called "progressive enhancement" - the browsers with the most support get the best experience. The other part of that is "graceful degradation" meaning the experience will be agreeable but perhaps not the best or most attractive until that browser has implemented the module, or parts of the module that are relevant to what you want to do.

This creates quite an odd situation that unfortunately front-end devs get extremely frustrated by: inconsistent timing on implementations. So it's a real challenge on either side - do you blame the browser companies, the W3C, or worse yet - yourself (goodness knows we can't know it all!) Do those of us who are working for a browser company and W3C group members blame ourselves? You?

Of course not. It's always a game of balance, and as of yet, we've not as an industry figured out where that point of balance really is. That's the joy of working in evolutionary technology :)

Rails - Could not find a JavaScript runtime?

On the windows platform, I met that problem too The solution for me is just add

C:\Windows\System32

to the PATH

and restart the computer.

Range with step of type float

Here is a special case that might be good enough:

 [ (1.0/divStep)*x for x in range(start*divStep, stop*divStep)]

In your case this would be:

#for(float x = 0; x < 10; x += 0.5f) { /* ... */ } ==>
start = 0
stop  = 10
divstep = 1/.5 = 2 #This needs to be int, thats why I said 'special case'

and so:

>>> [ .5*x for x in range(0*2, 10*2)]
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

Its an XML namespace. It is required when you use XHTML 1.0 or 1.1 doctypes or application/xhtml+xml mimetypes.

You should be using HTML5 doctype, then you don't need it for text/html. Better start from template like this :

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8 />
        <title>domcument title</title>
        <link rel="stylesheet" href="/stylesheet.css" type="text/css" />
    </head>
    <body>
            <!-- your html content -->
            <script src="/script.js"></script>
    </body>
</html>



When you have put your Doctype straight - do and validate you html and your css .
That usually will sove you layout issues.

Append data to a POST NSURLRequest

Any one looking for a swift solution

let url = NSURL(string: "http://www.apple.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPBody = "company=Locassa&quality=AWESOME!".dataUsingEncoding(NSUTF8StringEncoding)

Rails 4 Authenticity Token

This official doc - talks about how to turn off forgery protection for api properly http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html

ALTER TABLE, set null in not null column, PostgreSQL 9.1

Execute the command in this format:

ALTER [ COLUMN ] column { SET | DROP } NOT NULL

Get current time as formatted string in Go?

To answer the exact question:

import "github.com/golang/protobuf/ptypes"

Timestamp, _ = ptypes.TimestampProto(time.Now())

Why is there no Constant feature in Java?

You can use static final to create something that works similar to Const, I have used this in the past.

protected static final int cOTHER = 0;
protected static final int cRPM = 1;
protected static final int cSPEED = 2;
protected static final int cTPS = 3;
protected int DataItemEnum = 0;

public static final int INVALID_PIN = -1;
public static final int LED_PIN = 0;

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

This is similar to my case, where I have a table named tabel_buku_besar. What I need are

  1. Looking for record that have account_code='101.100' in tabel_buku_besar which have companyarea='20000' and also have IDR as currency

  2. I need to get all record from tabel_buku_besar which have account_code same as step 1 but have transaction_number in step 1 result

while using select ... from...where....transaction_number in (select transaction_number from ....), my query running extremely slow and sometimes causing request time out or make my application not responding...

I try this combination and the result...not bad...

`select DATE_FORMAT(L.TANGGAL_INPUT,'%d-%m-%y') AS TANGGAL,
      L.TRANSACTION_NUMBER AS VOUCHER,
      L.ACCOUNT_CODE,
      C.DESCRIPTION,
      L.DEBET,
      L.KREDIT 
 from (select * from tabel_buku_besar A
                where A.COMPANYAREA='$COMPANYAREA'
                      AND A.CURRENCY='$Currency'
                      AND A.ACCOUNT_CODE!='$ACCOUNT'
                      AND (A.TANGGAL_INPUT BETWEEN STR_TO_DATE('$StartDate','%d/%m/%Y') AND STR_TO_DATE('$EndDate','%d/%m/%Y'))) L 
INNER JOIN (select * from tabel_buku_besar A
                     where A.COMPANYAREA='$COMPANYAREA'
                           AND A.CURRENCY='$Currency'
                           AND A.ACCOUNT_CODE='$ACCOUNT'
                           AND (A.TANGGAL_INPUT BETWEEN STR_TO_DATE('$StartDate','%d/%m/%Y') AND STR_TO_DATE('$EndDate','%d/%m/%Y'))) R ON R.TRANSACTION_NUMBER=L.TRANSACTION_NUMBER AND R.COMPANYAREA=L.COMPANYAREA 
LEFT OUTER JOIN master_account C ON C.ACCOUNT_CODE=L.ACCOUNT_CODE AND C.COMPANYAREA=L.COMPANYAREA 
ORDER BY L.TANGGAL_INPUT,L.TRANSACTION_NUMBER`

How to join multiple lines of file names into one with custom delimiter?

It looks like the answers already exist.

If you want a, b, c format, use ls -m ( Tulains Córdova’s answer)

Or if you want a b c format, use ls | xargs (simpified version of Chris J’s answer)

Or if you want any other delimiter like |, use ls | paste -sd'|' (application of Artem’s answer)

Check if a variable exists in a list in Bash

Assuming TARGET variable can be only 'binomial' or 'regression', then following would do:

# Check for modeling types known to this script
if [ $( echo "${TARGET}" | egrep -c "^(binomial|regression)$" ) -eq 0 ]; then
    echo "This scoring program can only handle 'binomial' and 'regression' methods now." >&2
    usage
fi

You could add more strings into the list by separating them with a | (pipe) character.

Advantage of using egrep, is that you could easily add case insensitivity (-i), or check more complex scenarios with a regular expression.

Pretty printing JSON from Jackson 2.2's ObjectMapper

if you are using spring and jackson combination you can do it as following. I'm following @gregwhitaker as suggested but implementing in spring style.

<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
    <property name="dateFormat">
        <bean class="java.text.SimpleDateFormat">
            <constructor-arg value="yyyy-MM-dd" />
            <property name="lenient" value="false" />
        </bean>
    </property>
    <property name="serializationInclusion">
        <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">
            NON_NULL
        </value>
    </property>
</bean>

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject">
        <ref bean="objectMapper" />
    </property>
    <property name="targetMethod">
        <value>enable</value>
    </property>
    <property name="arguments">
        <value type="com.fasterxml.jackson.databind.SerializationFeature">
            INDENT_OUTPUT
        </value>
    </property>
</bean>

In a bootstrap responsive page how to center a div

Not the best way ,but will still work

<div class="container-fluid h-100">
<div class="row h-100">
<div class="col-lg-12"></div>
<div class="col-lg-12">
<div class="row h-100">
  <div class="col-lg-4"></div>
  <div class="col-lg-4 border">
    This div is in middle
  </div>
  <div class="col-lg-4"></div>
</div>

</div>
<div class="col-lg-12"></div>
</div>

</div>

Place cursor at the end of text in EditText

The question is old and answered, but I think it may be useful to have this answer if you want to use the newly released DataBinding tools for Android, just set this in your XML :

<data>
    <variable name="stringValue" type="String"/>
</data>
...
<EditText
        ...
        android:text="@={stringValue}"
        android:selection="@{stringValue.length()}"
        ...
/>