Programs & Examples On #Law of demeter

The Law of Demeter (LoD) or Principle of Least Knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling.

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

Iterating through array - java

Since atleast Java 1.5.0 (Java 5) the code can be cleaned up a bit. Arrays and anything that implements Iterator (e.g. Collections) can be looped as such:

public static boolean inArray(int[] array, int check) {
   for (int o : array){
      if (o == check) {
         return true;
      }
   }
   return false;
}

In Java 8 you can also do something like:

// import java.util.stream.IntStream;

public static boolean inArray(int[] array, int check) {
   return IntStream.of(array).anyMatch(val -> val == check);
}

Although converting to a stream for this is probably overkill.

Working Soap client example

For Basic Authentication of WSDL the accepted answers code raises an error. Try the following instead

Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("username","password".toCharArray());
    }
});

Simple 3x3 matrix inverse code (C++)

I would also recommend Ilmbase, which is part of OpenEXR. It's a good set of templated 2,3,4-vector and matrix routines.

How can I get the height and width of an uiimage?

There are a lot of helpful solutions out there, but there is no simplified way with extension. Here is the code to solve the issue with an extension:

extension UIImage {

    var getWidth: CGFloat {
        get {
            let width = self.size.width
            return width
        }
    }

    var getHeight: CGFloat {
        get {
            let height = self.size.height
            return height
        }
    }
}

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

This can be accomplished in two steps:

1: select the element you want to change by either tagname, id, class etc.

var element = document.getElementsByTagName('h2')[0];

  1. remove the style attribute

element.removeAttribute('style');

In PowerShell, how can I test if a variable holds a numeric value?

If you want to check if a string has a numeric value, use this code:

$a = "44.4"
$b = "ad"
$rtn = ""
[double]::TryParse($a,[ref]$rtn)
[double]::TryParse($b,[ref]$rtn)

Credits go here

Using Spring MVC Test to unit test multipart POST request

If you are using Spring4/SpringBoot 1.x, then it's worth mentioning that you can add "text" (json) parts as well . This can be done via MockMvcRequestBuilders.fileUpload().file(MockMultipartFile file) (which is needed as method .multipart() is not available in this version):

@Test
public void test() throws Exception {

   mockMvc.perform( 
       MockMvcRequestBuilders.fileUpload("/files")
         // file-part
         .file(makeMultipartFile( "file-part" "some/path/to/file.bin", "application/octet-stream"))
        // text part
         .file(makeMultipartTextPart("json-part", "{ \"foo\" : \"bar\" }", "application/json"))
       .andExpect(status().isOk())));

   }

   private MockMultipartFile(String requestPartName, String filename, 
       String contentType, String pathOnClassPath) {

       return new MockMultipartFile(requestPartName, filename, 
          contentType, readResourceFile(pathOnClasspath);
   }

   // make text-part using MockMultipartFile
   private MockMultipartFile makeMultipartTextPart(String requestPartName, 
       String value, String contentType) throws Exception {

       return new MockMultipartFile(requestPartName, "", contentType,
               value.getBytes(Charset.forName("UTF-8")));   
   }


   private byte[] readResourceFile(String pathOnClassPath) throws Exception {
      return Files.readAllBytes(Paths.get(Thread.currentThread().getContextClassLoader()
         .getResource(pathOnClassPath).toUri()));
   }

}

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

As a workaround, follow the below steps:

  1. Go to the project directory
  2. Remove the node_modules directory: rm -rf node_modules
  3. Remove package-lock.json file: rm package-lock.json
  4. Clear the cache: npm cache clean --force
  5. Run npm install --verbose If after following the above steps still the issue exists then please provide us the output of installation command with --verbose.

How to check if object has any properties in JavaScript?

How about this?

var obj = {},
var isEmpty = !obj;
var hasContent = !!obj

How to change colour of blue highlight on select box dropdown

try this.. I know it's an old post but it might help somebody

select option:hover,
    select option:focus,
    select option:active {
        background: linear-gradient(#000000, #000000);
        background-color: #000000 !important; /* for IE */
        color: #ffed00 !important;
    }

    select option:checked {
        background: linear-gradient(#d6d6d6, #d6d6d6);
        background-color: #d6d6d6 !important; /* for IE */
        color: #000000 !important;
    }

How to change the text of a button in jQuery?

You can use

$("#btnAddProfile").text('Save');

although

$("#btnAddProfile").html('Save');

would work as well, but it's misleading (it gives the impression you could write something like

$("#btnAddProfile").html('Save <b>now</b>');

but of course you can't

Angular 6: How to set response type as text while making http call

On your backEnd, you should add:

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)

On the frontEnd (Service):

methodBlabla() 
{
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
  return this.http.get(this.url,{ headers, responseType: 'text'});
}

How to convert JSON data into a Python object

The lightest solution I think is

import json
from typing import NamedTuple

_j = '{"name":"????","age":37,"mother":{"name":"?????","age":58},"children":["????","?????","????"],"married": true,' \
     '"dog":null} '


class PersonNameAge(NamedTuple):
    name: str
    age: int


class UserInfo(NamedTuple):
    name: str
    age: int
    mother: PersonNameAge
    children: list
    married: bool
    dog: str


j = json.loads(_j)
u = UserInfo(**j)

print(u.name, u.age, u.mother, u.children, u.married, u.dog)

>>> Ivan 37 {'name': 'Olga', 'age': 58} ['Mary', 'Igor', 'Jane'] True None

Concatenating multiple text files into a single file in Bash

The most upvoted answers will fail if the file list is too long.

A more portable solution would be using fd

fd -e txt -d 1 -X awk 1 > combined.txt

-d 1 limits the search to the current directory. If you omit this option then it will recursively find all .txt files from the current directory.
-X (otherwise known as --exec-batch) executes a command (awk 1 in this case) for all the search results at once.

"break;" out of "if" statement?

I think the question is a little bit fuzzy - for example, it can be interpreted as a question about best practices in programming loops with if inside. So, I'll try to answer this question with this particular interpretation.

If you have if inside a loop, then in most cases you'd like to know how the loop has ended - was it "broken" by the if or was it ended "naturally"? So, your sample code can be modified in this way:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; break;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

The problem with this code is that the if statement is buried inside the loop body, and it takes some effort to locate it and understand what it does. A more clear (even without the break statement) variant will be:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX && !intMaxFound; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; continue;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

In this case you can clearly see (just looking at the loop "header") that this loop can end prematurely. If the loop body is a multi-page text, written by somebody else, then you'd thank its author for saving your time.

UPDATE:

Thanks to SO - it has just suggested the already answered question about crash of the AT&T phone network in 1990. It's about a risky decision of C creators to use a single reserved word break to exit from both loops and switch.

Anyway this interpretation doesn't follow from the sample code in the original question, so I'm leaving my answer as it is.

Run cron job only if it isn't already running

This one never failed me:

one.sh:

LFILE=/tmp/one-`echo "$@" | md5sum | cut -d\  -f1`.pid
if [ -e ${LFILE} ] && kill -0 `cat ${LFILE}`; then
   exit
fi

trap "rm -f ${LFILE}; exit" INT TERM EXIT
echo $$ > ${LFILE}

$@

rm -f ${LFILE}

cron job:

* * * * * /path/to/one.sh <command>

how to use python2.7 pip instead of default pip

An alternative is to call the pip module by using python2.7, as below:

python2.7 -m pip <commands>

For example, you could run python2.7 -m pip install <package> to install your favorite python modules. Here is a reference: https://stackoverflow.com/a/50017310/4256346.

In case the pip module has not yet been installed for this version of python, you can run the following:

python2.7 -m ensurepip

Running this command will "bootstrap the pip installer". Note that running this may require administrative privileges (i.e. sudo). Here is a reference: https://docs.python.org/2.7/library/ensurepip.html and another reference https://stackoverflow.com/a/46631019/4256346.

How to implement "Access-Control-Allow-Origin" header in asp.net

1.Install-Package Microsoft.AspNet.WebApi.Cors

2 . Add this code in WebApiConfig.cs.

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes

    config.EnableCors();

    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

3. Add this

using System.Web.Http.Cors; 

4. Add this code in Api Controller (HomeController.cs)

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class HomeController : ApiController
{
    [HttpGet]
    [Route("api/Home/test")]
    public string test()
    {
       return "";
    }
}

Detect encoding and make everything UTF-8

I find solution here http://deer.org.ua/2009/10/06/1/

class Encoding
{
    /**
     * http://deer.org.ua/2009/10/06/1/
     * @param $string
     * @return null
     */
    public static function detect_encoding($string)
    {
        static $list = ['utf-8', 'windows-1251'];

        foreach ($list as $item) {
            try {
                $sample = iconv($item, $item, $string);
            } catch (\Exception $e) {
                continue;
            }
            if (md5($sample) == md5($string)) {
                return $item;
            }
        }
        return null;
    }
}

$content = file_get_contents($file['tmp_name']);
$encoding = Encoding::detect_encoding($content);
if ($encoding != 'utf-8') {
    $result = iconv($encoding, 'utf-8', $content);
} else {
    $result = $content;
}

I think that @ is bad decision, and make some changes to solution from deer.org.ua;

(grep) Regex to match non-ASCII characters?

You could also to check this page: Unicode Regular Expressions, as it contains some useful Unicode characters classes, like:

\p{Control}: an ASCII 0x00..0x1F or Latin-1 0x80..0x9F control character.

Java SSLException: hostname in certificate didn't match

In httpclient-4.3.3.jar, there is another HttpClient to use:

public static void main (String[] args) throws Exception {
    // org.apache.http.client.HttpClient client = new DefaultHttpClient();
    org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
    System.out.println("HttpClient = " + client.getClass().toString());
    org.apache.http.client.methods.HttpPost post = new HttpPost("https://www.rideforrainbows.org/");
    org.apache.http.HttpResponse response = client.execute(post);
    java.io.InputStream is = response.getEntity().getContent();
    java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line;
    while ((line = rd.readLine()) != null) { 
        System.out.println(line);
    }
}

This HttpClientBuilder.create().build() will return org.apache.http.impl.client.InternalHttpClient. It can handle the this hostname in certificate didn't match issue.

How to access iOS simulator camera

Simulator doesn't have a Camera. If you want to access a camera you need a device. You can't test camera on simulator. You can only check the photo and video gallery.

How to display length of filtered ng-repeat data

You can do it with 2 ways. In template and in Controller. In template you can set your filtered array to another variable, then use it like you want. Here is how to do it:

<ul>
  <li data-ng-repeat="user in usersList = (users | gender:filterGender)" data-ng-bind="user.name"></li>
</ul>
 ....
<span>{{ usersList.length | number }}</span>

If you need examples, see the AngularJs filtered count examples/demos

How to download a file via FTP with Python ftplib

This is a Python code that is working fine for me. Comments are in Spanish but the app is easy to understand

# coding=utf-8

from ftplib import FTP                                                                      # Importamos la libreria ftplib desde FTP

import sys

def imprimirMensaje():                                                                      # Definimos la funcion para Imprimir el mensaje de bienvenida
    print "------------------------------------------------------"
    print "--               COMMAND LINE EXAMPLE               --"
    print "------------------------------------------------------"
    print ""
    print ">>>             Cliente FTP  en Python                "
    print ""
    print ">>> python <appname>.py <host> <port> <user> <pass>   "
    print "------------------------------------------------------"

def f(s):                                                                                   # Funcion para imprimir por pantalla los datos 
    print s

def download(j):                                                                            # Funcion para descargarnos el fichero que indiquemos según numero    
    print "Descargando=>",files[j]      
    fhandle = open(files[j], 'wb')
    ftp.retrbinary('RETR ' + files[j], fhandle.write)                                       # Imprimimos por pantalla lo que estamos descargando        #fhandle.close()
    fhandle.close()                                                     

ip          = sys.argv[1]                                                                   # Recogemos la IP       desde la linea de comandos sys.argv[1] 
puerto      = sys.argv[2]                                                                   # Recogemos el PUERTO   desde la linea de comandos sys.argv[2]
usuario     = sys.argv[3]                                                                   # Recogemos el USUARIO  desde la linea de comandos sys.argv[3]
password    = sys.argv[4]                                                                   # Recogemos el PASSWORD desde la linea de comandos sys.argv[4]


ftp = FTP(ip)                                                                               # Creamos un objeto realizando una instancia de FTP pasandole la IP
ftp.login(usuario,password)                                                                 # Asignamos al objeto ftp el usuario y la contraseña

files = ftp.nlst()                                                                          # Ponemos en una lista los directorios obtenidos del FTP

for i,v in enumerate(files,1):                                                              # Imprimimos por pantalla el listado de directorios enumerados
    print i,"->",v

print ""
i = int(raw_input("Pon un Nº para descargar el archivo or pulsa 0 para descargarlos\n"))    # Introducimos algun numero para descargar el fichero que queramos. Lo convertimos en integer

if i==0:                                                                                    # Si elegimos el valor 0 nos decargamos todos los ficheros del directorio                                                                               
    for j in range(len(files)):                                                             # Hacemos un for para la lista files y
        download(j)                                                                         # llamamos a la funcion download para descargar los ficheros
if i>0 and i<=len(files):                                                                   # Si elegimos unicamente un numero para descargarnos el elemento nos lo descargamos. Comprobamos que sea mayor de 0 y menor que la longitud de files 
    download(i-1)                                                                           # Nos descargamos i-1 por el tema que que los arrays empiezan por 0 

Gson: Is there an easier way to serialize a map

In Gson 2.7.2 it's as easy as

Gson gson = new Gson();
String serialized = gson.toJson(map);

Android ListView with different layouts for each row

I know how to create a custom row + custom array adapter to support a custom row for the entire list view. But how can one listview support many different row styles?

You already know the basics. You just need to get your custom adapter to return a different layout/view based on the row/cursor information being provided.

A ListView can support multiple row styles because it derives from AdapterView:

An AdapterView is a view whose children are determined by an Adapter.

If you look at the Adapter, you'll see methods that account for using row-specific views:

abstract int getViewTypeCount()
// Returns the number of types of Views that will be created ...

abstract int getItemViewType(int position)
// Get the type of View that will be created ...

abstract View getView(int position, View convertView, ViewGroup parent)
// Get a View that displays the data ...

The latter two methods provide the position so you can use that to determine the type of view you should use for that row.


Of course, you generally don't use AdapterView and Adapter directly, but rather use or derive from one of their subclasses. The subclasses of Adapter may add additional functionality that change how to get custom layouts for different rows. Since the view used for a given row is driven by the adapter, the trick is to get the adapter to return the desired view for a given row. How to do this differs depending on the specific adapter.

For example, to use ArrayAdapter,

  • override getView() to inflate, populate, and return the desired view for the given position. The getView() method includes an opportunity reuse views via the convertView parameter.

But to use derivatives of CursorAdapter,

  • override newView() to inflate, populate, and return the desired view for the current cursor state (i.e. the current "row") [you also need to override bindView so that widget can reuse views]

However, to use SimpleCursorAdapter,

  • define a SimpleCursorAdapter.ViewBinder with a setViewValue() method to inflate, populate, and return the desired view for a given row (current cursor state) and data "column". The method can define just the "special" views and defer to SimpleCursorAdapter's standard behavior for the "normal" bindings.

Look up the specific examples/tutorials for the kind of adapter you end up using.

How to remove html special chars?

<?php
function strip_only($str, $tags, $stripContent = false) {
    $content = '';
    if(!is_array($tags)) {
        $tags = (strpos($str, '>') !== false
                 ? explode('>', str_replace('<', '', $tags))
                 : array($tags));
        if(end($tags) == '') array_pop($tags);
    }
    foreach($tags as $tag) {
        if ($stripContent)
             $content = '(.+</'.$tag.'[^>]*>|)';
         $str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
    }
    return $str;
}

$str = '<font color="red">red</font> text';
$tags = 'font';
$a = strip_only($str, $tags); // red text
$b = strip_only($str, $tags, true); // text
?> 

inner join in linq to entities

public IList<Splitting> get(Guid companyId, long customrId) {    
    var res=from c in Customers_data_source
            where c.CustomerId = customrId && c.CompanyID == companyId
            from s in Splittings_data_srouce
            where s.CustomerID = c.CustomerID
            select s;

    return res.ToList();
}

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

First download this JavaScript code, JSON2.js, that will help us serialize the object into a string.

In my example I'm posting the rows of a jqGrid via Ajax:

    var commissions = new Array();
    // Do several row data and do some push. In this example is just one push.
    var rowData = $(GRID_AGENTS).getRowData(ids[i]);
    commissions.push(rowData);
    $.ajax({
        type: "POST",
        traditional: true,
        url: '<%= Url.Content("~/") %>' + AREA + CONTROLLER + 'SubmitCommissions',
        async: true,
        data: JSON.stringify(commissions),
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data.Result) {
                jQuery(GRID_AGENTS).trigger('reloadGrid');
            }
            else {
                jAlert("A problem ocurred during updating", "Commissions Report");
            }
        }
    });

Now on the controller:

    [HttpPost]
    [JsonFilter(Param = "commissions", JsonDataType = typeof(List<CommissionsJs>))]
    public ActionResult SubmitCommissions(List<CommissionsJs> commissions)
    {
        var result = dosomething(commissions);
        var jsonData = new
        {
            Result = true,
            Message = "Success"
        };
        if (result < 1)
        {
            jsonData = new
            {
                Result = false,
                Message = "Problem"
            };
        }
        return Json(jsonData);
    }

Create a JsonFilter Class (thanks to JSC reference).

    public class JsonFilter : ActionFilterAttribute
    {
        public string Param { get; set; }
        public Type JsonDataType { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
            {
                string inputContent;
                using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
                {
                    inputContent = sr.ReadToEnd();
                }
                var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);
                filterContext.ActionParameters[Param] = result;
            }
        }
    }

Create another class so the filter can parse the JSON string to the actual manipulable object: This class comissionsJS are all the rows of my jqGrid.

    public class CommissionsJs
    {
        public string Amount { get; set; }

        public string CheckNumber { get; set; }

        public string Contract { get; set; }
        public string DatePayed { get; set; }
        public string DealerName { get; set; }
        public string ID { get; set; }
        public string IdAgentPayment { get; set; }
        public string Notes { get; set; }
        public string PaymentMethodName { get; set; }
        public string RowNumber { get; set; }
        public string AgentId { get; set; }
    }

I hope this example helps to illustrate how to post a complex object.

How to scp in Python?

You could also check out paramiko. There's no scp module (yet), but it fully supports sftp.

[EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.

scp.py for paramiko

correct way to use super (argument passing)

As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object, all arguments have been eaten, and object.__init__ will be called without arguments (as it expects). So your code should look like this:

class A(object):
    def __init__(self, *args, **kwargs):
        print "A"
        super(A, self).__init__(*args, **kwargs)

class B(object):
    def __init__(self, *args, **kwargs):
        print "B"
        super(B, self).__init__(*args, **kwargs)

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print "C","arg=",arg
        super(C, self).__init__(*args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print "D", "arg=",arg
        super(D, self).__init__(*args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print "E", "arg=",arg
        super(E, self).__init__(*args, **kwargs)

print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)

Is it really impossible to make a div fit its size to its content?

You can use:

width: -webkit-fit-content;
height: -webkit-fit-content;
width: -moz-fit-content;
height: -moz-fit-content;

EDIT: No. see http://red-team-design.com/horizontal-centering-using-css-fit-content-value/

ALSO: http://dev.w3.org/csswg/css-box-3/

Add a column to existing table and uniquely number them on MS SQL Server

It would help if you posted what SQL database you're using. For MySQL you probably want auto_increment:

ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY

Not sure if this applies the values retroactively though. If it doesn't you should just be able to iterate over your values with a stored procedure or in a simple program (as long as no one else is writing to the database) and set use the LAST_INSERT_ID() function to generate the id value.

PHP - Merging two arrays into one array (also Remove Duplicates)

You can use this code to get the desired result. It will remove duplicates.

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result=array_unique(array_merge($a1,$a2));

print_r($result);

How to sort alphabetically while ignoring case sensitive?

In your case you have a List of Strings and most of the already proposed solutions (I specially like @guyblank answer) are just fine but!!!, if you have a List of beans, which is my case, you can use Comparable interface in your bean like this:

public class UserBean implements Comparable<UserBean> {

   private String name;
   private String surname;        
   private Integer phone;

   // GETTERS AND SETTERS

   public int compareTo(UserBean bean) {
       return name.compareToIgnoreCase(bean.name);
   }

}

Then you only need to create your ArrayList<UserBean> userBeanArray = new ArrayList<UserBean>();, fill it and sort it: Collections.sort(userBeanArray);

And you have it done!

Hope to help to community ;-)

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

Converting from longitude\latitude to Cartesian coordinates

If you care about getting coordinates based on an ellipsoid rather than a sphere, take a look at Geographic_coordinate_conversion - it gives the formulae. GEodetic Datum has the WGS84 constants you need for the conversion.

The formulae there also take into account the altitude relative to the reference ellipsoid surface (useful if you are getting altitude data from a GPS device).

How generate unique Integers based on GUIDs

In a static class, keep a static const integer, then add 1 to it before every single access (using a public get property). This will ensure you cycle the whole int range before you get a non-unique value.

    /// <summary>
    /// The command id to use. This is a thread-safe id, that is unique over the lifetime of the process. It changes
    /// at each access.
    /// </summary>
    internal static int NextCommandId
    {
        get
        {
            return _nextCommandId++;
        }
    }       
    private static int _nextCommandId = 0;

This will produce a unique integer value within a running process. Since you do not explicitly define how unique your integer should be, this will probably fit.

Using "Object.create" instead of "new"

Another possible usage of Object.create is to clone immutable objects in a cheap and effective way.

var anObj = {
    a: "test",
    b: "jest"
};

var bObj = Object.create(anObj);

bObj.b = "gone"; // replace an existing (by masking prototype)
bObj.c = "brand"; // add a new to demonstrate it is actually a new obj

// now bObj is {a: test, b: gone, c: brand}

Notes: The above snippet creates a clone of an source object (aka not a reference, as in cObj = aObj). It benefits over the copy-properties method (see 1), in that it does not copy object member properties. Rather it creates another -destination- object with it's prototype set on the source object. Moreover when properties are modified on the dest object, they are created "on the fly", masking the prototype's (src's) properties.This constitutes a fast an effective way of cloning immutable objects.

The caveat here is that this applies to source objects that should not be modified after creation (immutable). If the source object is modified after creation, all the clone's unmasked properties will be modified, too.

Fiddle here(http://jsfiddle.net/y5b5q/1/) (needs Object.create capable browser).

How can I convert ticks to a date format?

Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.

public class Time
{
    public static void Timestamps()
    {
        OutputTimestamp();
        Thread.Sleep(1000);
        OutputTimestamp();
    }

    private static void OutputTimestamp()
    {
        var timestamp = DateTime.UtcNow.Ticks;
        var localTicks = DateTime.Now.Ticks;
        var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
        Console.Out.WriteLine("Timestamp = {0}.  Local ticks = {1}.  Local time = {2}.", timestamp, localTicks, localTime);
    }
}

Output:

Timestamp = 636988286338754530.  Local ticks = 636988034338754530.  Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736.  Local ticks = 636988034348878736.  Local time = 2019-07-15 4:03:54 PM.

Installing Java on OS X 10.9 (Mavericks)

I downloaded and installed the JDK 1.7 from Oracle. In the console / in Terminal Java 7 works fine.

When I start a Java program (like Eclipse) via the GUI, I get:

To open "Eclipse.app" you need a Java SE 6 runtime. Would you like to install one now?

Because I did not want to install old Java version, I used the following workaround:

sudo ln -nsf /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK

Credits to monkehWorks.

What are all the uses of an underscore in Scala?

An excellent explanation of the uses of the underscore is Scala _ [underscore] magic.

Examples:

 def matchTest(x: Int): String = x match {
     case 1 => "one"
     case 2 => "two"
     case _ => "anything other than one and two"
 }

 expr match {
     case List(1,_,_) => " a list with three element and the first element is 1"
     case List(_*)  => " a list with zero or more elements "
     case Map[_,_] => " matches a map with any key type and any value type "
     case _ =>
 }

 List(1,2,3,4,5).foreach(print(_))
 // Doing the same without underscore: 
 List(1,2,3,4,5).foreach( a => print(a))

In Scala, _ acts similar to * in Java while importing packages.

// Imports all the classes in the package matching
import scala.util.matching._

// Imports all the members of the object Fun (static import in Java).
import com.test.Fun._

// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }

// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }

In Scala, a getter and setter will be implicitly defined for all non-private vars in a object. The getter name is same as the variable name and _= is added for the setter name.

class Test {
    private var a = 0
    def age = a
    def age_=(n:Int) = {
            require(n>0)
            a = n
    }
}

Usage:

val t = new Test
t.age = 5
println(t.age)

If you try to assign a function to a new variable, the function will be invoked and the result will be assigned to the variable. This confusion occurs due to the optional braces for method invocation. We should use _ after the function name to assign it to another variable.

class Test {
    def fun = {
        // Some code
    }
    val funLike = fun _
}

Capitalize first letter. MySQL

This should work nicely:

UPDATE tb_Company SET CompanyIndustry = 
CONCAT(UPPER(LEFT(CompanyIndustry, 1)), SUBSTRING(CompanyIndustry, 2))

Padding In bootstrap

The suggestion from @Dawood is good if that works for you.

If you need more fine-tuning than that, one option is to use padding on the text elements, here's an example: http://jsfiddle.net/panchroma/FtBwe/

CSS

p, h2 {
    padding-left:10px;
}

SQL query for today's date minus two months

TSQL, Alternative using variable declaration. (it might improve Query's readability)

DECLARE @gapPeriod DATETIME = DATEADD(MONTH,-2,GETDATE()); --Period:Last 2 months.

SELECT 
        *
    FROM 
        FB as A
    WHERE
        A.Dte <= @gapPeriod;                               --only older records.

can't multiply sequence by non-int of type 'float'

You're multipling your "1 + 0.01" times the growthRate list, not the item in the list you're iterating through. I've renamed i to rate and using that instead. See the updated code below:

def nestEgVariable(salary, save, growthRates):
    SavingsRecord = []
    fund = 0
    depositPerYear = salary * save * 0.01
    #    V-- rate is a clearer name than i here, since you're iterating through the rates contained in the growthRates list
    for rate in growthRates:  
        #                           V-- Use the `rate` item in the growthRate list you're iterating through rather than multiplying by the `growthRate` list itself.
        fund = fund * (1 + 0.01 * rate) + depositPerYear
        SavingsRecord += [fund,]
    return SavingsRecord 


print nestEgVariable(10000,10,[3,4,5,0,3])

Usage of $broadcast(), $emit() And $on() in AngularJS

  • Broadcast: We can pass the value from parent to child (i.e parent -> child controller.)
  • Emit: we can pass the value from child to parent (i.e.child ->parent controller.)
  • On: catch the event dispatched by $broadcast or $emit.

How to extract HTTP response body from a Python requests call?


import requests

site_request = requests.get("https://abhiunix.in")

site_response = str(site_request.content)

print(site_response)

You can do it either way.

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

For those who didn't solve the problem setting route middleware in App\Http\Kernel, try to set global middleware. In App\Http\Middleware\Cors:

public function handle($request, Closure $next)
{
    return $next($request)->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}

In App\Http\Kernel:

protected $middleware = [
    ...
    \App\Http\Middleware\Cors::class,
];

How store a range from excel into a Range variable?

When you use a Range object, you cannot simply use the following syntax:

Dim myRange as Range
myRange = Range("A1")  

You must use the set keyword to assign Range objects:

Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)

    Dim dataTable As Range
    Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

    Set getData = dataTable

End Function

Sub main()
    Dim test As Range

    Set test = getData(ActiveSheet, 1, 3, 2, 5)
    test.select

End Sub

Note that every time a range is declared I use the Set keyword.


You can also allow your getData function to return a Range object instead of a Variant although this is unrelated to the problem you are having.

SQL Query Where Date = Today Minus 7 Days

You can use the CURDATE() and DATE_SUB() functions to achieve this:

SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()    
GROUP BY URLx
ORDER BY Count DESC; 

Class name does not name a type in C++

NOTE: Because people searching with the same keyword will land on this page, I am adding this answer which is not the cause for this compiler error in the above mentioned case.

I was facing this error when I had an enum declared in some file which had one of the elements having the same symbol as my class name.

e.g. if I declare an enum = {A, B, C} in some file which is included in another file where I declare an object of class A.

This was throwing the same compiler error message mentioning that Class A does not name a type. There was no circular dependency in my case.

So, be careful while naming classes and declaring enums (which might be visible, imported and used externally in other files) in C++.

Java error: Implicit super constructor is undefined for default constructor

Sorry for necroposting but faced this problem just today. For everybody also facing with this problem - one of he possible reasons - you don't call super at the first line of method. Second, third and other lines fire this error. Call of super should be very first call in your method. In this case everything is well.

Maximum size of an Array in Javascript

No need to trim the array, simply address it as a circular buffer (index % maxlen). This will ensure it never goes over the limit (implementing a circular buffer means that once you get to the end you wrap around to the beginning again - not possible to overrun the end of the array).

For example:

var container = new Array ();
var maxlen = 100;
var index = 0;

// 'store' 1538 items (only the last 'maxlen' items are kept)
for (var i=0; i<1538; i++) {
   container [index++ % maxlen] = "storing" + i;
}

// get element at index 11 (you want the 11th item in the array)
eleventh = container [(index + 11) % maxlen];

// get element at index 11 (you want the 11th item in the array)
thirtyfifth = container [(index + 35) % maxlen];

// print out all 100 elements that we have left in the array, note
// that it doesn't matter if we address past 100 - circular buffer
// so we'll simply get back to the beginning if we do that.
for (i=0; i<200; i++) {
   document.write (container[(index + i) % maxlen] + "<br>\n");
}

Show animated GIF

This work for me!

public void showLoader(){
        URL url = this.getClass().getResource("images/ajax-loader.gif");
        Icon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);
        frameLoader.setUndecorated(true);
        frameLoader.getContentPane().add(label);
        frameLoader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frameLoader.pack();
        frameLoader.setLocationRelativeTo(null);
        frameLoader.setVisible(true);
    }

When should I use GC.SuppressFinalize()?

Dispose(true);
GC.SuppressFinalize(this);

If object has finalizer, .net put a reference in finalization queue.

Since we have call Dispose(ture), it clear object, so we don't need finalization queue to do this job.

So call GC.SuppressFinalize(this) remove reference in finalization queue.

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

HTML5 record audio to file

This is a simple JavaScript sound recorder and editor. You can try it.

https://www.danieldemmel.me/JSSoundRecorder/

Can download from here

https://github.com/daaain/JSSoundRecorder

CSS transition between left -> right and top -> bottom positions

This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.

topleft {
  top: 0%;
  left: 0%;
}
bottomright {
  top: 100%;
  left: 100%;
  -webkit-transform: translate(-100%,-100%);
}

add string to String array

You cannot resize an array in java.

Once the size of array is declared, it remains fixed.

Instead you can use ArrayList that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.

ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);

String s4 ="Test4";
ar.add(s4);

CSS override rules and specificity

To give the second rule higher specificity you can always use parts of the first rule. In this case I would add table.rule1 trfrom rule one and add it to rule two.

table.rule1 tr td {
    background-color: #ff0000;
}

table.rule1 tr td.rule2 {
    background-color: #ffff00;
}

After a while I find this gets natural, but I know some people disagree. For those people I would suggest looking into LESS or SASS.

Convert List into Comma-Separated String

categories = ['sprots', 'news'];
categoriesList = ", ".join(categories)
print(categoriesList)

This is the output: sprots, news

Align contents inside a div

Here is a technique I use that has worked well:

_x000D_
_x000D_
<div>_x000D_
    <div style="display: table-cell; width: 100%">&nbsp;</div>_x000D_
    <div style="display: table-cell; white-space: nowrap;">Something Here</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SSL cert "err_cert_authority_invalid" on mobile chrome only

Just do the following for Version 44.0.2403.155 dev-m

Privacy -->Content settings -->Do not allow any site to run JavaScript

Problem Solved

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

I have an undergraduate degree from a cheap "mass market" US university, so I'd say I fall into the middle of the user intelligence (or at least education) scale :) I've been dabbling with Scala for just a few months and have worked on two or three non-trivial apps.

Especially now that IntelliJ has released their fine IDE with what IMHO is currently the best Scala plugin, Scala development is relatively painless:

  • I find I can use Scala as a "Java without semicolons," i.e. I write similar-looking code to what I'd do in Java, and benefit a little from syntactic brevity such as that gained by type inference. Exception handling, when I do it at all, is more convenient. Class definition is much less verbose without the getter/setter boilerplate.

  • Once in a while I manage to write a single line to accomplish the equivalent of multiple lines of Java. Where applicable, chains of functional methods like map, fold, collect, filter etc. are fun to compose and elegant to behold.

  • Only rarely do I find myself benefitting from Scala's more high-powered features: Closures and partial (or curried) functions, pattern matching... that kinda thing.

As a newbie, I continue to struggle with the terse and idiomatic syntax. Method calls without parameters don't need parentheses except where they do; cases in the match statement need a fat arrow ( => ), but there are also places where you need a thin arrow ( -> ). Many methods have short but rather cryptic names like /: or \: - I can get my stuff done if I flip enough manual pages, but some of my code ends up looking like Perl or line noise. Ironically, one of the most popular bits of syntactic shorthand is missing in action: I keep getting bitten by the fact that Int doesn't define a ++ method.

This is just my opinion: I feel like Scala has the power of C++ combined with the complexity and readability of C++. The syntactic complexity of the language also makes the API documentation hard to read.

Scala is very well thought out and brilliant in many respects. I suspect many an academic would love to program in it. However, it's also full of cleverness and gotchas, it has a much higher learning curve than Java and is harder to read. If I scan the fora and see how many developers are still struggling with the finer points of Java, I cannot conceive of Scala ever becoming a mainstream language. No company will be able to justify sending its developers on a 3 week Scala course when formerly they only needed a 1 week Java course.

Sending emails with Javascript

The way I'm doing it now is basically like this:

The HTML:

<textarea id="myText">
    Lorem ipsum...
</textarea>
<button onclick="sendMail(); return false">Send</button>

The Javascript:

function sendMail() {
    var link = "mailto:[email protected]"
             + "[email protected]"
             + "&subject=" + encodeURIComponent("This is my subject")
             + "&body=" + encodeURIComponent(document.getElementById('myText').value)
    ;
    
    window.location.href = link;
}

This, surprisingly, works rather well. The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it. I suspect that it'd be to do with the maximum length of the URL being exceeded.

How to set a variable to current date and date-1 in linux?

You can also use the shorter format

From the man page:

%F     full date; same as %Y-%m-%d

Example:

#!/bin/bash
date_today=$(date +%F)
date_dir=$(date +%F -d yesterday)

SDK Manager.exe doesn't work

Step #1: Open up a command prompt.

Step #2: Use the cd command to move to wherever you installed your Android SDK.

Step #3: Run tools\android.

If that does not work, you should have information dumped to the command prompt that will help you diagnose your setup problem.

Describe table structure

For Sybase aka SQL Anywhere the following command outputs the structure of a table:

DESCRIBE 'TABLE_NAME';

python tuple to dict

Even more concise if you are on python 2.7:

>>> t = ((1,'a'),(2,'b'))
>>> {y:x for x,y in t}
{'a':1, 'b':2}

Styling twitter bootstrap buttons

Here is a very easy and eficient way: add in your CSS your class with the colors you want to apply to your button:

.my-btn{
    background: #0099cc;
    color: #ffffff;
}
.my-btn:hover { 
  border-color: #C0C0C0; 
  background-color: #C0C0C0; 
}

and add the style to your bootstrap button or link:

<a href="xxx" class="btn btn-info my-btn">aaa</a>

How do I retrieve a textbox value using JQuery?

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

var txt=$('input:text[name=DrugDurationLength]').val();

How to change python version in anaconda spyder

In Preferences, select Python Interpreter

Under Python Interpreter, change from "Default" to "Use the following Python interpreter"

The path there should be the default Python executable. Find your Python 2.7 executable and use that.

Removing duplicates from a SQL query (not just "use distinct")

Your question is kind of confusing; do you want to show only one row per user, or do you want to show a row per picture but suppress repeating values in the U.NAME field? I think you want the second; if not there are plenty of answers for the first.

Whether to display repeating values is display logic, which SQL wasn't really designed for. You can use a cursor in a loop to process the results row-by-row, but you will lose a lot of performance. If you have a "smart" frontend language like a .NET language or Java, whatever construction you put this data into can be cheaply manipulated to suppress repeating values before finally displaying it in the UI.

If you're using Microsoft SQL Server, and the transformation HAS to be done at the data layer, you may consider using a CTE (Computed Table Expression) to hold the initial query, then select values from each row of the CTE based on whether the columns in the previous row hold the same data. It'll be more performant than the cursor, but it'll be kinda messy either way. Observe:

USING CTE (Row, Name, PicID)
AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY U.NAME, P.PIC_ID),
       U.NAME, P.PIC_ID
    FROM USERS U
        INNER JOIN POSTINGS P1
            ON U.EMAIL_ID = P1.EMAIL_ID
        INNER JOIN PICTURES P
            ON P1.PIC_ID = P.PIC_ID
    WHERE P.CAPTION LIKE '%car%'
    ORDER BY U.NAME, P.PIC_ID 
)
SELECT
    CASE WHEN current.Name == previous.Name THEN '' ELSE current.Name END,
    current.PicID
FROM CTE current
LEFT OUTER JOIN CTE previous
   ON current.Row = previous.Row + 1
ORDER BY current.Row

The above sample is TSQL-specific; it is not guaranteed to work in any other DBPL like PL/SQL, but I think most of the enterprise-level SQL engines have something similar.

How to view AndroidManifest.xml from APK file?

There is an online tool that lets you upload an APK It decompiles it and finally lets you to download a zip with all sources, manifest XML file and so on decompiled, all of that without having to install any program on your computer: http://www.javadecompilers.com/apk

Also if you wish just to check on some params you can, by their UI

Send request to curl with post data sourced from a file

If you are using form data to upload file,in which a parameter name must be specified , you can use:

curl -X POST -i -F "parametername=@filename" -F "additional_parm=param2" host:port/xxx

How to upload a file using Java HttpClient library working with PHP

I knew I am late to the party but below is the correct way to deal with this, the key is to use InputStreamBody in place of FileBody to upload multi-part file.

   try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("https://someserver.com/api/path/");
        postRequest.addHeader("Authorization",authHeader);
        //don't set the content type here            
        //postRequest.addHeader("Content-Type","multipart/form-data");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);


        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        reqEntity.addPart("parm-name", new InputStreamBody(fileInputStream,"image/jpeg","file_name.jpg"));

        postRequest.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(postRequest);

        }catch(Exception e) {
            Log.e("URISyntaxException", e.toString());
   }

How to send email in ASP.NET C#

You can try MailKit MailKit is an Open Source cross-platform .NET mail-client library that is based on MimeKit and optimized for mobile devices. You can use easily in your application.You can download from here.

                MimeMessage mailMessage = new MimeMessage();
                mailMessage.From.Add(new MailboxAddress(fromName, [email protected]));
                mailMessage.Sender = new MailboxAddress(senderName, [email protected]);
                mailMessage.To.Add(new MailboxAddress(emailid, emailid));
                mailMessage.Subject = subject;
                mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
                mailMessage.Subject = subject;
                var builder = new BodyBuilder();
                builder.TextBody = "Hello There";           
                try
                {
                    using (var smtpClient = new SmtpClient())
                    {
                        smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
                        smtpClient.Authenticate("[email protected]", "password");

                        smtpClient.Send(mailMessage);
                        Console.WriteLine("Success");
                    }
                }
                catch (SmtpCommandException ex)
                {
                    Console.WriteLine(ex.ToString());              
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());                
                }              

C# Macro definitions in Preprocessor

No, C# does not support preprocessor macros like C. Visual Studio on the other hand has snippets. Visual Studio's snippets are a feature of the IDE and are expanded in the editor rather than replaced in the code on compilation by a preprocessor.

Detect changed input text box

I think you can use keydown too:

$('#fieldID').on('keydown', function (e) {
  //console.log(e.which);
  if (e.which === 8) {
    //do something when pressing delete
    return true;
  } else {
    //do something else
    return false;
  }
});

Why use Ruby's attr_accessor, attr_reader and attr_writer?

All of the answers above are correct; attr_reader and attr_writer are more convenient to write than manually typing the methods they are shorthands for. Apart from that they offer much better performance than writing the method definition yourself. For more info see slide 152 onwards from this talk (PDF) by Aaron Patterson.

What is the meaning of prepended double colon "::"?

Lots of reasonable answers already. I'll chip in with an analogy that may help some readers. :: works a lot like the filesystem directory separator '/', when searching your path for a program you'd like to run. Consider:

/path/to/executable

This is very explicit - only an executable at that exact location in the filesystem tree can match this specification, irrespective of the PATH in effect. Similarly...

::std::cout

...is equally explicit in the C++ namespace "tree".

Contrasting with such absolute paths, you can configure good UNIX shells (e.g. zsh) to resolve relative paths under your current directory or any element in your PATH environment variable, so if PATH=/usr/bin:/usr/local/bin, and you were "in" /tmp, then...

X11/xterm

...would happily run /tmp/X11/xterm if found, else /usr/bin/X11/xterm, else /usr/local/bin/X11/xterm. Similarly, say you were in a namespace called X, and had a "using namespace Y" in effect, then...

std::cout

...could be found in any of ::X::std::cout, ::std::cout, ::Y::std::cout, and possibly other places due to argument-dependent lookup (ADL, aka Koenig lookup). So, only ::std::cout is really explicit about exactly which object you mean, but luckily nobody in their right mind would ever create their own class/struct or namespace called "std", nor anything called "cout", so in practice using only std::cout is fine.

Noteworthy differences:

1) shells tend to use the first match using the ordering in PATH, whereas C++ gives a compiler error when you've been ambiguous.

2) In C++, names without any leading scope can be matched in the current namespace, while most UNIX shells only do that if you put . in the PATH.

3) C++ always searches the global namespace (like having / implicitly your PATH).

General discussion on namespaces and explicitness of symbols

Using absolute ::abc::def::... "paths" can sometimes be useful to isolate you from any other namespaces you're using, part of but don't really have control over the content of, or even other libraries that your library's client code also uses. On the other hand, it also couples you more tightly to the existing "absolute" location of the symbol, and you miss the advantages of implicit matching in namespaces: less coupling, easier mobility of code between namespaces, and more concise, readable source code.

As with many things, it's a balancing act. The C++ Standard puts lots of identifiers under std:: that are less "unique" than cout, that programmers might use for something completely different in their code (e.g. merge, includes, fill, generate, exchange, queue, toupper, max). Two unrelated non-Standard libraries have a far higher chance of using the same identifiers as the authors are generally un- or less-aware of each other. And libraries - including the C++ Standard library - change their symbols over time. All this potentially creates ambiguity when recompiling old code, particularly when there's been heavy use of using namespaces: the worst thing you can do in this space is allow using namespaces in headers to escape the headers' scopes, such that an arbitrarily large amount of direct and indirect client code is unable to make their own decisions about which namespaces to use and how to manage ambiguities.

So, a leading :: is one tool in the C++ programmer's toolbox to actively disambiguate a known clash, and/or eliminate the possibility of future ambiguity....

How is a JavaScript hash map implemented?

every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:

var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;

javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode() function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)

2020 Update:

javascript today supports other datatypes as well: Map and WeakMap. They behave more closely as hash maps than traditional objects.

What is the difference between <html lang="en"> and <html lang="en-US">?

This should help : http://www.w3.org/International/articles/language-tags/

The golden rule when creating language tags is to keep the tag as short as possible. Avoid region, script or other subtags except where they add useful distinguishing information. For instance, use ja for Japanese and not ja-JP, unless there is a particular reason that you need to say that this is Japanese as spoken in Japan, rather than elsewhere.

The list below shows the various types of subtag that are available. We will work our way through these and how they are used in the sections that follow.

language-extlang-script-region-variant-extension-privateuse

Align items in a stack panel?

This works perfectly for me. Just put the button first since you're starting on the right. If FlowDirection becomes a problem just add a StackPanel around it and specify FlowDirection="LeftToRight" for that portion. Or simply specify FlowDirection="LeftToRight" for the relevant control.

<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" FlowDirection="RightToLeft">
    <Button Width="40" HorizontalAlignment="Right" Margin="3">Right</Button>
    <TextBlock Margin="5">Left</TextBlock>
    <StackPanel FlowDirection="LeftToRight">
        <my:DatePicker Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />    
    </StackPanel>
    <my:DatePicker FlowDirection="LeftToRight" Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />    
</StackPanel>

Set value of textarea in jQuery

We can either use .val() or .text() methods to set values. we need to put value inside val() like val("hello").

  $(document).ready(function () {
    $("#submitbtn").click(function () {
      var inputVal = $("#inputText").val();
      $("#txtMessage").val(inputVal);
    });
  });

Check example here: http://www.codegateway.com/2012/03/set-value-to-textarea-jquery.html

How to dump a table to console?

I have humbly modified a bit Alundaio code:

-- by Alundaio
-- KK modified 11/28/2019

function dump_table_to_string(node, tree, indentation)
    local cache, stack, output = {},{},{}
    local depth = 1


    if type(node) ~= "table" then
        return "only table type is supported, got " .. type(node)
    end

    if nil == indentation then indentation = 1 end

    local NEW_LINE = "\n"
    local TAB_CHAR = " "

    if nil == tree then
        NEW_LINE = "\n"
    elseif not tree then
        NEW_LINE = ""
        TAB_CHAR = ""
    end

    local output_str = "{" .. NEW_LINE

    while true do
        local size = 0
        for k,v in pairs(node) do
            size = size + 1
        end

        local cur_index = 1
        for k,v in pairs(node) do
            if (cache[node] == nil) or (cur_index >= cache[node]) then

                if (string.find(output_str,"}",output_str:len())) then
                    output_str = output_str .. "," .. NEW_LINE
                elseif not (string.find(output_str,NEW_LINE,output_str:len())) then
                    output_str = output_str .. NEW_LINE
                end

                -- This is necessary for working with HUGE tables otherwise we run out of memory using concat on huge strings
                table.insert(output,output_str)
                output_str = ""

                local key
                if (type(k) == "number" or type(k) == "boolean") then
                    key = "["..tostring(k).."]"
                else
                    key = "['"..tostring(k).."']"
                end

                if (type(v) == "number" or type(v) == "boolean") then
                    output_str = output_str .. string.rep(TAB_CHAR,depth*indentation) .. key .. " = "..tostring(v)
                elseif (type(v) == "table") then
                    output_str = output_str .. string.rep(TAB_CHAR,depth*indentation) .. key .. " = {" .. NEW_LINE
                    table.insert(stack,node)
                    table.insert(stack,v)
                    cache[node] = cur_index+1
                    break
                else
                    output_str = output_str .. string.rep(TAB_CHAR,depth*indentation) .. key .. " = '"..tostring(v).."'"
                end

                if (cur_index == size) then
                    output_str = output_str .. NEW_LINE .. string.rep(TAB_CHAR,(depth-1)*indentation) .. "}"
                else
                    output_str = output_str .. ","
                end
            else
                -- close the table
                if (cur_index == size) then
                    output_str = output_str .. NEW_LINE .. string.rep(TAB_CHAR,(depth-1)*indentation) .. "}"
                end
            end

            cur_index = cur_index + 1
        end

        if (size == 0) then
            output_str = output_str .. NEW_LINE .. string.rep(TAB_CHAR,(depth-1)*indentation) .. "}"
        end

        if (#stack > 0) then
            node = stack[#stack]
            stack[#stack] = nil
            depth = cache[node] == nil and depth + 1 or depth - 1
        else
            break
        end
    end

    -- This is necessary for working with HUGE tables otherwise we run out of memory using concat on huge strings
    table.insert(output,output_str)
    output_str = table.concat(output)

    return output_str

end

then:

print(dump_table_to_string("AA", true,3))

print(dump_table_to_string({"AA","BB"}, true,3))

print(dump_table_to_string({"AA","BB"}))

print(dump_table_to_string({"AA","BB"},false))

print(dump_table_to_string({"AA","BB",{22,33}},true,2))

gives:

only table type is supported, got string

{
   [1] = 'AA',
   [2] = 'BB'
}

{
 [1] = 'AA',
 [2] = 'BB'
}

{[1] = 'AA',[2] = 'BB'}

{
  [1] = 'AA',
  [2] = 'BB',
  [3] = {
    [1] = 22,
    [2] = 33
  }
}

How to create an Array, ArrayList, Stack and Queue in Java?

Without more details as to what the question is exactly asking, I am going to answer the title of the question,

Create an Array:

String[] myArray = new String[2];
int[] intArray = new int[2];

// or can be declared as follows
String[] myArray = {"this", "is", "my", "array"};
int[] intArray = {1,2,3,4};

Create an ArrayList:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");

ArrayList<Integer> myNum = new ArrayList<Integer>();
myNum.add(1);
myNum.add(2);

This means, create an ArrayList of String and Integer objects. You cannot use int because thats a primitive data types, see the link for a list of primitive data types.

Create a Stack:

Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);

Create an Queue: (using LinkedList)

Queue<String> myQueue = new LinkedList<String>();
Queue<Integer> myNumbers = new LinkedList<Integer>();
myQueue.add("Hello");
myQueue.add("World");
myNumbers.add(1);
myNumbers.add(2);

Same thing as an ArrayList, this declaration means create an Queue of String and Integer objects.


Update:

In response to your comment from the other given answer,

i am pretty confused now, why are using string. and what does <String> means

We are using String only as a pure example, but you can add any other object, but the main point is that you use an object not a primitive type. Each primitive data type has their own primitive wrapper class, see link for list of primitive data type's wrapper class.

I have posted some links to explain the difference between the two, but here are a list of primitive types

  • byte
  • short
  • char
  • int
  • long
  • boolean
  • double
  • float

Which means, you are not allowed to make an ArrayList of integer's like so:

ArrayList<int> numbers = new ArrayList<int>(); 
           ^ should be an object, int is not an object, but Integer is!
ArrayList<Integer> numbers = new ArrayList<Integer>();
            ^ perfectly valid

Also, you can use your own objects, here is my Monster object I created,

public class Monster {
   String name = null;
   String location = null;
   int age = 0;

public Monster(String name, String loc, int age) { 
   this.name = name;
   this.loc = location;
   this.age = age;
 }

public void printDetails() {
   System.out.println(name + " is from " + location +
                                     " and is " + age + " old.");
 }
} 

Here we have a Monster object, but now in our Main.java class we want to keep a record of all our Monster's that we create, so let's add them to an ArrayList

public class Main {
    ArrayList<Monster> myMonsters = new ArrayList<Monster>();

public Main() {
    Monster yetti = new Monster("Yetti", "The Mountains", 77);
    Monster lochness = new Monster("Lochness Monster", "Scotland", 20);

    myMonsters.add(yetti); // <-- added Yetti to our list
    myMonsters.add(lochness); // <--added Lochness to our list
  
    for (Monster m : myMonsters) {
        m.printDetails();
     }
   }

public static void main(String[] args) {
    new Main();
 }
}

(I helped my girlfriend's brother with a Java game, and he had to do something along those lines as well, but I hope the example was well demonstrated)

Create an Excel file using vbscripts

'Create Excel

Set objExcel = Wscript.CreateObject("Excel.Application")

objExcel.visible = True

Set objWb = objExcel.Workbooks.Add

objWb.Saveas("D:\Example.xlsx")

objExcel.Quit

SQL grouping by all the columns

The DISTINCT Keyword


I believe what you are trying to do is:

SELECT DISTINCT * FROM MyFooTable;

If you group by all columns, you are just requesting that duplicate data be removed.

For example a table with the following data:

 id |     value      
----+----------------
  1 | foo
  2 | bar
  1 | foo
  3 | something else

If you perform the following query which is essentially the same as SELECT * FROM MyFooTable GROUP BY * if you are assuming * means all columns:

SELECT * FROM MyFooTable GROUP BY id, value;

 id |     value      
----+----------------
  1 | foo
  3 | something else
  2 | bar

It removes all duplicate values, which essentially makes it semantically identical to using the DISTINCT keyword with the exception of the ordering of results. For example:

SELECT DISTINCT * FROM MyFooTable;

 id |     value      
----+----------------
  1 | foo
  2 | bar
  3 | something else

Moment.js: Date between dates

In versions 2.9+ there is an isBetween function, but it's exclusive:

var compareDate = moment("15/02/2013", "DD/MM/YYYY");
var startDate   = moment("12/01/2013", "DD/MM/YYYY");
var endDate     = moment("15/01/2013", "DD/MM/YYYY");

// omitting the optional third parameter, 'units'
compareDate.isBetween(startDate, endDate); //false in this case

There is an inclusive workaround ...
x.isBetween(a, b) || x.isSame(a) || x.isSame(b)

... which is logically equivalent to
!(x.isBefore(a) || x.isAfter(b))


In version 2.13 the isBetween function has a fourth optional parameter, inclusivity.

Use it like this:

target.isBetween(start, finish, 'days', '()') // default exclusive
target.isBetween(start, finish, 'days', '(]') // right inclusive
target.isBetween(start, finish, 'days', '[)') // left inclusive
target.isBetween(start, finish, 'days', '[]') // all inclusive

More units to consider: years, months, days, hours, minutes, seconds, milliseconds

Note: units are still optional. Use null as the third argument to disregard units in which case milliseconds is the default granularity.

Visit the Official Docs

Why Anaconda does not recognize conda command?

When you install anaconda on windows now, it doesn't automatically add Python or Conda to your path so you have to add it yourself.

If you don’t know where your conda and/or python is, you type the following commands into your anaconda prompt

enter image description here

Next, you can add Python and Conda to your path by using the setx command in your command prompt. enter image description here

Next close that command prompt and open a new one. Congrats you can now use conda and python

Source: https://medium.com/@GalarnykMichael/install-python-on-windows-anaconda-c63c7c3d1444

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

I just tried with PHP 5.2, and that constant seems to exists :

var_dump(PDO::MYSQL_ATTR_INIT_COMMAND);

Gives me :

int 1002


But it seems there is a bug in PHP 5.3, that causes this constant to not exists anymore -- or, at least, not when the mysqlnd driver is used (and it's the one that's configured by default)

I suppose a temporary solution, as suggested on this bug report, could be to directly use the integer 1002 value, instead of the contant...

But note that you should go back to using the constant as soon as possible -- as this makes the code easier to understand.

Using partial views in ASP.net MVC 4

You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

Converting bool to text in C++

C++ has proper strings so you might as well use them. They're in the standard header string. #include <string> to use them. No more strcat/strcpy buffer overruns; no more missing null terminators; no more messy manual memory management; proper counted strings with proper value semantics.

C++ has the ability to convert bools into human-readable representations too. We saw hints at it earlier with the iostream examples, but they're a bit limited because they can only blast the text to the console (or with fstreams, a file). Fortunately, the designers of C++ weren't complete idiots; we also have iostreams that are backed not by the console or a file, but by an automatically managed string buffer. They're called stringstreams. #include <sstream> to get them. Then we can say:

std::string bool_as_text(bool b)
{
    std::stringstream converter;
    converter << std::boolalpha << b;   // flag boolalpha calls converter.setf(std::ios_base::boolalpha)
    return converter.str();
}

Of course, we don't really want to type all that. Fortunately, C++ also has a convenient third-party library named Boost that can help us out here. Boost has a nice function called lexical_cast. We can use it thus:

boost::lexical_cast<std::string>(my_bool)

Now, it's true to say that this is higher overhead than some macro; stringstreams deal with locales which you might not care about, and create a dynamic string (with memory allocation) whereas the macro can yield a literal string, which avoids that. But on the flip side, the stringstream method can be used for a great many conversions between printable and internal representations. You can run 'em backwards; boost::lexical_cast<bool>("true") does the right thing, for example. You can use them with numbers and in fact any type with the right formatted I/O operators. So they're quite versatile and useful.

And if after all this your profiling and benchmarking reveals that the lexical_casts are an unacceptable bottleneck, that's when you should consider doing some macro horror.

How can I get the session object if I have the entity-manager?

See the section "5.1. Accessing Hibernate APIs from JPA" in the Hibernate ORM User Guide:

Session session = entityManager.unwrap(Session.class);

How do I update the GUI from another thread?

The easiest way I think:

   void Update()
   {
       BeginInvoke((Action)delegate()
       {
           //do your update
       });
   }

"git pull" or "git merge" between master and development branches

my rule of thumb is:

rebase for branches with the same name, merge otherwise.

examples for same names would be master, origin/master and otherRemote/master.

if develop exists only in the local repository, and it is always based on a recent origin/master commit, you should call it master, and work there directly. it simplifies your life, and presents things as they actually are: you are directly developing on the master branch.

if develop is shared, it should not be rebased on master, just merged back into it with --no-ff. you are developing on develop. master and develop have different names, because we want them to be different things, and stay separate. do not make them same with rebase.

Remove folder and its contents from git/GitHub's history

I removed the bin and obj folders from old C# projects using git on windows. Be careful with

git filter-branch --tree-filter "rm -rf bin" --prune-empty HEAD

It destroys the integrity of the git installation by deleting the usr/bin folder in the git install folder.

how to store Image as blob in Sqlite & how to retrieve it?

for a ionic project


    var imgURI       = "";
    var imgBBDD      = ""; //sqllite for save into

    function takepicture() {
                var options = {
                    quality : 75,
                    destinationType : Camera.DestinationType.DATA_URL,
                    sourceType : Camera.PictureSourceType.CAMERA,
                    allowEdit : true,
                    encodingType: Camera.EncodingType.JPEG,
                    targetWidth: 300,
                    targetHeight: 300,
                    popoverOptions: CameraPopoverOptions,
                    saveToPhotoAlbum: false
                };

                $cordovaCamera.getPicture(options).then(function(imageData) {
                    imgURI = "data:image/jpeg;base64," + imageData;
                    imgBBDD = imageData;
                }, function(err) {
                    // An error occured. Show a message to the user
                });
            }

And now we put imgBBDD into SqlLite


     function saveImage = function (theId, theimage){
      var insertQuery = "INSERT INTO images(id, image) VALUES("+theId+", '"+theimage+"');"
      console.log('>>>>>>>');
      DDBB.SelectQuery(insertQuery)
                    .then( function(result) {
                        console.log("Image saved");
                    })
                    .catch( function(err) 
                     {
                        deferred.resolve(err);
                        return cb(err);
                    });
    }

A server side (php)


        $request = file_get_contents("php://input"); // gets the raw data
        $dades = json_decode($request,true); // true for return as array


    if($dades==""){
            $array = array();
            $array['error'] = -1;
            $array['descError'] = "Error when get the file";
            $array['logError'] = '';
            echo json_encode($array);
            exit;
        }
        //send the image again to the client
        header('Content-Type: image/jpeg');
        echo '';

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

Anaconda is made for the purpose you are asking. It is also an environment manager. It separates out environments. It was made because stable and legacy packages were not supported with newer/unstable versions of host languages; therefore a software was required that could separate and manage these versions on the same machine without the need to reinstall or uninstall individual host programming languages/environments.

You can find creation/deletion of environments in the Anaconda documentation.

Hope this helped.

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

Just install the necessary types for react and it should solve the error.

if you are using yarn:

yarn add @types/react @types/react-dom @types/react-router-dom -D

if you are using npm:

npm install @types/react @types/react-dom @types/react-router-dom --save-dev

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

Please make sure that you are not consuming your inputstream anywhere before parsing. Sample code is following: the respose below is httpresponse(i.e. response) and main content is contain inside StringEntity (i.e. getEntity())in form of inputStream(i.e. getContent()).

InputStream rescontent = response.getEntity().getContent();
tsResponse=(TsResponse) transformer.convertFromXMLToObject(rescontent );

How to check syslog in Bash on Linux?

By default it's logged into system log at /var/log/syslog, so it can be read by:

tail -f /var/log/syslog

If the file doesn't exist, check /etc/syslog.conf to see configuration file for syslogd. Note that the configuration file could be different, so check the running process if it's using different file:

# ps wuax | grep syslog
root      /sbin/syslogd -f /etc/syslog-knoppix.conf

Note: In some distributions (such as Knoppix) all logged messages could be sent into different terminal (e.g. /dev/tty12), so to access e.g. tty12 try pressing Control+Alt+F12.

You can also use lsof tool to find out which log file the syslogd process is using, e.g.

sudo lsof -p $(pgrep syslog) | grep log$ 

To send the test message to syslogd in shell, you may try:

echo test | logger

For troubleshooting use a trace tool (strace on Linux, dtruss on Unix), e.g.:

sudo strace -fp $(cat /var/run/syslogd.pid)

How to remove entry from $PATH on mac

Close the terminal(End the current session). Open it again.

How can I create a keystore?

You can create your keystore by exporting a signed APK. When you will try to export/build a signed APK, it will ask for a keystore.

You can choose your existing keystore or you can easily create a new one by clicking create new keystore

Here a link very useful and well-explained of how to create your keystore and generate a signed APK

THis link explained how to do it with Android Studio, but if I remember, it is pretty similar on Eclipse

WATCH OUT

Once you generate your keystore, keep it somewhere safe because you will need it to regenerate a new signed APK.

How do I export a project in the Android studio?

Unescape HTML entities in Javascript?

First create a <span id="decodeIt" style="display:none;"></span> somewhere in the body

Next, assign the string to be decoded as innerHTML to this:

document.getElementById("decodeIt").innerHTML=stringtodecode

Finally,

stringtodecode=document.getElementById("decodeIt").innerText

Here is the overall code:

var stringtodecode="<B>Hello</B> world<br>";
document.getElementById("decodeIt").innerHTML=stringtodecode;
stringtodecode=document.getElementById("decodeIt").innerText

Retrieving parameters from a URL

def getParams(url):
    params = url.split("?")[1]
    params = params.split('=')
    pairs = zip(params[0::2], params[1::2])
    answer = dict((k,v) for k,v in pairs)

Hope this helps

How to format a DateTime in PowerShell

The question is answered, but there is some more information missing:

Variable vs. Cmdlet

You have a value in the $Date variable and the -f operator does work in this form: 'format string' -f values. If you call Get-Date -format "yyyyMMdd" you call a cmdlet with some parameters. The value "yyyyMMdd" is the value for parameter Format (try help Get-Date -param Format).

-f operator

There are plenty of format strings. Look at least at part1 and part2. She uses string.Format('format string', values'). Think of it as 'format-string' -f values, because the -f operator works very similarly as string.Format method (although there are some differences (for more information look at question at Stack Overflow: How exactly does the RHS of PowerShell's -f operator work?).

Why can't I define my workbook as an object?

You'll need to open the workbook to refer to it.

Sub Setwbk()

    Dim wbk As Workbook

    Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
        Master Benchmark Data Sheet.xlsx")

End Sub

* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:

Why do I have to "set" it?

Set is how VBA assigns object variables. Since a Range and a Workbook/Worksheet are objects, you must use Set with these.

Why do I get a C malloc assertion failure?

You are probably overrunning beyond the allocated mem somewhere. then the underlying sw doesn't pick up on it until you call malloc

There may be a guard value clobbered that is being caught by malloc.

edit...added this for bounds checking help

http://www.lrde.epita.fr/~akim/ccmp/doc/bounds-checking.html

Turning a Comma Separated string into individual rows

You can use the wonderful recursive functions from SQL Server:


Sample table:

CREATE TABLE Testdata
(
    SomeID INT,
    OtherID INT,
    String VARCHAR(MAX)
)

INSERT Testdata SELECT 1,  9, '18,20,22'
INSERT Testdata SELECT 2,  8, '17,19'
INSERT Testdata SELECT 3,  7, '13,19,20'
INSERT Testdata SELECT 4,  6, ''
INSERT Testdata SELECT 9, 11, '1,2,3,4'

The query

;WITH tmp(SomeID, OtherID, DataItem, String) AS
(
    SELECT
        SomeID,
        OtherID,
        LEFT(String, CHARINDEX(',', String + ',') - 1),
        STUFF(String, 1, CHARINDEX(',', String + ','), '')
    FROM Testdata
    UNION all

    SELECT
        SomeID,
        OtherID,
        LEFT(String, CHARINDEX(',', String + ',') - 1),
        STUFF(String, 1, CHARINDEX(',', String + ','), '')
    FROM tmp
    WHERE
        String > ''
)

SELECT
    SomeID,
    OtherID,
    DataItem
FROM tmp
ORDER BY SomeID
-- OPTION (maxrecursion 0)
-- normally recursion is limited to 100. If you know you have very long
-- strings, uncomment the option

Output

 SomeID | OtherID | DataItem 
--------+---------+----------
 1      | 9       | 18       
 1      | 9       | 20       
 1      | 9       | 22       
 2      | 8       | 17       
 2      | 8       | 19       
 3      | 7       | 13       
 3      | 7       | 19       
 3      | 7       | 20       
 4      | 6       |          
 9      | 11      | 1        
 9      | 11      | 2        
 9      | 11      | 3        
 9      | 11      | 4        

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

I found the easiest way is to use the node.js package cors. The simplest usage is:

var cors = require('cors')

var app = express()
app.use(cors())

There are, of course many ways to configure the behaviour to your needs; the page linked above shows a number of examples.

Execute a SQL Stored Procedure and process the results

From MSDN

To execute a stored procedure returning rows programmatically using a command object

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1

sqlConnection1.Open()

reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
  someVar = reader(0)
  someVar2 = reader(1)
  someVar3 = reader("NamedField")
End If    

sqlConnection1.Close()

How to convert WebResponse.GetResponseStream return into a string?

Richard Schneider is right. use code below to fetch data from site which is not utf8 charset will get wrong string.

using (Stream stream = response.GetResponseStream())
{
   StreamReader reader = new StreamReader(stream, Encoding.UTF8);
   String responseString = reader.ReadToEnd();
}

" i can't vote.so wrote this.

Input and Output binary streams using JERSEY?

This worked fine with me url:http://example.com/rest/muqsith/get-file?filePath=C:\Users\I066807\Desktop\test.xml

@GET
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
@Path("/get-file")
public Response getFile(@Context HttpServletRequest request){
   String filePath = request.getParameter("filePath");
   if(filePath != null && !"".equals(filePath)){
        File file = new File(filePath);
        StreamingOutput stream = null;
        try {
        final InputStream in = new FileInputStream(file);
        stream = new StreamingOutput() {
            public void write(OutputStream out) throws IOException, WebApplicationException {
                try {
                    int read = 0;
                        byte[] bytes = new byte[1024];

                        while ((read = in.read(bytes)) != -1) {
                            out.write(bytes, 0, read);
                        }
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
        return Response.ok(stream).header("content-disposition","attachment; filename = "+file.getName()).build();
        }
    return Response.ok("file path null").build();
}

How to disable text selection highlighting

UPDATE January, 2017:

According to Can I use, the user-select is currently supported in all browsers except Internet Explorer 9 and its earlier versions (but sadly still needs a vendor prefix).


These are all of the available correct CSS variations:

_x000D_
_x000D_
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Old versions of Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome, Edge, Opera and Firefox */
}
_x000D_
<p>
  Selectable text.
</p>
<p class="noselect">
  Unselectable text.
</p>
_x000D_
_x000D_
_x000D_


Note that user-select is in standardization process (currently in a W3C working draft). It is not guaranteed to work everywhere and there might be differences in implementation among browsers. Also browsers can drop support for it in the future.


More information can be found in Mozilla Developer Network documentation.

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

nvarchar(max) still being truncated

Your first problem is a limitation of the PRINT statement. I'm not sure why sp_executesql is failing. It should support pretty much any length of input.

Perhaps the reason the query is malformed is something other than truncation.

How to run the Python program forever?

I know this is too old thread but why no one mentioned this

#!/usr/bin/python3
import asyncio 

loop = asyncio.get_event_loop()
try:
    loop.run_forever()
finally:
    loop.close()

How do I set the background color of Excel cells using VBA?

It doesn't work if you use Function, but works if you Sub. However, you cannot call a sub from a cell using formula.

Test if characters are in a string

Similar problem here: Given a string and a list of keywords, detect which, if any, of the keywords are contained in the string.

Recommendations from this thread suggest stringr's str_detect and grepl. Here are the benchmarks from the microbenchmark package:

Using

map_keywords = c("once", "twice", "few")
t = "yes but only a few times"

mapper1 <- function (x) {
  r = str_detect(x, map_keywords)
}

mapper2 <- function (x) {
  r = sapply(map_keywords, function (k) grepl(k, x, fixed = T))
}

and then

microbenchmark(mapper1(t), mapper2(t), times = 5000)

we find

Unit: microseconds
       expr    min     lq     mean  median      uq      max neval
 mapper1(t) 26.401 27.988 31.32951 28.8430 29.5225 2091.476  5000
 mapper2(t) 19.289 20.767 24.94484 23.7725 24.6220 1011.837  5000

As you can see, over 5,000 iterations of the keyword search using str_detect and grepl over a practical string and vector of keywords, grepl performs quite a bit better than str_detect.

The outcome is the boolean vector r which identifies which, if any, of the keywords are contained in the string.

Therefore, I recommend using grepl to determine if any keywords are in a string.

load Js file in HTML

I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:

const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))

How to rename a component in Angular CLI?

I personally have not found any command for the same. Just make a new component (renamed name) and copy paste the previous component's html, css, and ts. In ts obviously the class name would be replaced. Its the safest method but does take a little time.

How to register multiple servlets in web.xml in one Spring application

I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.

Select Tag Helper in ASP.NET Core MVC

I created an Interface and a <options> tag helper for this. So I didn't have to convert the IEnumerable<T> items into IEnumerable<SelectListItem> every time I have to populate the <select> control.

And I think it works beautifully...

The usage is something like:

<select asp-for="EmployeeId">
    <option value="">Please select...</option>
    <options asp-items="@Model.EmployeesList" />
</select>

And to make it work with the tag helper you have to implement that interface in your class:

public class Employee : IIntegerListItem
{
   public int Id { get; set; }
   public string FullName { get; set; }

   public int Value { return Id; }
   public string Text{ return FullName ; }
}

These are the needed codes:

The interface:

public interface IIntegerListItem
{
    int Value { get; }
    string Text { get; }
}

The <options> tag helper:

[HtmlTargetElement("options", Attributes = "asp-items")]
public class OptionsTagHelper : TagHelper
{
    public OptionsTagHelper(IHtmlGenerator generator)
    {
        Generator = generator;
    }

    [HtmlAttributeNotBound]
    public IHtmlGenerator Generator { get; set; }

    [HtmlAttributeName("asp-items")]
    public object Items { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.SuppressOutput();
        // Is this <options /> element a child of a <select/> element the SelectTagHelper targeted?
        object formDataEntry;
        context.Items.TryGetValue(typeof(SelectTagHelper), out formDataEntry);

        var selectedValues = formDataEntry as ICollection<string>;
        var encodedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        if (selectedValues != null && selectedValues.Count != 0)
        {
            foreach (var selectedValue in selectedValues)
            {
                encodedValues.Add(Generator.Encode(selectedValue));
            }
        }

        IEnumerable<SelectListItem> items = null;
        if (Items != null)
        {
            if (Items is IEnumerable)
            {
                var enumerable = Items as IEnumerable;
                if (Items is IEnumerable<SelectListItem>)
                    items = Items as IEnumerable<SelectListItem>;
                else if (Items is IEnumerable<IIntegerListItem>)
                    items = ((IEnumerable<IIntegerListItem>)Items).Select(x => new SelectListItem() { Selected = false, Value = ((IIntegerListItem)x).Value.ToString(), Text = ((IIntegerListItem)x).Text });
                else
                    throw new InvalidOperationException(string.Format("The {2} was unable to provide metadata about '{1}' expression value '{3}' for <options>.",
                        "<options>",
                        "ForAttributeName",
                        nameof(IModelMetadataProvider),
                        "For.Name"));
            }
            else
            {
                throw new InvalidOperationException("Invalid items for <options>");
            }

            foreach (var item in items)
            {
                bool selected = (selectedValues != null && selectedValues.Contains(item.Value)) || encodedValues.Contains(item.Value);
                var selectedAttr = selected ? "selected='selected'" : "";

                if (item.Value != null)
                    output.Content.AppendHtml($"<option value='{item.Value}' {selectedAttr}>{item.Text}</option>");
                else
                    output.Content.AppendHtml($"<option>{item.Text}</option>");
            }
        }
    }
}

There may be some typo but the aim is clear I think. I had to edit a little bit.

printf not printing on console

Output is buffered.

stdout is line-buffered by default, which means that '\n' is supposed to flush the buffer. Why is it not happening in your case? I don't know. I need more info about your application/environment.

However, you can control buffering with setvbuf():

setvbuf(stdout, NULL, _IOLBF, 0);

This will force stdout to be line-buffered.

setvbuf(stdout, NULL, _IONBF, 0);

This will force stdout to be unbuffered, so you won't need to use fflush(). Note that it will severely affect application performance if you have lots of prints.

"SyntaxError: Unexpected token < in JSON at position 0"

Protip: Testing json on a local Node.js server? Make sure you don't already have something routing to that path

'/:url(app|assets|stuff|etc)';

How to Iterate over a Set/HashSet without an Iterator?

You can use functional operation for a more neat code

Set<String> set = new HashSet<String>();

set.forEach((s) -> {
     System.out.println(s);
});

Skip first entry in for loop in python?

I do it like this, even though it looks like a hack it works every time:

ls_of_things = ['apple', 'car', 'truck', 'bike', 'banana']
first = 0
last = len(ls_of_things)
for items in ls_of_things:
    if first == 0
        first = first + 1
        pass
    elif first == last - 1:
        break
    else:
        do_stuff
        first = first + 1
        pass

Calling other function in the same controller?

To call a function inside a same controller in any laravel version follow as bellow

$role = $this->sendRequest('parameter');
// sendRequest is a public function

How do I convert Int/Decimal to float in C#?

The same as an int:

float f = 6;

Also here's how to programmatically convert from an int to a float, and a single in C# is the same as a float:

int i = 8;
float f = Convert.ToSingle(i);

Or you can just cast an int to a float:

float f = (float)i;

Screenshot sizes for publishing android app on Google Play

When I publish apps I use the following screenshot sizes:

Phone: 1080 x 1920 I prepare 8 images with title, some fancy background and a screenshot inside a smartphone mockup. So it's more than a simple screenshot. It gives some nice branding and helps you to stand out from other apps out there.

Tablet 7": 1200 x 1920 - I do actually a couple of raw screenshots of 7" emulator so that the user could know how the layout will appear on his device. No fancy design with titles etc.

Tablet 10": 1800 x 2560 - same thing here, just a couple of raw screenshots.

all in .png format. Hope this helps.

Oracle 11g Express Edition for Windows 64bit?

Some of more advanced Oracle database features such as session trace do not work properly in Oracle 11g XE 32-bit if installed on Windows 64-bit system. I needed session trace on Windows 7 64-bit.

Apart from that it works well for me in multiple production MS Windows 64-bit systems: Windows Server 2008 R2 and Windows Server 2003 R2.

Checking if an input field is required using jQuery

The required property is boolean:

$('form#register').find('input').each(function(){
    if(!$(this).prop('required')){
        console.log("NR");
    } else {
        console.log("IR");
    }
});

Reference: HTMLInputElement

How to remove commits from a pull request

If you're removing a commit and don't want to keep its changes @ferit has a good solution.

If you want to add that commit to the current branch, but doesn't make sense to be part of the current pr, you can do the following instead:

  1. use git rebase -i HEAD~n
  2. Swap the commit you want to remove to the bottom (most recent) position
  3. Save and exit
  4. use git reset HEAD^ --soft to uncommit the changes and get them back in a staged state.
  5. use git push --force to update the remote branch without your removed commit.

Now you'll have removed the commit from your remote, but will still have the changes locally.

Handling Dialogs in WPF with MVVM

An interesting alternative is to use Controllers which are responsible to show the views (dialogs).

How this works is shown by the WPF Application Framework (WAF).

How to enable Ad Hoc Distributed Queries

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

Django MEDIA_URL and MEDIA_ROOT

Your setting is all right. Some web servers require to specify the media and static folder files specifically. For example in pythonanywhere.com you have to go to the 'Web' section and add the url od the media folders and static folder. For example:

  URL                     Directory                
/static/            /home/Saidmamad/discoverthepamirs/static     
/accounts/static/   /home/Saidmamad/discoverthepamirs/accounts/static    
/media/            /home/Saidmamad/discoverthepamirs/discoverthepamirs/media    

I know that it is late, but just to help those who visit this link because of the same problem ;)

Jquery change background color

The .css() function doesn't queue behind running animations, it's instantaneous.

To match the behaviour that you're after, you'd need to do the following:

$(document).ready(function() {
  $("button").mouseover(function() {
    var p = $("p#44.test").css("background-color", "yellow");
    p.hide(1500).show(1500);
    p.queue(function() {
      p.css("background-color", "red");
    });
  });
});

The .queue() function waits for running animations to run out and then fires whatever's in the supplied function.

jQuery loop over JSON result from AJAX Success?

This is what I came up with to easily view all data values:

_x000D_
_x000D_
var dataItems = "";_x000D_
$.each(data, function (index, itemData) {_x000D_
    dataItems += index + ": " + itemData + "\n";_x000D_
});_x000D_
console.log(dataItems);
_x000D_
_x000D_
_x000D_

Create new XML file and write data to it?

With FluidXML you can generate and store an XML document very easily.

$doc = fluidxml();

$doc->add('Album', true)
        ->add('Track', 'Track Title');

$doc->save('album.xml');

Loading a document from a file is equally simple.

$doc = fluidify('album.xml');

$doc->query('//Track')
        ->attr('id', 123);

https://github.com/servo-php/fluidxml

Java 8: Difference between two LocalDateTime in multiple units

Joda-Time

Since many of the answers required API 26 support and my min API was 23, I solved it by below code :

import org.joda.time.Days

LocalDate startDate = Something
LocalDate endDate = Something
// The difference would be exclusive of both dates, 
// so in most of use cases we may need to increment it by 1
Days.daysBetween(startDate, endDate).days

How to declare 2D array in bash

The below code will definitely work provided if you are working on a Mac you have bash version 4. Not only can you declare 0 but this is more of a universal approach to dynamically accepting values.

2D Array

declare -A arr
echo "Enter the row"
read r
echo "Enter the column"
read c
i=0
j=0
echo "Enter the elements"
while [ $i -lt $r ]
do
  j=0
  while [ $j -lt $c ]
  do
    echo $i $j
    read m
    arr[${i},${j}]=$m
    j=`expr $j + 1`
  done
  i=`expr $i + 1`
done

i=0
j=0
while [ $i -lt $r ]
do
  j=0
  while [ $j -lt $c ]
  do
    echo -n ${arr[${i},${j}]} " "
    j=`expr $j + 1`
  done
  echo ""
  i=`expr $i + 1`
done

Page redirect after certain time PHP

header( "refresh:5;url=wherever.php" );

this is the php way to set header which will redirect you to wherever.php in 5 seconds


Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file. (source php.net)

In Firebase, is there a way to get the number of children of a node without loading all the node data?

Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).

The 'trick' here is to use the node priority to as the vote count...

The data is:

vote/$issueBeingVotedOn/user/$uniqueIdOfVoter = thisVotesCount, priority=thisVotesCount vote/$issueBeingVotedOn/count = 'user/'+$idOfLastVoter, priority=CountofLastVote

,"vote": {
  ".read" : true
  ,".write" : true
  ,"$issue" : {
    "user" : {
      "$user" : {
        ".validate" : "!data.exists() && 
             newData.val()==data.parent().parent().child('count').getPriority()+1 &&
             newData.val()==newData.GetPriority()" 

user can only vote once && count must be one higher than current count && data value must be same as priority.

      }
    }
    ,"count" : {
      ".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
             newData.getPriority()==data.getPriority()+1 "
    }

count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.

  }
}

Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.

<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
  window.fb = new Firebase('https:...vote/iss1/');
  window.fb.child('count').once('value', function (dss) {
    votes = dss.getPriority();
    for (var i=1;i<10;i++) vote(dss,i+votes);
  } );

function vote(dss,count)
{
  var user='user/zz' + count; // replace with auth.id or whatever
  window.fb.child(user).setWithPriority(count,count);
  window.fb.child('count').setWithPriority(user,count);
}
</script>

The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)

The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).

How can I install a package with go get?

Command go

Download and install packages and dependencies

Usage:

go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]

Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.

The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.

The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.

The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.

The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.

The -t flag instructs get to also download the packages required to build the tests for the specified packages.

The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.

The -v flag enables verbose progress and debug output.

Get also accepts build flags to control the installation. See 'go help build'.

When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.

When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.

When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.

Get never checks out or updates code stored in vendor directories.

For more about specifying packages, see 'go help packages'.

For more about how 'go get' finds source code to download, see 'go help importpath'.

This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.

See also: go build, go install, go clean.


For example, showing verbose output,

$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$ 

What's the difference between ViewData and ViewBag?

One main difference I noticed between ViewData and ViewBag is:

ViewData : it will return object does not matter what you have assigned into this and need to typecast again back to the original type.

ViewBag : it is enough smart to return exact type what you have assigned to it it does not matter weather you have assigned simple type (i.e. int, string etc.) or complex type.

Ex: Controller code.

 namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Products p1 = new Products();
            p1.productId = 101;
            p1.productName = "Phone";
            Products p2 = new Products();
            p2.productId = 102;
            p2.productName = "laptop";

            List<Products> products = new List<Products>();
            products.Add(p1);
            products.Add(p2);
            ViewBag.Countries = products;
            return View();
        }
    }
    public class Products
    {
        public int productId { get; set; }
        public string productName { get; set; }
    }
}

View Code.

<ul>
            @foreach (WebApplication1.Controllers.Products item in ViewBag.Countries)
            {
            <li>@item.productId &nbsp;&nbsp;&nbsp;@item.productName</li>
            }
        </ul>

OutPut Screen.

enter image description here

How to run a javascript function during a mouseover on a div

Here's a jQuery solution.

<script type="text/javascript" src="/path/to/your/copy/of/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#sub1").mouseover(function() {
        $("#welcome").toggle();
    });
});
</script>

Using this markup:

<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Welcome message</div>

You didn't really specify if (or when) you wanted to hide the welcome message, but this would toggle hiding or showing each time you moused over the text.

JSON to string variable dump

Yes, JSON.stringify, can be found here, it's included in Firefox 3.5.4 and above.

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier. https://web.archive.org/web/20100611210643/http://www.json.org/js.html

var myJSONText = JSON.stringify(myObject, replacer);

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Add colorbar to existing axis

The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax kwarg to tell fig.colorbar to use the new axes.

For example:

import numpy as np
import matplotlib.pyplot as plt

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])

im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()

enter image description here

Java ResultSet how to check if there are any results

you can do something like this

boolean found = false;

while ( resultSet.next() )
{
    found = true;
    resultSet.getString("column_name");
}

if (!found)
    System.out.println("No Data");

How to parse XML in Bash?

After some research for translation between Linux and Windows formats of the file paths in XML files I found interesting tutorials and solutions on:

How to recursively find and list the latest modified files in a directory with subdirectories and times

You may give the printf command of find a try

%Ak File's last access time in the format specified by k, which is either @' or a directive for the C strftime' function. The possible values for k are listed below; some of them might not be available on all systems, due to differences in `strftime' between systems.

How to save a base64 image to user's disk using JavaScript?

This Works

function saveBase64AsFile(base64, fileName) {
    var link = document.createElement("a");
    document.body.appendChild(link);
    link.setAttribute("type", "hidden");
    link.href = "data:text/plain;base64," + base64;
    link.download = fileName;
    link.click();  
    document.body.removeChild(link);
}

Based on the answer above but with some changes

Why is jquery's .ajax() method not sending my session cookie?

Adding my scenario and solution in case it helps someone else. I encountered similar case when using RESTful APIs. My Web server hosting HTML/Script/CSS files and Application Server exposing APIs were hosted on same domain. However the path was different.

web server - mydomain/webpages/abc.html

used abc.js which set cookie named mycookie

app server - mydomain/webapis/servicename.

to which api calls were made

I was expecting the cookie in mydomain/webapis/servicename and tried reading it but it was not being sent. After reading comment from the answer, I checked in browser's development tool that mycookie's path was set to "/webpages" and hence not available in service call to

mydomain/webapis/servicename

So While setting cookie from jquery, this is what I did -

$.cookie("mycookie","mayvalue",{**path:'/'**});

for each inside a for each - Java

most simple solution would be to set a boolean var. if to true where you do the insert statement and then in the outter loop check this and insert the tweet there if the boolean is true...

Equivalent VB keyword for 'break'

Exit [construct], and intelisense will tell you which one(s) are valid in a particular place.

Git copy file preserving history

This process preserve history, but is little workarround:

# make branchs to new files
$: git mv arquivos && git commit

# in original branch, remove original files
$: git rm arquivos && git commit

# do merge and fix conflicts
$: git merge branch-copia-arquivos

# back to original branch and revert commit removing files
$: git revert commit

What is the command to truncate a SQL Server log file?

if I remember well... in query analyzer or equivalent:

BACKUP LOG  databasename  WITH TRUNCATE_ONLY

DBCC SHRINKFILE (  databasename_Log, 1)

Insert a row to pandas dataframe

One way to achieve this is

>>> pd.DataFrame(np.array([[2, 3, 4]]), columns=['A', 'B', 'C']).append(df, ignore_index=True)
Out[330]: 
   A  B  C
0  2  3  4
1  5  6  7
2  7  8  9

Generally, it's easiest to append dataframes, not series. In your case, since you want the new row to be "on top" (with starting id), and there is no function pd.prepend(), I first create the new dataframe and then append your old one.

ignore_index will ignore the old ongoing index in your dataframe and ensure that the first row actually starts with index 1 instead of restarting with index 0.

Typical Disclaimer: Cetero censeo ... appending rows is a quite inefficient operation. If you care about performance and can somehow ensure to first create a dataframe with the correct (longer) index and then just inserting the additional row into the dataframe, you should definitely do that. See:

>>> index = np.array([0, 1, 2])
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[0:1] = [list(s1), list(s2)]
>>> df2
Out[336]: 
     A    B    C
0    5    6    7
1    7    8    9
2  NaN  NaN  NaN
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[1:] = [list(s1), list(s2)]

So far, we have what you had as df:

>>> df2
Out[339]: 
     A    B    C
0  NaN  NaN  NaN
1    5    6    7
2    7    8    9

But now you can easily insert the row as follows. Since the space was preallocated, this is more efficient.

>>> df2.loc[0] = np.array([2, 3, 4])
>>> df2
Out[341]: 
   A  B  C
0  2  3  4
1  5  6  7
2  7  8  9

Hidden Features of Java

This is not exactly "hidden features" and not very useful, but can be extremely interesting in some cases:
Class sun.misc.Unsafe - will allow you to implement direct memory management in Java (you can even write self-modifying Java code with this if you try a lot):

public class UnsafeUtil {

    public static Unsafe unsafe;
    private static long fieldOffset;
    private static UnsafeUtil instance = new UnsafeUtil();

    private Object obj;

    static {
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);

            unsafe = (Unsafe)f.get(null);
            fieldOffset = unsafe.objectFieldOffset(UnsafeUtil.class.getDeclaredField("obj"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };
}

Calling pylab.savefig without display in ipython

We don't need to plt.ioff() or plt.show() (if we use %matplotlib inline). You can test above code without plt.ioff(). plt.close() has the essential role. Try this one:

%matplotlib inline
import pylab as plt

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')

If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2) to the end of it, you will see nothing.

In conclusion, if you close figure by plt.close(fig), it won't be displayed.

Java says FileNotFoundException but file exists

There are a number situation where a FileNotFoundException may be thrown at runtime.

  1. The named file does not exist. This could be for a number of reasons including:

    • The pathname is simply wrong
    • The pathname looks correct but is actually wrong because it contains non-printing characters (or homoglyphs) that you did not notice
    • The pathname is relative, and it doesn't resolve correctly relative to the actual current directory of the running application. This typically happens because the application's current directory is not what you are expecting or assuming.
    • The path to the file is is broken; e.g. a directory name of the path is incorrect, a symbolic link on the path is broken, or there is a permission problem with one of the path components.
  2. The named file is actually a directory.

  3. The named file cannot be opened for reading for some reason.

The good news that, the problem will inevitably be one of the above. It is just a matter of working out which. Here are some things that you can try:

  • Calling file.exists() will tell you if any file system object exists with the given name / pathname.
  • Calling file.isDirectory() will test if it is a directory.
  • Calling file.canRead() will test if it is a readable file.
  • This line will tell you what the current directory is:

    System.out.println(new File(".").getAbsolutePath());
    
  • This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trainiong whitespace:

    System.out.println("The path is '" + path + "'");
    

    Look for unexpected spaces, line breaks, etc in the output.


It turns out that your example code has a compilation error.

I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

If you change your code to the following, it will fix that problem.

public static void main(String[] args) throws FileNotFoundException {    
    File file = new File("scores.dat");
    System.out.println(file.exists());
    Scanner scan = new Scanner(file);
}

Explanation: the Scanner(File) constructor is declared as throwing the FileNotFoundException exception. (It happens the scanner it cannot open the file.) Now FileNotFoundException is a checked exception. That means that a method in which the exception may be thrown must either catch the exception or declare it in the throws clause. The above fix takes the latter approach.

Removing all line breaks and adding them after certain text

  • Open Notepad++
  • Paste your text
  • Control + H

In the pop up

  • Find what: \r\n
  • Replace with: BLANK_SPACE

You end up with a big line. Then

  • Control + H

In the pop up

  • Find what: (\.)
  • Replace with: \r\n

So you end up with lines that end by dot

And if you have to do the same process lots of times

  • Go to Macro
  • Start recording
  • Do the process above
  • Go to Macro
  • Stop recording
  • Save current recorded macro
  • Choose a short cut
  • Select the text you want to apply the process (Control + A)
  • Do the shortcut

Tooltip on image

You can use the standard HTML title attribute of image for this:

<img src="source of image" alt="alternative text" title="this will be displayed as a tooltip"/>

VBA vlookup reference in different sheet

try this:

Dim ws as Worksheet

Set ws = Thisworkbook.Sheets("Sheet2")

With ws
    .Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With

End Sub

This just the simplified version of what you want.
No need to use Application if you will just output the answer in the Range("E2").

If you want to stick with your logic, declare the variables.
See below for example.

Sub Test()

Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String

Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")

With ws2
    On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
    MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
    On Error GoTo 0
    If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With

End Sub

Hope this get's you started.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

You are getting this is because you are using a Anaconda distribution of Jupyter notebook. So just do conda install pandas restart your jupyter notebook and rerun your cell. It should work. If you are trying this on a Virtual Env try this

  1. conda create -n name_of_my_env python This will create a minimal environment with only Python installed in it. To put your self inside this environment run:

2 source activate name_of_my_env On Windows the command is: activate name_of_my_env The final step required is to install pandas. This can be done with the following command:

conda install pandas To install a specific pandas version:

conda install pandas=0.20.3

To install other packages, IPython for example:

conda install ipython To install the full Anaconda distribution:

conda install anaconda

If you need packages that are available to pip but not conda, then install pip, and then use pip to install those packages:

conda install pip pip install django Installing from PyPI pandas can be installed via pip from PyPI.

pip install pandas Installing with ActivePython

Hope this helps.

Escaping Double Quotes in Batch Script

eplawless's own answer simply and effectively solves his specific problem: it replaces all " instances in the entire argument list with \", which is how Bash requires double-quotes inside a double-quoted string to be represented.

To generally answer the question of how to escape double-quotes inside a double-quoted string using cmd.exe, the Windows command-line interpreter (whether on the command line - often still mistakenly called the "DOS prompt" - or in a batch file):See bottom for a look at PowerShell.

tl;dr:

  • You must use "" when passing a string to a(nother) batch file and you may use "" with applications created with Microsoft's C/C++/.NET compilers (which also accept \"), which on Windows includes Python and Node.js:

    • Example: foo.bat "We had 3"" of rain."

    • The following applies to batch files only:

      • "" is the only way to get the command interpreter (cmd.exe) to treat the whole double-quoted string as a single argument.

      • Sadly, however, not only are the enclosing double-quotes retained (as usual), but so are the doubled escaped ones, so obtaining the intended string is a two-step process; e.g., assuming that the double-quoted string is passed as the 1st argument, %1:

      • set "str=%~1" removes the enclosing double-quotes; set "str=%str:""="%" then converts the doubled double-quotes to single ones.
        Be sure to use the enclosing double-quotes around the assignment parts to prevent unwanted interpretation of the values.

  • \" is required - as the only option - by many other programs, (e.g., Ruby, Perl, and even Microsoft's own Windows PowerShell(!)), but ITS USE IS NOT SAFE:

    • \" is what many executables and interpreters either require - including Windows PowerShell - when passed strings from the outside - or, in the case of Microsoft's compilers, support as an alternative to "" - ultimately, though, it's up to the target program to parse the argument list.
      • Example: foo.exe "We had 3\" of rain."
    • HOWEVER, USE OF \" CAN RESULT IN UNWANTED, ARBITRARY EXECUTION OF COMMANDS and/or INPUT/OUTPUT REDIRECTIONS:
      • The following characters present this risk: & | < >
      • For instance, the following results in unintended execution of the ver command; see further below for an explanation and the next bullet point for a workaround:
        • foo.exe "3\" of snow" "& ver."
    • For Windows PowerShell, \"" and "^"" are robust, but limited alternatives (see section "Calling PowerShell's CLI ..." below).
  • If you must use \", there are only 3 safe approaches, which are, however quite cumbersome: Tip of the hat to T S for his help.

    • Using (possibly selective) delayed variable expansion in your batch file, you can store literal \" in a variable and reference that variable inside a "..." string using !var! syntax - see T S's helpful answer.

      • The above approach, despite being cumbersome, has the advantage that you can apply it methodically and that it works robustly, with any input.
    • Only with LITERAL strings - ones NOT involving VARIABLES - do you get a similarly methodical approach: categorically ^-escape all cmd.exe metacharacters: " & | < > and - if you also want to suppress variable expansion - %:
      foo.exe ^"3\^" of snow^" ^"^& ver.^"

    • Otherwise, you must formulate your string based on recognizing which portions of the string cmd.exe considers unquoted due to misinterpreting \" as closing delimiters:

      • in literal portions containing shell metacharacters: ^-escape them; using the example above, it is & that must be ^-escaped:
        foo.exe "3\" of snow" "^& ver."

      • in portions with %...%-style variable references: ensure that cmd.exe considers them part of a "..." string and that that the variable values do not themselves have embedded, unbalanced quotes - which is not even always possible.

For background information, read on.


Background

Note: This is based on my own experiments. Do let me know if I'm wrong.

POSIX-like shells such as Bash on Unix-like systems tokenize the argument list (string) before passing arguments individually to the target program: among other expansions, they split the argument list into individual words (word splitting) and remove quoting characters from the resulting words (quote removal). The target program is handed an array of individual arguments, with syntactic quotes removed.

By contrast, the Windows command interpreter apparently does not tokenize the argument list and simply passes the single string comprising all arguments - including quoting chars. - to the target program.
However, some preprocessing takes place before the single string is passed to the target program: ^ escape chars. outside of double-quoted strings are removed (they escape the following char.), and variable references (e.g., %USERNAME%) are interpolated first.

Thus, unlike in Unix, it is the target program's responsibility to parse to parse the arguments string and break it down into individual arguments with quotes removed. Thus, different programs can hypothetically require differing escaping methods and there's no single escaping mechanism that is guaranteed to work with all programs - https://stackoverflow.com/a/4094897/45375 contains excellent background on the anarchy that is Windows command-line parsing.

In practice, \" is very common, but NOT SAFE, as mentioned above:

Since cmd.exe itself doesn't recognize \" as an escaped double-quote, it can misconstrue later tokens on the command line as unquoted and potentially interpret them as commands and/or input/output redirections.
In a nutshell: the problem surfaces, if any of the following characters follow an opening or unbalanced \": & | < >; for example:

foo.exe "3\" of snow" "& ver."

cmd.exe sees the following tokens, resulting from misinterpreting \" as a regular double-quote:

  • "3\"
  • of
  • snow" "
  • rest: & ver.

Since cmd.exe thinks that & ver. is unquoted, it interprets it as & (the command-sequencing operator), followed by the name of a command to execute (ver. - the . is ignored; ver reports cmd.exe's version information).
The overall effect is:

  • First, foo.exe is invoked with the first 3 tokens only.
  • Then, command ver is executed.

Even in cases where the accidental command does no harm, your overall command won't work as designed, given that not all arguments are passed to it.

Many compilers / interpreters recognize ONLY \" - e.g., the GNU C/C++ compiler, Python, Perl, Ruby, even Microsoft's own Windows PowerShell when invoked from cmd.exe - and, except (with limitations) for Windows PowerShell with \"", for them there is no simple solution to this problem.
Essentially, you'd have to know in advance which portions of your command line are misinterpreted as unquoted, and selectively ^-escape all instances of & | < > in those portions.

By contrast, use of "" is SAFE, but is regrettably only supported by Microsoft-compiler-based executables and batch files (in the case of batch files, with the quirks discussed above), which notable excludes PowerShell - see next section.


Calling PowerShell's CLI from cmd.exe or POSIX-like shells:

Note: See the bottom section for how quoting is handled inside PowerShell.

When invoked from the outside - e.g., from cmd.exe, whether from the command line or a batch file:

  • PowerShell [Core] v6+ now properly recognizes "" (in addition to \"), which is both safe to use and whitespace-preserving.

    • pwsh -c " ""a & c"".length " doesn't break and correctly yields 6
  • Windows PowerShell (the legacy edition whose last version is 5.1) recognizes only \" and, on Windows also """ and the more robust \"" / "^"" (even though internally PowerShell uses ` as the escape character in double-quoted strings and also accepts "" - see bottom section):

Calling Windows PowerShell from cmd.exe / a batch file:

  • "" breaks, because it is fundamentally unsupported:

    • powershell -c " ""ab c"".length " -> error "The string is missing the terminator"
  • \" and """ work in principle, but aren't safe:

    • powershell -c " \"ab c\".length " works as intended: it outputs 5 (note the 2 spaces)
    • But it isn't safe, because cmd.exe metacharacters break the command, unless escaped:
      powershell -c " \"a& c\".length " breaks, due to the &, which would have to be escaped as ^&
  • \"" is safe, but normalize interior whitespace, which can be undesired:

    • powershell -c " \""a& c\"".length " outputs 4(!), because the 2 spaces are normalized to 1.
  • "^"" is the best choice for Windows PowerShell specifically, where it is both safe and whitespace-preserving, but with PowerShell Core (on Windows) it is the same as \"", i.e, whitespace-normalizing. Credit goes to Venryx for discovering this approach.

    • powershell -c " "^""a& c"^"".length " works: doesn't break - despite & - and outputs 5, i.e., correctly preserved whitespace.

    • PowerShell Core: pwsh -c " "^""a& c"^"".length " works, but outputs 4, i.e. normalizes whitespace, as \"" does.

On Unix-like platforms (Linux, macOS), when calling PowerShell [Core]'s CLI, pwsh, from a POSIX-like shell such as bash:

You must use \", which, however is both safe and whitespace-preserving:

$ pwsh -c " \"a&  c|\".length" # OK: 5

Related information

  • ^ can only be used as the escape character in unquoted strings - inside double-quoted strings, ^ is not special and treated as a literal.

    • CAVEAT: Use of ^ in parameters passed to the call statement is broken (this applies to both uses of call: invoking another batch file or binary, and calling a subroutine in the same batch file):
      • ^ instances in double-quoted values are inexplicably doubled, altering the value being passed: e.g., if variable %v% contains literal value a^b, call :foo "%v%" assigns "a^^b"(!) to %1 (the first parameter) in subroutine :foo.
      • Unquoted use of ^ with call is broken altogether in that ^ can no longer be used to escape special characters: e.g., call foo.cmd a^&b quietly breaks (instead of passing literal a&b too foo.cmd, as would be the case without call) - foo.cmd is never even invoked(!), at least on Windows 7.
  • Escaping a literal % is a special case, unfortunately, which requires distinct syntax depending on whether a string is specified on the command line vs. inside a batch file; see https://stackoverflow.com/a/31420292/45375

    • The short of it: Inside a batch file, use %%. On the command line, % cannot be escaped, but if you place a ^ at the start, end, or inside a variable name in an unquoted string (e.g., echo %^foo%), you can prevent variable expansion (interpolation); % instances on the command line that are not part of a variable reference are treated as literals (e.g, 100%).
  • Generally, to safely work with variable values that may contain spaces and special characters:

    • Assignment: Enclose both the variable name and the value in a single pair of double-quotes; e.g., set "v=a & b" assigns literal value a & b to variable %v% (by contrast, set v="a & b" would make the double-quotes part of the value). Escape literal % instances as %% (works only in batch files - see above).
    • Reference: Double-quote variable references to make sure their value is not interpolated; e.g., echo "%v%" does not subject the value of %v% to interpolation and prints "a & b" (but note that the double-quotes are invariably printed too). By contrast, echo %v% passes literal a to echo, interprets & as the command-sequencing operator, and therefore tries to execute a command named b.
      Also note the above caveat re use of ^ with the call statement.
    • External programs typically take care of removing enclosing double-quotes around parameters, but, as noted, in batch files you have to do it yourself (e.g., %~1 to remove enclosing double-quotes from the 1st parameter) and, sadly, there is no direct way that I know of to get echo to print a variable value faithfully without the enclosing double-quotes.
      • Neil offers a for-based workaround that works as long as the value has no embedded double quotes; e.g.:
        set "var=^&')|;,%!" for /f "delims=" %%v in ("%var%") do echo %%~v
  • cmd.exe does not recognize single-quotes as string delimiters - they are treated as literals and cannot generally be used to delimit strings with embedded whitespace; also, it follows that the tokens abutting the single-quotes and any tokens in between are treated as unquoted by cmd.exe and interpreted accordingly.

    • However, given that target programs ultimately perform their own argument parsing, some programs such as Ruby do recognize single-quoted strings even on Windows; by contrast, C/C++ executables, Perl and Python do not recognize them.
      Even if supported by the target program, however, it is not advisable to use single-quoted strings, given that their contents are not protected from potentially unwanted interpretation by cmd.exe.

Quoting from within PowerShell:

Windows PowerShell is a much more advanced shell than cmd.exe, and it has been a part of Windows for many years now (and PowerShell Core brought the PowerShell experience to macOS and Linux as well).

PowerShell works consistently internally with respect to quoting:

  • inside double-quoted strings, use `" or "" to escape double-quotes
  • inside single-quoted strings, use '' to escape single-quotes

This works on the PowerShell command line and when passing parameters to PowerShell scripts or functions from within PowerShell.

(As discussed above, passing an escaped double-quote to PowerShell from the outside requires \" or, more robustly, \"" - nothing else works).

Sadly, when invoking external programs from PowerShell, you're faced with the need to both accommodate PowerShell's own quoting rules and to escape for the target program:

This problematic behavior is also discussed and summarized in this answer

Double-quotes inside double-quoted strings:

Consider string "3`" of rain", which PowerShell-internally translates to literal 3" of rain.

If you want to pass this string to an external program, you have to apply the target program's escaping in addition to PowerShell's; say you want to pass the string to a C program, which expects embedded double-quotes to be escaped as \":

foo.exe "3\`" of rain"

Note how both `" - to make PowerShell happy - and the \ - to make the target program happy - must be present.

The same logic applies to invoking a batch file, where "" must be used:

foo.bat "3`"`" of rain"

By contrast, embedding single-quotes in a double-quoted string requires no escaping at all.

Single-quotes inside single-quoted strings do not require extra escaping; consider '2'' of snow', which is PowerShell' representation of 2' of snow.

foo.exe '2'' of snow'
foo.bat '2'' of snow'

PowerShell translates single-quoted strings to double-quoted ones before passing them to the target program.

However, double-quotes inside single-quoted strings, which do not need escaping for PowerShell, do still need to be escaped for the target program:

foo.exe '3\" of rain'
foo.bat '3"" of rain'

PowerShell v3 introduced the magic --% option, called the stop-parsing symbol, which alleviates some of the pain, by passing anything after it uninterpreted to the target program, save for cmd.exe-style environment-variable references (e.g., %USERNAME%), which are expanded; e.g.:

foo.exe --% "3\" of rain" -u %USERNAME%

Note how escaping the embedded " as \" for the target program only (and not also for PowerShell as \`") is sufficient.

However, this approach:

  • does not allow for escaping % characters in order to avoid environment-variable expansions.
  • precludes direct use of PowerShell variables and expressions; instead, the command line must be built in a string variable in a first step, and then invoked with Invoke-Expression in a second.

Thus, despite its many advancements, PowerShell has not made escaping much easier when calling external programs. It has, however, introduced support for single-quoted strings.

I wonder if it's fundamentally possible in the Windows world to ever switch to the Unix model of letting the shell do all the tokenization and quote removal predictably, up front, irrespective of the target program, and then invoke the target program by passing the resulting tokens.

Math functions in AngularJS bindings

If you're looking to do a simple round in Angular you can easily set the filter inside your expression. For example:

{{ val | number:0 }}

See this CodePen example & for other number filter options.

Angular Docs on using Number Filters

How to change the style of a DatePicker in android?

Calendar calendar = Calendar.getInstance();

DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.DatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
  public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    Calendar newDate = Calendar.getInstance();
    newDate.set(year, monthOfYear, dayOfMonth);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = simpleDateFormat.format(newDate.getTime());
  }
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

datePickerDialog.show();

And use this style:

<style name="DatePickerDialogTheme" parent="Theme.AppCompat.Light.Dialog">
  <item name="colorAccent">@color/colorPrimary</item>
</style>

Is it possible to use Visual Studio on macOS?

Yes! You can use the new Visual Studio for Mac, which Microsoft launched in November.

Read about it here: https://msdn.microsoft.com/magazine/mt790182

Download a preview version here: https://www.visualstudio.com/vs/visual-studio-mac/

Bootstrap: Open Another Modal in Modal

The answer given by H Dog is great, but this approach was actually giving me some modal flicker in Internet Explorer 11. Bootstrap will first hide the modal removing the 'modal-open' class, and then (using H Dogs solution) we add the 'modal-open' class again. I suspect this is somehow causing the flicker I was seeing, maybe due to some slow HTML/CSS rendering.

Another solution is to prevent bootstrap in removing the 'modal-open' class from the body element in the first place. Using Bootstrap 3.3.7, this override of the internal hideModal function works perfectly for me.

$.fn.modal.Constructor.prototype.hideModal = function () {
    var that = this
    this.$element.hide()
    this.backdrop(function () {
        if ($(".modal:visible").length === 0) {
            that.$body.removeClass('modal-open')
        }
        that.resetAdjustments()
        that.resetScrollbar()
        that.$element.trigger('hidden.bs.modal')
    })
}

In this override, the 'modal-open' class is only removed when there are no visible modals on the screen. And you prevent one frame of removing and adding a class to the body element.

Just include the override after bootstrap have been loaded.

PHP validation/regex for URL

Here's a simple class for URL Validation using RegEx and then cross-references the domain against popular RBL (Realtime Blackhole Lists) servers:

Install:

require 'URLValidation.php';

Usage:

require 'URLValidation.php';
$urlVal = new UrlValidation(); //Create Object Instance

Add a URL as the parameter of the domain() method and check the the return.

$urlArray = ['http://www.bokranzr.com/test.php?test=foo&test=dfdf', 'https://en-gb.facebook.com', 'https://www.google.com'];
foreach ($urlArray as $k=>$v) {

    echo var_dump($urlVal->domain($v)) . ' URL: ' . $v . '<br>';

}

Output:

bool(false) URL: http://www.bokranzr.com/test.php?test=foo&test=dfdf
bool(true) URL: https://en-gb.facebook.com
bool(true) URL: https://www.google.com

As you can see above, www.bokranzr.com is listed as malicious website via an RBL so the domain was returned as false.

PHP - Get array value with a numeric index

$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
$array = array_values($array);
echo $array[0]; //bar
echo $array[1]; //bin
echo $array[2]; //ipsum

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

  • Save your work,
  • Close Visual Studio, then
  • Re-open your project

This worked for me.

asp.net mvc3 return raw html to view

public ActionResult Questionnaire()
{
    return Redirect("~/MedicalHistory.html");
}

What to do about Eclipse's "No repository found containing: ..." error messages?

None of the other answers worked for me (Windows 10, Eclipse Neon). Running Eclipse as Administrator fixed it.

SQL Server - INNER JOIN WITH DISTINCT

It's not the same doing a select distinct at the beginning because you are wasting all the calculated rows from the result.

select a.FirstName, a.LastName, v.District
from AddTbl a order by Firstname
natural join (select distinct LastName from
            ValTbl v  where a.LastName = v.LastName)

try that.

How to return multiple values in one column (T-SQL)?

DECLARE @Str varchar(500)

SELECT @Str=COALESCE(@Str,'') + CAST(ID as varchar(10)) + ','
FROM dbo.fcUser

SELECT @Str

How do I select an element that has a certain class?

The CSS :first-child selector allows you to target an element that is the first child element within its parent.

element:first-child { style_properties }
table:first-child { style_properties }

Darkening an image with CSS (In any shape)

I would make a new image of the dog's silhouette (black) and the rest the same as the original image. In the html, add a wrapper div with this silhouette as as background. Now, make the original image semi-transparent. The dog will become darker and the background of the dog will stay the same. You can do :hover tricks by setting the opacity of the original image to 100% on hover. Then the dog pops out when you mouse over him!

style

.wrapper{background-image:url(silhouette.png);} 
.original{opacity:0.7:}
.original:hover{opacity:1}

<div class="wrapper">
  <div class="img">
    <img src="original.png">
  </div>
</div>

Clearing content of text file using C#

Just open the file with the FileMode.Truncate flag, then close it:

using (var fs = new FileStream(@"C:\path\to\file", FileMode.Truncate))
{
}

How to write logs in text file when using java.util.logging.Logger

Maybe this is what you need...

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 * LogToFile class
 * This class is intended to be use with the default logging class of java
 * It save the log in an XML file  and display a friendly message to the user
 * @author Ibrabel <[email protected]>
 */
public class LogToFile {

    protected static final Logger logger=Logger.getLogger("MYLOG");
    /**
     * log Method 
     * enable to log all exceptions to a file and display user message on demand
     * @param ex
     * @param level
     * @param msg 
     */
    public static void log(Exception ex, String level, String msg){

        FileHandler fh = null;
        try {
            fh = new FileHandler("log.xml",true);
            logger.addHandler(fh);
            switch (level) {
                case "severe":
                    logger.log(Level.SEVERE, msg, ex);
                    if(!msg.equals(""))
                        JOptionPane.showMessageDialog(null,msg,
                            "Error", JOptionPane.ERROR_MESSAGE);
                    break;
                case "warning":
                    logger.log(Level.WARNING, msg, ex);
                    if(!msg.equals(""))
                        JOptionPane.showMessageDialog(null,msg,
                            "Warning", JOptionPane.WARNING_MESSAGE);
                    break;
                case "info":
                    logger.log(Level.INFO, msg, ex);
                    if(!msg.equals(""))
                        JOptionPane.showMessageDialog(null,msg,
                            "Info", JOptionPane.INFORMATION_MESSAGE);
                    break;
                case "config":
                    logger.log(Level.CONFIG, msg, ex);
                    break;
                case "fine":
                    logger.log(Level.FINE, msg, ex);
                    break;
                case "finer":
                    logger.log(Level.FINER, msg, ex);
                    break;
                case "finest":
                    logger.log(Level.FINEST, msg, ex);
                    break;
                default:
                    logger.log(Level.CONFIG, msg, ex);
                    break;
            }
        } catch (IOException | SecurityException ex1) {
            logger.log(Level.SEVERE, null, ex1);
        } finally{
            if(fh!=null)fh.close();
        }
    }

    public static void main(String[] args) {

        /*
            Create simple frame for the example
        */
        JFrame myFrame = new JFrame();
        myFrame.setTitle("LogToFileExample");
        myFrame.setSize(300, 100);
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setLocationRelativeTo(null);
        JPanel pan = new JPanel();
        JButton severe = new JButton("severe");
        pan.add(severe);
        JButton warning = new JButton("warning");
        pan.add(warning);
        JButton info = new JButton("info");
        pan.add(info);

        /*
            Create an exception on click to use the LogToFile class
        */
        severe.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                int j = 20, i = 0;
                try {
                    System.out.println(j/i);
                } catch (ArithmeticException ex) {
                    log(ex,"severe","You can't divide anything by zero");
                }

            }

        });

        warning.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                int j = 20, i = 0;
                try {
                    System.out.println(j/i);
                } catch (ArithmeticException ex) {
                    log(ex,"warning","You can't divide anything by zero");
                }

            }

        });

        info.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                int j = 20, i = 0;
                try {
                    System.out.println(j/i);
                } catch (ArithmeticException ex) {
                    log(ex,"info","You can't divide anything by zero");
                }

            }

        });

        /*
            Add the JPanel to the JFrame and set the JFrame visible
        */
        myFrame.setContentPane(pan);
        myFrame.setVisible(true);
    }
}

Update some specific field of an entity in android Room

If you need to update user information for a specific user ID "x",

  1. you need to create a dbManager class that will initialise the database in its constructor and acts as a mediator between your viewModel and DAO, and also .
  2. The ViewModel will initialize an instance of dbManager to access the database. The code should look like this:

       @Entity
        class User{
        @PrimaryKey
        String userId;
        String username;
        }
    
        Interface UserDao{
        //forUpdate
        @Update
        void updateUser(User user)
        }
    
        Class DbManager{
        //AppDatabase gets the static object o roomDatabase.
        AppDatabase appDatabase;
        UserDao userDao;
        public DbManager(Application application ){
        appDatabase = AppDatabase.getInstance(application);
    
        //getUserDao is and abstract method of type UserDao declared in AppDatabase //class
        userDao = appDatabase.getUserDao();
        } 
    
        public void updateUser(User user, boolean isUpdate){
        new InsertUpdateUserAsyncTask(userDao,isUpdate).execute(user);
        }
    
    
    
        public static class InsertUpdateUserAsyncTask extends AsyncTask<User, Void, Void> {
    
    
         private UserDao userDAO;
         private boolean isInsert;
    
         public InsertUpdateBrandAsyncTask(BrandDAO userDAO, boolean isInsert) {
           this. userDAO = userDAO;
           this.isInsert = isInsert;
         }
    
         @Override
         protected Void doInBackground(User... users) {
           if (isInsert)
        userDAO.insertBrand(brandEntities[0]);
           else
        //for update
        userDAO.updateBrand(users[0]);
        //try {
        //  Thread.sleep(1000);
        //} catch (InterruptedException e) {
        //  e.printStackTrace();
        //}
           return null;
         }
          }
        }
    
         Class UserViewModel{
         DbManager dbManager;
         public UserViewModel(Application application){
         dbmanager = new DbMnager(application);
         }
    
         public void updateUser(User user, boolean isUpdate){
         dbmanager.updateUser(user,isUpdate);
         }
    
         }
    
    
    
    
    Now in your activity or fragment initialise your UserViewModel like this:
    
    UserViewModel userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    

    Then just update your user item this way, suppose your userId is 1122 and userName is "xyz" which has to be changed to "zyx".

    Get an userItem of id 1122 User object

User user = new user();
 if(user.getUserId() == 1122){
   user.setuserName("zyx");
   userViewModel.updateUser(user);
 }

This is a raw code, hope it helps you.

Happy coding

Plotting time-series with Date labels on x-axis

1) Since the times are dates be sure to use "Date" class, not "POSIXct" or "POSIXlt". See R News 4/1 for advice and try this where Lines is defined in the Note at the end. No packages are used here.

dm <- read.table(text = Lines, header = TRUE)
dm$Date <- as.Date(dm$Date, "%m/%d/%Y")
plot(Visits ~ Date, dm, xaxt = "n", type = "l")
axis(1, dm$Date, format(dm$Date, "%b %d"), cex.axis = .7)

The use of text = Lines is just to keep the example self-contained and in reality it would be replaced with something like "myfile.dat" . (continued after image)

screenshot

2) Since this is a time series you may wish to use a time series representation giving slightly simpler code:

library(zoo)

z <- read.zoo(text = Lines, header = TRUE, format = "%m/%d/%Y")
plot(z, xaxt = "n")
axis(1, dm$Date, format(dm$Date, "%b %d"), cex.axis = .7)

Depending on what you want the plot to look like it may be sufficient just to use plot(Visits ~ Date, dm) in the first case or plot(z) in the second case suppressing the axis command entirely. It could also be done using xyplot.zoo

library(lattice)
xyplot(z)

or autoplot.zoo:

library(ggplot2)
autoplot(z)

Note:

Lines <- "Date            Visits
11/1/2010   696537
11/2/2010   718748
11/3/2010   799355
11/4/2010   805800
11/5/2010   701262
11/6/2010   531579
11/7/2010   690068
11/8/2010   756947
11/9/2010   718757
11/10/2010  701768
11/11/2010  820113
11/12/2010  645259"

Select box arrow style

Browsers and OS's determine the style of the select boxes in most cases, and it's next to impossible to alter them with CSS alone. You'll have to look into replacement methods. The main trick is to apply appearance: none which lets you override some of the styling.

My favourite method is this one:

http://cssdeck.com/item/265/styling-select-box-with-css3

It doesn't replace the OS select menu UI element so all the problems related to doing that are non-existant (not being able to break out of the browser window with a long list being the main one).

Good luck :)

Checking if form has been submitted - PHP

On a different note, it is also always a good practice to add a token to your form and verify it to check if the data was not sent from outside. Here are the steps:

  1. Generate a unique token (you can use hash) Ex:

    $token = hash (string $algo , string $data [, bool $raw_output = FALSE ] );
    
  2. Assign this token to a session variable. Ex:

    $_SESSION['form_token'] = $token;
    
  3. Add a hidden input to submit the token. Ex:

    input type="hidden" name="token" value="{$token}"
    
  4. then as part of your validation, check if the submitted token matches the session var.

    Ex: if ( $_POST['token'] === $_SESSION['form_token'] ) ....
    

How to set time to midnight for current day?

I believe you are looking for DateTime.Today. The documentation states:

An object that is set to today's date, with the time component set to 00:00:00.

http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx

Your code would be

DateTime _Begin = DateTime.Today;

How would I check a string for a certain letter in Python?

in keyword allows you to loop over a collection and check if there is a member in the collection that is equal to the element.

In this case string is nothing but a list of characters:

dog = "xdasds"
if "x" in dog:
     print "Yes!"

You can check a substring too:

>>> 'x' in "xdasds"
True
>>> 'xd' in "xdasds"
True
>>> 
>>> 
>>> 'xa' in "xdasds"
False

Think collection:

>>> 'x' in ['x', 'd', 'a', 's', 'd', 's']
True
>>> 

You can also test the set membership over user defined classes.

For user-defined classes which define the __contains__ method, x in y is true if and only if y.__contains__(x) is true.

phpmyadmin.pma_table_uiprefs doesn't exist

I just located the create_tables.sql, saved to my desktop, opened phpMyAdmin, selected the import tab, selected the create_tables.sql, clicked ok

How to connect to a secure website using SSL in Java with a pkcs12 file?

It appears that you are extracting you certificate from the PKCS #12 key store and creating a new Java key store (with type "JKS"). You don't strictly have to provide a trust store password (although using one allows you to test the integrity of your root certificates).

So, try your program with only the following SSL properties set. The list shown in your question is over-specified and may be causing problems.

System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

Also, using the PKCS #12 file directly as the trust store should work, as long as the CA certificate is detected as a "trusted" entry. But in that case, you'll have to specify the javax.net.ssl.trustStoreType property as "PKCS12" too.

Try with these properties only. If you get the same error, I suspect your problem is not the key store. If it still occurs, post more of the stack trace in your question to narrow the problem down.


The new error, "the trustAnchors parameter must be non-empty," could be due to setting the javax.net.ssl.trustStore property to a file that doesn't exist; if the file cannot be opened, an empty key store created, which would lead to this error.

IOException: Too many open files

Don't know the nature of your app, but I have seen this error manifested multiple times because of a connection pool leak, so that would be worth checking out. On Linux, socket connections consume file descriptors as well as file system files. Just a thought.

Excel 2010 VBA Referencing Specific Cells in other worksheets

Sub Results2()

    Dim rCell As Range
    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim lCnt As Long

    Set shSource = ThisWorkbook.Sheets("Sheet1")
    Set shDest = ThisWorkbook.Sheets("Sheet2")

    For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
        lCnt = lCnt + 1
        shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
    Next rCell

End Sub

This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.

To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.

I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,

Sub Results3()

    Dim i As Long, lCnt As Long
    Dim sh As Worksheet

    lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
    Set sh = ThisWorkbook.Sheets("Sheet2")

    Const sSOURCE As String = "Sheet1!"

    For i = 1 To lCnt
        sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
    Next i

End Sub

What is the path that Django uses for locating and loading templates?

Smart solution in Django 2.0.3 for keeping templates in project directory (/root/templates/app_name):

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMP_DIR = os.path.join(BASE_DIR, 'templates')
...
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [TEMP_DIR],
...

in views.py just add such template path:

app_name/html_name

LD_LIBRARY_PATH vs LIBRARY_PATH

LIBRARY_PATH is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.

LD_LIBRARY_PATH is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.

EDIT: As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH comes into play.

How can I keep my branch up to date with master with git?

If your branch is local only and hasn't been pushed to the server, use

git rebase master

Otherwise, use

git merge master