Programs & Examples On #Skelta

Skelta BPM is a BPM workflow software that is built on today's cutting-edge Microsoft .NET, XML, and Web services technologies.

remove all variables except functions

I wrote this to remove all objects apart from functions from the current environment (Programming language used is R with IDE R-Studio):

    remove_list=c()                             # create a vector

      for(i in 1:NROW(ls())){                   # repeat over all objects in environment
        if(class(get(ls()[i]))!="function"){    # if object is *not* a function
         remove_list=c(remove_list,ls()[i])     # ..add to vector remove_list
         }    
      }

    rm(list=remove_list)                        # remove all objects named in remove_list

Notes-

The argument "list" in rm(list=) must be a character vector.

The name of an object in position i of the current environment is returned from ls()[i] and the object itself from get(ls()[i]). Therefore the class of an object is returned from class(get(ls()[i]))

How to trigger click on page load?

$(function(){

    $(selector).click();

});

nginx: send all requests to a single html page

Your original rewrite should almost work. I'm not sure why it would be redirecting, but I think what you really want is just

rewrite ^ /base.html break;

You should be able to put that in a location or directly in the server.

How can I check if a View exists in a Database?

For people checking the existence to drop View use this

From SQL Server 2016 CTP3 you can use new DIE statements instead of big IF wrappers

syntax

DROP VIEW [ IF EXISTS ] [ schema_name . ] view_name [ ...,n ] [ ; ]

Query :

DROP VIEW IF EXISTS view_name

More info here

How to sort two lists (which reference each other) in the exact same way

Another approach to retaining the order of a string list when sorting against another list is as follows:

list1 = [3,2,4,1, 1]
list2 = ['three', 'two', 'four', 'one', 'one2']

# sort on list1 while retaining order of string list
sorted_list1 = [y for _,y in sorted(zip(list1,list2),key=lambda x: x[0])]
sorted_list2 = sorted(list1)

print(sorted_list1)
print(sorted_list2)

output

['one', 'one2', 'two', 'three', 'four']
[1, 1, 2, 3, 4]

How to set -source 1.7 in Android Studio and Gradle

At current, Android doesn't support Java 7, only Java 6. New features in Java 7 such as the diamond syntax are therefore not currently supported. Finding sources to support this isn't easy, but I could find that the Dalvic engine is built upon a subset of Apache Harmony which only ever supported Java up to version 6. And if you check the system requirements for developing Android apps it also states that at least JDK 6 is needed (though this of course isn't real proof, just an indication). And this says pretty much the same as I have. If I find anything more substancial, I'll add it.

Edit: It seems Java 7 support has been added since I originally wrote this answer; check the answer by Sergii Pechenizkyi.

How can I do an asc and desc sort using underscore.js?

Similar to Underscore library there is another library called as 'lodash' that has one method "orderBy" which takes in the parameter to determine in which order to sort it. You can use it like

_.orderBy('collection', 'propertyName', 'desc')

For some reason, it's not documented on the website docs.

Get local href value from anchor (a) tag

In my case I had a href with a # and target.href was returning me the complete url. Target.hash did the work for me.

$(".test a").on('click', function(e) {
    console.log(e.target.href); // logs https://www.test.com/#test
    console.log(e.target.hash); // logs #test
  });

HTML form do some "action" when hit submit button

index.html

<!DOCTYPE html>
<html>
   <body>
       <form action="submit.php" method="POST">
         First name: <input type="text" name="firstname" /><br /><br />
         Last name: <input type="text" name="lastname" /><br />
         <input type="submit" value="Submit" />
      </form> 
   </body>
</html>

After that one more file which page you want to display after pressing the submit button

submit.php

<html>
  <body>

    Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
    Your Last Name is -   <?php echo $_POST["lastname"]; ?>

  </body>
</html>

Remove border from buttons

Try using: border:0; or border:none;

Angular - Set headers for every request

You can create your own http client with some authorization header:

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HttpClientWithAuthorization {

  constructor(private http: HttpClient) {}

createAuthorizationHeader(bearerToken: string): HttpHeaders {
  const headerDict = {
    Authorization: 'Bearer ' + bearerToken,
  }
  return new HttpHeaders(headerDict);
}

get<T>(url, bearerToken) {
  this.createAuthorizationHeader(bearerToken);
  return this.http.get<T>(url, {
    headers: this.createAuthorizationHeader(bearerToken)
  });
}

post<T>(url, bearerToken, data) {
  this.createAuthorizationHeader(bearerToken);
  return this.http.post<T>(url, data, {
    headers: this.createAuthorizationHeader(bearerToken)
  });
}
}

And then inject it instead of HttpClient in your service class:

@Injectable({
  providedIn: 'root'
})
export class SomeService {

  constructor(readonly httpClientWithAuthorization: HttpClientWithAuthorization) {}

  getSomething(): Observable<Object> {
    return this.httpClientWithAuthorization.get<Object>(url,'someBearer');
  }

  postSomething(data) {
    return this.httpClientWithAuthorization.post<Object>(url,'someBearer', data);
  }
}

SVG drop shadow using css3

Here's an example of applying dropshadow to some svg using the 'filter' property. If you want to control the opacity of the dropshadow have a look at this example. The slope attribute controls how much opacity to give to the dropshadow.

Relevant bits from the example:

<filter id="dropshadow" height="130%">
  <feGaussianBlur in="SourceAlpha" stdDeviation="3"/> <!-- stdDeviation is how much to blur -->
  <feOffset dx="2" dy="2" result="offsetblur"/> <!-- how much to offset -->
  <feComponentTransfer>
    <feFuncA type="linear" slope="0.5"/> <!-- slope is the opacity of the shadow -->
  </feComponentTransfer>
  <feMerge> 
    <feMergeNode/> <!-- this contains the offset blurred image -->
    <feMergeNode in="SourceGraphic"/> <!-- this contains the element that the filter is applied to -->
  </feMerge>
</filter>
<circle r="10" style="filter:url(#dropshadow)"/>

Box-shadow is defined to work on CSS boxes (read: rectangles), while svg is a bit more expressive than just rectangles. Read the SVG Primer to learn a bit more about what you can do with SVG filters.

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

There are two ways to resolve this error:

  1. Include /etc/apache2/httpd.conf

    Add the above line in file /etc/apache2/apache2.conf

  2. Add this line at the end of the file /etc/apache2/apache2.conf:

    ServerName localhost

Can my enums have friendly names?

You can use the Description attribute to get that friendly name. You can use the code below:

public static string ToStringEnums(Enum en)
{
    Type type = en.GetType();

    MemberInfo[] memInfo = type.GetMember(en.ToString());
    if (memInfo != null && memInfo.Length > 0)
    {
        object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attrs != null && attrs.Length > 0)
            return ((DescriptionAttribute)attrs[0]).Description;
    }
    return en.ToString();
}

An example of when you would want to use this method: When your enum value is EncryptionProviderType and you want enumVar.Tostring() to return "Encryption Provider Type".

Prerequisite: All enum members should be applied with the attribute [Description("String to be returned by Tostring()")].

Example enum:

enum ExampleEnum
{
    [Description("One is one")]
    ValueOne = 1,
    [Description("Two is two")]
    ValueTow = 2
}

And in your class, you would use it like this:

ExampleEnum enumVar = ExampleEnum.ValueOne;
Console.WriteLine(ToStringEnums(enumVar));

includes() not working in all browsers

IE11 does implement String.prototype.includes so why not using the official Polyfill?

Source: polyfill source

  if (!String.prototype.includes) {
    String.prototype.includes = function(search, start) {
      if (typeof start !== 'number') {
        start = 0;
      }

      if (start + search.length > this.length) {
        return false;
      } else {
        return this.indexOf(search, start) !== -1;
      }
    };
  }

res.sendFile absolute path

res.sendFile( __dirname + "/public/" + "index1.html" );

where __dirname will manage the name of the directory that the currently executing script ( server.js ) resides in.

How to input automatically when running a shell over SSH?

For general command-line automation, Expect is the classic tool. Or try pexpect if you're more comfortable with Python.

Here's a similar question that suggests using Expect: Use expect in bash script to provide password to SSH command

How to mute an html5 video player using jQuery

If you don't want to jQuery, here's the vanilla JavaScript:

///Mute
var video = document.getElementById("your-video-id");
video.muted= true;

//Unmute
var video = document.getElementById("your-video-id");
video.muted= false;

It will work for audio too, just put the element's id and it will work (and change the var name if you want, to 'media' or something suited for both audio/video as you like).

set value of input field by php variable's value

inside the Form, You can use this code. Replace your variable name (i use $variable)

<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">

%i or %d to print integer in C using printf()?

both %d and %i can be used to print an integer

%d stands for "decimal", and %i for "integer." You can use %x to print in hexadecimal, and %o to print in octal.

You can use %i as a synonym for %d, if you prefer to indicate "integer" instead of "decimal."

On input, using scanf(), you can use use both %i and %d as well. %i means parse it as an integer in any base (octal, hexadecimal, or decimal, as indicated by a 0 or 0x prefix), while %d means parse it as a decimal integer.

check here for more explanation

why does %d stand for Integer?

Apply CSS style attribute dynamically in Angular JS

Simply do this:

_x000D_
_x000D_
<div ng-style="{'background-color': '{{myColorVariable}}', height: '2rem'}"></div>
_x000D_
_x000D_
_x000D_

MySQL with Node.js

Imo, you should try MySQL Connector/Node.js which is the official Node.js driver for MySQL. See ref-1 and ref-2 for detailed explanation. I have tried mysqljs/mysql which is available here, but I don't find detailed documentation on classes, methods, properties of this library.

So I switched to the standard MySQL Connector/Node.js with X DevAPI, since it is an asynchronous Promise-based client library and provides good documentation. Take a look at the following code snippet :

const mysqlx = require('@mysql/xdevapi');
const rows = [];

mysqlx.getSession('mysqlx://localhost:33060')
.then(session => {
    const table = session.getSchema('testSchema').getTable('testTable');

    // The criteria is defined through the expression.
    return table.update().where('name = "bar"').set('age', 50)
        .execute()
        .then(() => {
            return table.select().orderBy('name ASC')
                .execute(row => rows.push(row));
        });
})
.then(() => {
    console.log(rows);
});

Execute a batch file on a remote PC using a batch file on local PC

If you are in same WORKGROUP shutdown.exe /s /m \\<target-computer-name> should be enough shutdown /? for more, otherwise you need software to connect and control the target server.

UPDATE:

Seems shutdown.bat here is for shutting down apache-tomcat.

So, you might be interested to psexec or PuTTY: A Free Telnet/SSH Client

As native solution could be wmic

Example:

wmic /node:<target-computer-name> process call create "cmd.exe c:\\somefolder\\batch.bat"

In your example should be:

wmic /node:inidsoasrv01 process call create ^
    "cmd.exe D:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat"

wmic /? and wmic /node /? for more

Disable activity slide-in animation when launching new activity?

Apply

startActivity(new Intent(FirstActivity.this,SecondActivity.class));

then

overridePendingTransition(0, 0);

This will stop the animation.

disable editing default value of text input

Probably due to the fact that I could not explain well you do not really understand my question. In general, I found the solution.

Sorry for my english

Finding three elements in an array whose sum is closest to a given number

This can be solved efficiently in O(n log (n)) as following. I am giving solution which tells if sum of any three numbers equal a given number.

import java.util.*;
public class MainClass {
        public static void main(String[] args) {
        int[] a = {-1, 0, 1, 2, 3, 5, -4, 6};
        System.out.println(((Object) isThreeSumEqualsTarget(a, 11)).toString());
}

public static boolean isThreeSumEqualsTarget(int[] array, int targetNumber) {

    //O(n log (n))
    Arrays.sort(array);
    System.out.println(Arrays.toString(array));

    int leftIndex = 0;
    int rightIndex = array.length - 1;

    //O(n)
    while (leftIndex + 1 < rightIndex - 1) {
        //take sum of two corners
        int sum = array[leftIndex] + array[rightIndex];
        //find if the number matches exactly. Or get the closest match.
        //here i am not storing closest matches. You can do it for yourself.
        //O(log (n)) complexity
        int binarySearchClosestIndex = binarySearch(leftIndex + 1, rightIndex - 1, targetNumber - sum, array);
        //if exact match is found, we already got the answer
        if (-1 == binarySearchClosestIndex) {
            System.out.println(("combo is " + array[leftIndex] + ", " + array[rightIndex] + ", " + (targetNumber - sum)));
            return true;
        }
        //if exact match is not found, we have to decide which pointer, left or right to move inwards
        //we are here means , either we are on left end or on right end
        else {

            //we ended up searching towards start of array,i.e. we need a lesser sum , lets move inwards from right
            //we need to have a lower sum, lets decrease right index
            if (binarySearchClosestIndex == leftIndex + 1) {
                rightIndex--;
            } else if (binarySearchClosestIndex == rightIndex - 1) {
                //we need to have a higher sum, lets decrease right index
                leftIndex++;
            }
        }
    }
    return false;
}

public static int binarySearch(int start, int end, int elem, int[] array) {
    int mid = 0;
    while (start <= end) {
        mid = (start + end) >>> 1;
        if (elem < array[mid]) {
            end = mid - 1;
        } else if (elem > array[mid]) {
            start = mid + 1;
        } else {
            //exact match case
            //Suits more for this particular case to return -1
            return -1;
        }
    }
    return mid;
}
}

Why calling react setState method doesn't mutate the state immediately?

async-await syntax works perfectly for something like the following...

changeStateFunction = () => {
  // Some Worker..

  this.setState((prevState) => ({
  year: funcHandleYear(),
  month: funcHandleMonth()
}));

goNextMonth = async () => {
  await this.changeStateFunction();
  const history = createBrowserHistory();
  history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}

goPrevMonth = async () => {
  await this.changeStateFunction();
  const history = createBrowserHistory();
  history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}

How can I tell gcc not to inline a function?

GCC has a switch called

-fno-inline-small-functions

So use that when invoking gcc. But the side effect is that all other small functions are also non-inlined.

How to automatically generate N "distinct" colors?

If N is big enough, you're going to get some similar-looking colors. There's only so many of them in the world.

Why not just evenly distribute them through the spectrum, like so:

IEnumerable<Color> CreateUniqueColors(int nColors)
{
    int subdivision = (int)Math.Floor(Math.Pow(nColors, 1/3d));
    for(int r = 0; r < 255; r += subdivision)
        for(int g = 0; g < 255; g += subdivision)
            for(int b = 0; b < 255; b += subdivision)
                yield return Color.FromArgb(r, g, b);
}

If you want to mix up the sequence so that similar colors aren't next to each other, you could maybe shuffle the resulting list.

Am I underthinking this?

$(...).datepicker is not a function - JQuery - Bootstrap

Need to include jquery-ui too:

<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Print array without brackets and commas

I used join() function like:

i=new Array("Hi", "Hello", "Cheers", "Greetings");
i=i.join("");

Which Prints:
HiHelloCheersGreetings


See more: Javascript Join - Use Join to Make an Array into a String in Javascript

How do I split a multi-line string into multiple lines?

I wish comments had proper code text formatting, because I think @1_CR 's answer needs more bumps, and I would like to augment his answer. Anyway, He led me to the following technique; it will use cStringIO if available (BUT NOTE: cStringIO and StringIO are not the same, because you cannot subclass cStringIO... it is a built-in... but for basic operations the syntax will be identical, so you can do this):

try:
    import cStringIO
    StringIO = cStringIO
except ImportError:
    import StringIO

for line in StringIO.StringIO(variable_with_multiline_string):
    pass
print line.strip()

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

When creating a Dockerfile, there are two commands that you can use to copy files/directories into it – ADD and COPY. Although there are slight differences in the scope of their function, they essentially perform the same task.

So, why do we have two commands, and how do we know when to use one or the other?

DOCKER ADD COMMAND

Let’s start by noting that the ADD command is older than COPY. Since the launch of the Docker platform, the ADD instruction has been part of its list of commands.

The command copies files/directories to a file system of the specified container.

The basic syntax for the ADD command is:

ADD <src> … <dest>

It includes the source you want to copy (<src>) followed by the destination where you want to store it (<dest>). If the source is a directory, ADD copies everything inside of it (including file system metadata).

For instance, if the file is locally available and you want to add it to the directory of an image, you type:

ADD /source/file/path  /destination/path

ADD can also copy files from a URL. It can download an external file and copy it to the wanted destination. For example:

ADD http://source.file/url  /destination/path

An additional feature is that it copies compressed files, automatically extracting the content in the given destination. This feature only applies to locally stored compressed files/directories.

ADD source.file.tar.gz /temp

Bear in mind that you cannot download and extract a compressed file/directory from a URL. The command does not unpack external packages when copying them to the local filesystem.

DOCKER COPY COMMAND

Due to some functionality issues, Docker had to introduce an additional command for duplicating content – COPY.

Unlike its closely related ADD command, COPY only has only one assigned function. Its role is to duplicate files/directories in a specified location in their existing format. This means that it doesn’t deal with extracting a compressed file, but rather copies it as-is.

The instruction can be used only for locally stored files. Therefore, you cannot use it with URLs to copy external files to your container.

To use the COPY instruction, follow the basic command format:

Type in the source and where you want the command to extract the content as follows:

COPY <src> … <dest> 

For example:

COPY /source/file/path  /destination/path 

Which command to use?(Best Practice)

Considering the circumstances in which the COPY command was introduced, it is evident that keeping ADD was a matter of necessity. Docker released an official document outlining best practices for writing Dockerfiles, which explicitly advises against using the ADD command.

Docker’s official documentation notes that COPY should always be the go-to instruction as it is more transparent than ADD.

If you need to copy from the local build context into a container, stick to using COPY.

The Docker team also strongly discourages using ADD to download and copy a package from a URL. Instead, it’s safer and more efficient to use wget or curl within a RUN command. By doing so, you avoid creating an additional image layer and save space.

NodeJS w/Express Error: Cannot GET /

You typically want to render templates like this:

app.get('/', function(req, res){
  res.render('index.ejs');
});

However you can also deliver static content - to do so use:

app.use(express.static(__dirname + '/public'));

Now everything in the /public directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm in the public folder if will be available by visiting /default.htm

Take a look through the express API and Connect Static middleware docs for more info.

Use '=' or LIKE to compare strings in SQL?

There is another reason for using "like" even if the performance is slower: Character values are implicitly converted to integer when compared, so:

declare @transid varchar(15)

if @transid != 0

will give you a "The conversion of the varchar value '123456789012345' overflowed an int column" error.

How do you set the EditText keyboard to only consist of numbers on Android?

For the EditText if we specify,

android:inputType="number"

only numbers can be got. But if you use,

android:inputType="phone"

along with the numbers it can accept special characters like ;,/". etc.

Using Image control in WPF to display System.Drawing.Bitmap

According to http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/

   [DllImport("gdi32")]
   static extern int DeleteObject(IntPtr o);

   public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
   {
       IntPtr ip = source.GetHbitmap();
       BitmapSource bs = null;
       try
       {
           bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, 
              IntPtr.Zero, Int32Rect.Empty, 
              System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
       }
       finally
       {
           DeleteObject(ip);
       }

       return bs;
   }

It gets System.Drawing.Bitmap (from WindowsBased) and converts it into BitmapSource, which can be actually used as image source for your Image control in WPF.

image1.Source = YourUtilClass.loadBitmap(SomeBitmap);

Remove characters from NSString?

Taken from NSString

stringByReplacingOccurrencesOfString:withString:

Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement

Parameters

target

The string to replace.

replacement

The string with which to replace target.

Return Value

A new string in which all occurrences of target in the receiver are replaced by replacement.

Is there a WebSocket client implemented for Python?

Autobahn has a good websocket client implementation for Python as well as some good examples. I tested the following with a Tornado WebSocket server and it worked.

from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS


class EchoClientProtocol(WebSocketClientProtocol):

   def sendHello(self):
      self.sendMessage("Hello, world!")

   def onOpen(self):
      self.sendHello()

   def onMessage(self, msg, binary):
      print "Got echo: " + msg
      reactor.callLater(1, self.sendHello)


if __name__ == '__main__':

   factory = WebSocketClientFactory("ws://localhost:9000")
   factory.protocol = EchoClientProtocol
   connectWS(factory)
   reactor.run()

Trim to remove white space

or just use $.trim(str)

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

You can set HorizontalAlignment to Left, set your MaxWidth and then bind Width to the ActualWidth of the parent element:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <StackPanel Name="Container">   
    <TextBox Background="Azure" 
    Width="{Binding ElementName=Container,Path=ActualWidth}"
    Text="Hello" HorizontalAlignment="Left" MaxWidth="200" />
  </StackPanel>
</Page>

Auto Scale TextView Text to Fit within Bounds

A workaround for Android 4.x:

I found AutoResizeTextView and it works great on my Android 2.1 emulator. I loved it so much. But unfortunately it failed on my own 4.0.4 cellphone and 4.1 emulator. After trying I found it could be easily resolved by adding following attributes in AutoResizeTextView class in the xml:

android:ellipsize="none"

android:singleLine="true"

With the 2 lines above, now AutoResizeTextView working perfectly on my 2.1 & 4.1 emulators and my own 4.0.4 cellphone now.

Hope this helps you. :-)

git checkout tag, git pull fails in branch

Switch back to the master branch using

$ git checkout master

and then run the git pull operation

$ git pull origin/master

Afterwards, you can switch back to your my_branch again.

css divide width 100% to 3 column

How about using the CSS3 flex model:

HTML Code:

<div id="wrapper">
    <div id="c1">c1</div>
    <div id="c2">c2</div>
    <div id="c3">c3</div>
</div>  

CSS Code:

*{
    margin:0;
    padding:0;
}

#wrapper{
    display:-webkit-flex;
    -webkit-justify-content:center;

    display:flex;
    justify-content:center;

}

#wrapper div{
    -webkit-flex:1;
    flex:1;
    border:thin solid #777;

}

How to debug a referenced dll (having pdb)

Make sure your DLL is not registered in the GAC. Visual Studio will use the version in the GAC and it will probably have no debugging information.

How do I turn off Oracle password expiration?

To alter the password expiry policy for a certain user profile in Oracle first check which profile the user is using:

select profile from DBA_USERS where username = '<username>';

Then you can change the limit to never expire using:

alter profile <profile_name> limit password_life_time UNLIMITED;

If you want to previously check the limit you may use:

select resource_name,limit from dba_profiles where profile='<profile_name>';

Recursive mkdir() system call on Unix

I'm not allowed to comment on the first (and accepted) answer (not enough rep), so I'll post my comments as code in a new answer. The code below is based on the first answer, but fixes a number of problems:

  • If called with a zero-length path, this does not read or write the character before the beginning of array opath[] (yes, "why would you call it that way?", but on the other hand "why would you not fix the vulnerability?")
  • the size of opath is now PATH_MAX (which isn't perfect, but is better than a constant)
  • if the path is as long as or longer than sizeof(opath) then it is properly terminated when copied (which strncpy() doesn't do)
  • you can specify the mode of the written directory, just as you can with the standard mkdir() (although if you specify non-user-writeable or non-user-executable then the recursion won't work)
  • main() returns the (required?) int
  • removed a few unnecessary #includes
  • I like the function name better ;)
// Based on http://nion.modprobe.de/blog/archives/357-Recursive-directory-creation.html
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>

static void mkdirRecursive(const char *path, mode_t mode) {
    char opath[PATH_MAX];
    char *p;
    size_t len;

    strncpy(opath, path, sizeof(opath));
    opath[sizeof(opath) - 1] = '\0';
    len = strlen(opath);
    if (len == 0)
        return;
    else if (opath[len - 1] == '/')
        opath[len - 1] = '\0';
    for(p = opath; *p; p++)
        if (*p == '/') {
            *p = '\0';
            if (access(opath, F_OK))
                mkdir(opath, mode);
            *p = '/';
        }
    if (access(opath, F_OK))         /* if path is not terminated with / */
        mkdir(opath, mode);
}


int main (void) {
    mkdirRecursive("/Users/griscom/one/two/three", S_IRWXU);
    return 0;
}

How many threads can a Java VM support?

After playing around with Charlie's DieLikeACode class, it looks like the Java thread stack size is a huge part of how many threads you can create.

-Xss set java thread stack size

For example

java -Xss100k DieLikeADog

But, Java has the Executor interface. I would use that, you will be able to submit thousands of Runnable tasks, and have the Executor process those tasks with a fixed number of threads.

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

NPM doesn't install module dependencies

I had the same problem. But on the same machine one project had good package.json, where all my dependencies are successfully installed. And in another project my package.json dependencies were not installed no matter what i do. I just copied the package.json and pasted into that another project. And it worked! The difference i have found was only empty line at the start of file. Dont know or it influences anything, maybe some other problem. But the problem was only the package.json file.

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

How to request Administrator access inside a batch file

Another approach is to

  • create a shortcut locally and set it to call for Admin permission (Properties, Advanced, Run as Admin)

and then

  • send your users the shortcut (or a link to the shortcut rather than one to the batch file itself).

XPath: difference between dot and text()

There is big difference between dot (".") and text() :-

  • The dot (".") in XPath is called the "context item expression" because it refers to the context item. This could be match with a node (such as an element, attribute, or text node) or an atomic value (such as a string, number, or boolean). While text() refers to match only element text which is in string form.

  • The dot (".") notation is the current node in the DOM. This is going to be an object of type Node while Using the XPath function text() to get the text for an element only gets the text up to the first inner element. If the text you are looking for is after the inner element you must use the current node to search for the string and not the XPath text() function.

For an example :-

<a href="something.html">
  <img src="filename.gif">
  link
</a>

Here if you want to find anchor a element by using text link, you need to use dot ("."). Because if you use //a[contains(.,'link')] it finds the anchor a element but if you use //a[contains(text(),'link')] the text() function does not seem to find it.

Hope it will help you..:)

What is the origin of foo and bar?

tl;dr

  • "Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.

  • Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).

  • Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.

  • Also, it seems likely the military FUBAR contributed to their popularity.


The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)


OK, so let's find some references.

STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:

On Foo-ism

The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")

As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.

It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!

The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:

By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.

...

It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.

Hopefully yours,

Indignant Mother of Five.

And The Tech in December 1938:

General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."


The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:

FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.

These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:

Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.

And from 1996's Jargon File 4.0.0:

Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."

A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):

Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!

Also 1964's MIT Voo Doo (PDF) references the TMRC usage:

Yes! I want to be an instant success and snow customers. Send me a degree in: ...

  • Foo Counters

  • Foo Jung


Let's find "foo", "bar" and "foobar" published in code examples.

So, Jargon File 4.4.7 says of "foobar":

Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.

The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:

Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.

Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z

I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:

car[((FOO . CROCK) . GLITCH)]

It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER

For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:

EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).


Some more recallations.

@Walter Mitty recalled on this site in 2008:

I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.

John V. Everett recalls in 1996:

When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.

Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.

It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.

Daniel P. B. Smith in 1998:

Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.

Robert Schuldenfrei in 1996:

The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?

Paul M. Wexelblat in 1992:

The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.

Bruce B. Reynolds in 1996:

On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...

Here's a straight IBM "BAR" from 1955.


Other early references:


I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.

Here are a some of even earlier F00s but I think they're coincidences/false positives:

How to Replace Multiple Characters in SQL?

I would seriously consider making a CLR UDF instead and using regular expressions (both the string and the pattern can be passed in as parameters) to do a complete search and replace for a range of characters. It should easily outperform this SQL UDF.

How to check if a windows form is already open, and close it if it is?

Funny, I had to add to this thread.

1) Add a global var on form.show() and clear out the var on form.close()

2) On the parent form add a timer. Keep the child form open and update your data every 10 min.

3) put timer on the child form to go update data on itself.

How do I get the total number of unique pairs of a set in the database?

I was solving this algorithm and get stuck with the pairs part.

This explanation help me a lot https://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/

So to calculate the sum of series of numbers:

n(n+1)/2

But you need to calculate this

1 + 2 + ... + (n-1)

So in order to get this you can use

n(n+1)/2 - n

that is equal to

n(n-1)/2

Pandas: Appending a row to a dataframe and specify its index label

I shall refer to the same sample of data as posted in the question:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))

Running this code will give you

The original data frame is:

          A         B         C         D
0  0.494824 -0.328480  0.818117  0.100290
1  0.239037  0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856  0.359811 -0.345560
3 -0.070814 -0.394711  0.081697 -1.178845
4 -1.638063  1.498027 -0.609325  0.882594
5 -0.510217  0.500475  1.039466  0.187076
6  1.116529  0.912380  0.869323  0.119459
7 -1.046507  0.507299 -0.373432 -1.024795

Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append returns a view of the dataframe and does not modify its contents. Following is the code:

row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))

Following would be the new output:

The new data frame is:

           A          B          C          D
0   0.494824  -0.328480   0.818117   0.100290
1   0.239037   0.954912  -0.186825  -0.651935
2  -1.818285  -0.158856   0.359811  -0.345560
3  -0.070814  -0.394711   0.081697  -1.178845
4  -1.638063   1.498027  -0.609325   0.882594
5  -0.510217   0.500475   1.039466   0.187076
6   1.116529   0.912380   0.869323   0.119459
7  -1.046507   0.507299  -0.373432  -1.024795
3  10.000000  20.000000  30.000000  40.000000

What's the difference between "static" and "static inline" function?

inline instructs the compiler to attempt to embed the function content into the calling code instead of executing an actual call.

For small functions that are called frequently that can make a big performance difference.

However, this is only a "hint", and the compiler may ignore it, and most compilers will try to "inline" even when the keyword is not used, as part of the optimizations, where its possible.

for example:

static int Inc(int i) {return i+1};
.... // some code
int i;
.... // some more code
for (i=0; i<999999; i = Inc(i)) {/*do something here*/};

This tight loop will perform a function call on each iteration, and the function content is actually significantly less than the code the compiler needs to put to perform the call. inline will essentially instruct the compiler to convert the code above into an equivalent of:

 int i;
 ....
 for (i=0; i<999999; i = i+1) { /* do something here */};

Skipping the actual function call and return

Obviously this is an example to show the point, not a real piece of code.

static refers to the scope. In C it means that the function/variable can only be used within the same translation unit.

Button background as transparent

You apply the background color as transparent(light gray) when you click the button.

ButtonName.setOnClickListener()

In the above method you set the background color of the button.

How to make tesseract to recognize only numbers, when they are mixed with letters?

For tesseract 3, i try to create config file according FAQ.

BEFORE calling an Init function or put this in a text file called tessdata/configs/digits:

tessedit_char_whitelist 0123456789                 

then, it works by using the command: tesseract imagename outputbase digits

Django - after login, redirect user to his custom page --> mysite.com/username

Got into django recently and been looking into a solution to that and found a method that might be useful.

So for example, if using allouth the default redirect is accounts/profile. Make a view that solely redirects to a location of choice using the username field like so:

def profile(request):
    name=request.user.username
    return redirect('-----choose where-----' + name + '/')

Then create a view that captures it in one of your apps, for example:

def profile(request, name):
    user = get_object_or_404(User, username=name)
    return render(request, 'myproject/user.html', {'profile': user})

Where the urlpatterns capture would look like this:

url(r'^(?P<name>.+)/$', views.profile, name='user')

Works well for me.

Checking to see if a DateTime variable has had a value assigned

If you don't want to have to worry about Null value issues like checking for null every time you use it or wrapping it up in some logic, and you also don't want to have to worry about offset time issues, then this is how I solved the problem:

startDate = startDate <= DateTime.MinValue.AddSeconds(1) ? keepIt : resetIt

I just check that the defaulted value is less than a day after the beginning of time. Works like a charm.

Edit 2021: If you need to check milliseconds of the beginning of time then just add ticks instead, but also maybe carbon dating is what you are really looking for. Still not sure carbon dating would even be as accurate as you need if you need accuracy to the tick.

How do you render primitives as wireframes in OpenGL?

If you are using the fixed pipeline (OpenGL < 3.3) or the compatibility profile you can use

//Turn on wireframe mode
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

//Draw the scene with polygons as lines (wireframe)
renderScene();

//Turn off wireframe mode
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

In this case you can change the line width by calling glLineWidth

Otherwise you need to change the polygon mode inside your draw method (glDrawElements, glDrawArrays, etc) and you may end up with some rough results because your vertex data is for triangles and you are outputting lines. For best results consider using a Geometry shader or creating new data for the wireframe.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Look at the exception:

No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency

This means that there's no bean available to fulfill that dependency. Yes, you have an implementation of the interface, but you haven't created a bean for that implementation. You have two options:

  • Annotate UserDaoImpl with @Component or @Repository, and let the component scan do the work for you, exactly as you have done with UserService.
  • Add the bean manually to your xml file, the same you have done with UserBoImpl.

Remember that if you create the bean explicitly you need to put the definition before the component scan. In this case the order is important.

Show Curl POST Request Headers? Is there a way to do this?

Here is all you need:

curl_setopt($curlHandle, CURLINFO_HEADER_OUT, true); // enable tracking
... // do curl request    
$headerSent = curl_getinfo($curlHandle, CURLINFO_HEADER_OUT ); // request headers

How to open SharePoint files in Chrome/Firefox

Installing the Chrome extension IE Tab did the job for me.

It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.

You can install IETab for FireFox too.

How to remove from a map while iterating it?

Pretty sad, eh? The way I usually do it is build up a container of iterators instead of deleting during traversal. Then loop through the container and use map.erase()

std::map<K,V> map;
std::list< std::map<K,V>::iterator > iteratorList;

for(auto i : map ){
    if ( needs_removing(i)){
        iteratorList.push_back(i);
    }
}
for(auto i : iteratorList){
    map.erase(*i)
}

Change the Right Margin of a View Programmatically?

Update: Android KTX

The Core KTX module provides extensions for common libraries that are part of the Android framework, androidx.core.view among them.

dependencies {
    implementation "androidx.core:core-ktx:{latest-version}"
}

The following extension functions are handy to deal with margins:

Note: they are all extension functions of MarginLayoutParams, so first you need to get and cast the layoutParams of your view:

val params = (myView.layoutParams as ViewGroup.MarginLayoutParams)

Sets the margins of all axes in the ViewGroup's MarginLayoutParams. (The dimension has to be provided in pixels, see the last section if you want to work with dp)

inline fun MarginLayoutParams.setMargins(@Px size: Int): Unit
// E.g. 16px margins
params.setMargins(16)

Updates the margins in the ViewGroup's ViewGroup.MarginLayoutParams.

inline fun MarginLayoutParams.updateMargins(
    @Px left: Int = leftMargin, 
    @Px top: Int = topMargin, 
    @Px right: Int = rightMargin, 
    @Px bottom: Int = bottomMargin
): Unit
// Example: 8px left margin 
params.updateMargins(left = 8)

Updates the relative margins in the ViewGroup's MarginLayoutParams (start/end instead of left/right).

inline fun MarginLayoutParams.updateMarginsRelative(
    @Px start: Int = marginStart, 
    @Px top: Int = topMargin, 
    @Px end: Int = marginEnd, 
    @Px bottom: Int = bottomMargin
): Unit
// E.g: 8px start margin 
params.updateMargins(start = 8)

The following extension properties are handy to get the current margins:

inline val View.marginBottom: Int
inline val View.marginEnd: Int
inline val View.marginLeft: Int
inline val View.marginRight: Int
inline val View.marginStart: Int
inline val View.marginTop: Int
// E.g: get margin bottom
val bottomPx = myView1.marginBottom
  • Using dp instead of px:

If you want to work with dp (density-independent pixels) instead of px, you will need to convert them first. You can easily do that with the following extension property:

val Int.px: Int
    get() = (this * Resources.getSystem().displayMetrics.density).toInt()

Then you can call the previous extension functions like:

params.updateMargins(start = 16.px, end = 16.px, top = 8.px, bottom = 8.px)
val bottomDp = myView1.marginBottom.dp

Old answer:

In Kotlin you can declare an extension function like:

fun View.setMargins(
    leftMarginDp: Int? = null,
    topMarginDp: Int? = null,
    rightMarginDp: Int? = null,
    bottomMarginDp: Int? = null
) {
    if (layoutParams is ViewGroup.MarginLayoutParams) {
        val params = layoutParams as ViewGroup.MarginLayoutParams
        leftMarginDp?.run { params.leftMargin = this.dpToPx(context) }
        topMarginDp?.run { params.topMargin = this.dpToPx(context) }
        rightMarginDp?.run { params.rightMargin = this.dpToPx(context) }
        bottomMarginDp?.run { params.bottomMargin = this.dpToPx(context) }
        requestLayout()
    }
}

fun Int.dpToPx(context: Context): Int {
    val metrics = context.resources.displayMetrics
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), metrics).toInt()
}

Then you can call it like:

myView1.setMargins(8, 16, 34, 42)

Or:

myView2.setMargins(topMarginDp = 8) 

Scroll back to the top of scrollable div

scrollTo

window.scrollTo(0, 0);

is the ultimate solution for scrolling the windows to the top - the best part is that it does not require any id selector and even if we use the IFRAME structure it will work extremely well.

The scrollTo() method scrolls the document to the specified coordinates.
window.scrollTo(xpos, ypos);
xpos Number Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels
ypos Number Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

jQuery

Another option to do the same is using jQuery and it will give a smoother look for the same

$('html,body').animate({scrollTop: 0}, 100);

where 0 after the scrollTop specifies the vertical scrollbar position in the pixel and second parameter is an optional parameter which shows the time in microseconds to complete the task.

Make copy of an array

All solution that call length from array, add your code redundant null checkersconsider example:

int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();

//What if array a comes as local parameter? You need to use null check:

public void someMethod(int[] a) {
    if (a!=null) {
        int[] b = Arrays.copyOf(a, a.length);
        int[] c = a.clone();
    }
}

I recommend you not inventing the wheel and use utility class where all necessary checks have already performed. Consider ArrayUtils from apache commons. You code become shorter:

public void someMethod(int[] a) {
    int[] b = ArrayUtils.clone(a);
}

Apache commons you can find there

Group by with multiple columns using lambda

if your table is like this

rowId     col1    col2    col3    col4
 1          a       e       12       2
 2          b       f       42       5
 3          a       e       32       2
 4          b       f       44       5


var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 =  r.Field<int>("col1"), pp2 = r.Field<int>("col2")});

How do I get first element rather than using [0] in jQuery?

With the assumption that there's only one element:

 $("#grid_GridHeader")[0]
 $("#grid_GridHeader").get(0)
 $("#grid_GridHeader").get()

...are all equivalent, returning the single underlying element.

From the jQuery source code, you can see that get(0), under the covers, essentially does the same thing as the [0] approach:

 // Return just the object
 ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );

How to identify all stored procedures referring a particular table

A non-query way would be to use the Sql Server Management Studio.

Locate the table, right click and choose "View dependencies".

EDIT

But, as the commenters said, it is not very reliable.

npm install -g less does not work: EACCES: permission denied

Using sudo is not recommended. It may give you permission issue later. While the above works, I am not a fan of changing folders owned by root to be writable for users, although it may only be an issue with multiple users. To work around that, you could use a group, with 'npm users' but that is also more administrative overhead. See here for the options to deal with permissions from the documentation: https://docs.npmjs.com/getting-started/fixing-npm-permissions

I would go for option 2:

To minimize the chance of permissions errors, you can configure npm to use a different directory. In this example, it will be a hidden directory on your home folder.

Make a directory for global installations:

 mkdir ~/.npm-global

Configure npm to use the new directory path:

 npm config set prefix '~/.npm-global'

Open or create a ~/.profile file and add this line:

 export PATH=~/.npm-global/bin:$PATH

Back on the command line, update your system variables:

 source ~/.profile

Test: Download a package globally without using sudo.

npm install -g jshint

If still show permission error run (mac os):

sudo chown -R $USER ~/.npm-global   

This works with the default ubuntu install of:

sudo apt-get install nodejs npm

I recommend nvm if you want more flexibility in managing versions: https://github.com/creationix/nvm

On MacOS use brew, it should work without sudo out of the box if you're on a recent npm version. Enjoy :)

Connect to Active Directory via LDAP

DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com

You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).

Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");

And you're done.

You can also specify a user and a password used to connect:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");

Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.

The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";

This would match the following AD hierarchy:

  • com
    • example
      • Users
        • All Users
          • Specific Users

Simply write the hierarchy from deepest to highest.

Now you can do plenty of things

For example search a user by account name and get the user's surname:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};

searcher.PropertiesToLoad.Add("sn");

var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case
}

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();
}

Send JSON via POST in C# and Receive the JSON returned?

Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:

// ...

string payload = JsonConvert.SerializeObject(new
{
    agent = new
    {
        name    = "Agent Name",
        version = 1,
    },

    username = "username",
    password = "password",
    token    = "xxxxx",
});

var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(uri, content);

// ...

Upload file to SFTP using PowerShell

There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.

Here is an example using Posh-SSH:

# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)

# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'

# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'

# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH

# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential

# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath

#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }

# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath

Some additional notes:

  • You'll have to download the Posh-SSH module which you can install to your user module directory (e.g. C:\Users\jon_dechiro\Documents\WindowsPowerShell\Modules) and just load using the name or put it anywhere and load it like I have in the code above.
  • If having the credentials in the script is not acceptable you'll have to use a credential file. If you need help with that I can update with some details or point you to some links.
  • Change the paths, IPs, etc. as needed.

That should give you a decent starting point.

How can I calculate the difference between two ArrayLists?

Hi use this class this will compare both lists and shows exactly the mismatch b/w both lists.

import java.util.ArrayList;
import java.util.List;


public class ListCompare {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List<String> dbVinList;
        dbVinList = new ArrayList<String>();
        List<String> ediVinList;
        ediVinList = new ArrayList<String>();           

        dbVinList.add("A");
        dbVinList.add("B");
        dbVinList.add("C");
        dbVinList.add("D");

        ediVinList.add("A");
        ediVinList.add("C");
        ediVinList.add("E");
        ediVinList.add("F");
        /*ediVinList.add("G");
        ediVinList.add("H");
        ediVinList.add("I");
        ediVinList.add("J");*/  

        List<String> dbVinListClone = dbVinList;
        List<String> ediVinListClone = ediVinList;

        boolean flag;
        String mismatchVins = null;
        if(dbVinListClone.containsAll(ediVinListClone)){
            flag = dbVinListClone.removeAll(ediVinListClone);   
            if(flag){
                mismatchVins = getMismatchVins(dbVinListClone);
            }
        }else{
            flag = ediVinListClone.removeAll(dbVinListClone);
            if(flag){
                mismatchVins = getMismatchVins(ediVinListClone);
            }
        }
        if(mismatchVins != null){
            System.out.println("mismatch vins : "+mismatchVins);
        }       

    }

    private static String getMismatchVins(List<String> mismatchList){
        StringBuilder mismatchVins = new StringBuilder();
        int i = 0;
        for(String mismatch : mismatchList){
            i++;
            if(i < mismatchList.size() && i!=5){
                mismatchVins.append(mismatch).append(",");  
            }else{
                mismatchVins.append(mismatch);
            }
            if(i==5){               
                break;
            }
        }
        String mismatch1;
        if(mismatchVins.length() > 100){
            mismatch1 = mismatchVins.substring(0, 99);
        }else{
            mismatch1 = mismatchVins.toString();
        }       
        return mismatch1;
    }

}

Types in Objective-C on iOS

This is a good overview:

http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html

or run this code:

32 bit process:

  NSLog(@"Primitive sizes:");
  NSLog(@"The size of a char is: %d.", sizeof(char));
  NSLog(@"The size of short is: %d.", sizeof(short));
  NSLog(@"The size of int is: %d.", sizeof(int));
  NSLog(@"The size of long is: %d.", sizeof(long));
  NSLog(@"The size of long long is: %d.", sizeof(long long));
  NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
  NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
  NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
  NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
  NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
  NSLog(@"The size of a float is: %d.", sizeof(float));
  NSLog(@"The size of a double is %d.", sizeof(double));

  NSLog(@"Ranges:");
  NSLog(@"CHAR_MIN:   %c",   CHAR_MIN);
  NSLog(@"CHAR_MAX:   %c",   CHAR_MAX);
  NSLog(@"SHRT_MIN:   %hi",  SHRT_MIN);    // signed short int
  NSLog(@"SHRT_MAX:   %hi",  SHRT_MAX);
  NSLog(@"INT_MIN:    %i",   INT_MIN);
  NSLog(@"INT_MAX:    %i",   INT_MAX);
  NSLog(@"LONG_MIN:   %li",  LONG_MIN);    // signed long int
  NSLog(@"LONG_MAX:   %li",  LONG_MAX);
  NSLog(@"ULONG_MAX:  %lu",  ULONG_MAX);   // unsigned long int
  NSLog(@"LLONG_MIN:  %lli", LLONG_MIN);   // signed long long int
  NSLog(@"LLONG_MAX:  %lli", LLONG_MAX);
  NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX);  // unsigned long long int

When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:

Primitive sizes:
The size of a char is: 1.                
The size of short is: 2.                 
The size of int is: 4.                   
The size of long is: 4.                  
The size of long long is: 8.             
The size of a unsigned char is: 1.       
The size of unsigned short is: 2.        
The size of unsigned int is: 4.          
The size of unsigned long is: 4.         
The size of unsigned long long is: 8.    
The size of a float is: 4.               
The size of a double is 8.               
Ranges:                                  
CHAR_MIN:   -128                         
CHAR_MAX:   127                          
SHRT_MIN:   -32768                       
SHRT_MAX:   32767                        
INT_MIN:    -2147483648                  
INT_MAX:    2147483647                   
LONG_MIN:   -2147483648                  
LONG_MAX:   2147483647                   
ULONG_MAX:  4294967295                   
LLONG_MIN:  -9223372036854775808         
LLONG_MAX:  9223372036854775807          
ULLONG_MAX: 18446744073709551615 

64 bit process:

The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 8.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 8.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

Uri not Absolute exception getting while calling Restful Webservice

An absolute URI specifies a scheme; a URI that is not absolute is said to be relative.

http://docs.oracle.com/javase/8/docs/api/java/net/URI.html

So, perhaps your URLEncoder isn't working as you're expecting (the https bit)?

    URLEncoder.encode(uri) 

Finding local IP addresses using Python's stdlib

import socket
socket.gethostbyname(socket.getfqdn())

Getting key with maximum value in dictionary?

With collections.Counter you could do

>>> import collections
>>> stats = {'a':1000, 'b':3000, 'c': 100}
>>> stats = collections.Counter(stats)
>>> stats.most_common(1)
[('b', 3000)]

If appropriate, you could simply start with an empty collections.Counter and add to it

>>> stats = collections.Counter()
>>> stats['a'] += 1
:
etc. 

stdlib and colored output in C

You can output special color control codes to get colored terminal output, here's a good resource on how to print colors.

For example:

printf("\033[22;34mHello, world!\033[0m");  // shows a blue hello world

EDIT: My original one used prompt color codes, which doesn't work :( This one does (I tested it).

Detect if user is scrolling

You just said javascript in your tags, so @Wampie Driessen post could helps you.

I want also to contribute, so you can use the following when using jQuery if you need it.

 //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.wheelDelta< 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

Another example:

$(function(){
    var _top = $(window).scrollTop();
    var _direction;
    $(window).scroll(function(){
        var _cur_top = $(window).scrollTop();
        if(_top < _cur_top)
        {
            _direction = 'down';
        }
        else
        {
            _direction = 'up';
        }
        _top = _cur_top;
        console.log(_direction);
    });
});?

How can I parse a JSON file with PHP?

I can't believe so many people are posting answers without reading the JSON properly.

If you foreach iterate $json_a alone, you have an object of objects. Even if you pass in true as the second parameter, you have a two-dimensional array. If you're looping through the first dimension you can't just echo the second dimension like that. So this is wrong:

foreach ($json_a as $k => $v) {
   echo $k, ' : ', $v;
}

To echo the statuses of each person, try this:

<?php

$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
    // deal with error...
}

$json_a = json_decode($string, true);
if ($json_a === null) {
    // deal with error...
}

foreach ($json_a as $person_name => $person_a) {
    echo $person_a['status'];
}

?>

How do I kill this tomcat process in Terminal?

As others already noted, you have seen the grep process. If you want to restrict the output to tomcat itself, you have two alternatives

  • wrap the first searched character in a character class

    ps -ef | grep '[t]omcat'
    

    This searches for tomcat too, but misses the grep [t]omcat entry, because it isn't matched by [t]omcat.

  • use a custom output format with ps

    ps -e -o pid,comm | grep tomcat
    

    This shows only the pid and the name of the process without the process arguments. So, grep is listed as grep and not as grep tomcat.

What is the best way to prevent session hijacking?

To reduce the risk you can also associate the originating IP with the session. That way an attacker has to be within the same private network to be able to use the session.

Checking referer headers can also be an option but those are more easily spoofed.

How do I generate a random integer between min and max in Java?

As the solutions above do not consider the possible overflow of doing max-min when min is negative, here another solution (similar to the one of kerouac)

public static int getRandom(int min, int max) {
    if (min > max) {
        throw new IllegalArgumentException("Min " + min + " greater than max " + max);
    }      
    return (int) ( (long) min + Math.random() * ((long)max - min + 1));
}

this works even if you call it with:

getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE) 

catching stdout in realtime from subprocess

for line in p.stdout:
  ...

always blocks until the next line-feed.

For "real-time" behaviour you have to do something like this:

while True:
  inchar = p.stdout.read(1)
  if inchar: #neither empty string nor None
    print(str(inchar), end='') #or end=None to flush immediately
  else:
    print('') #flush for implicit line-buffering
    break

The while-loop is left when the child process closes its stdout or exits. read()/read(-1) would block until the child process closed its stdout or exited.

CSS3 background image transition

I've figured out a solution that worked for me...

If you have a list item (or div) containing only the link, and let's say this is for social links on your page to facebook, twitter, ect. and you're using a sprite image you can do this:

<li id="facebook"><a href="facebook.com"></a></li>

Make the "li"s background your button image

#facebook {
   width:30px;
   height:30px;
   background:url(images/social) no-repeat 0px 0px;
}

Then make the link's background image the hover state of the button. Also add the opacity attribute to this and set it to 0.

#facebook a {
   display:inline-block;
   background:url(images/social) no-repeat 0px -30px;
   opacity:0;
}

Now all you need is "opacity" under "a:hover" and set this to 1.

#facebook a:hover {
   opacity:1;
}

Add the opacity transition attributes for each browser to "a" and "a:hover" so the the final css will look something like this:

#facebook {
   width:30px;
   height:30px;
   background:url(images/social) no-repeat 0px 0px;
}
#facebook a {
   display:inline-block;
   background:url(images/social) no-repeat 0px -30px;
   opacity:0;
   -webkit-transition: opacity 200ms linear;
   -moz-transition: opacity 200ms linear;
   -o-transition: opacity 200ms linear;
   -ms-transition: opacity 200ms linear;
   transition: opacity 200ms linear;
}
#facebook a:hover {
   opacity:1;
   -webkit-transition: opacity 200ms linear;
   -moz-transition: opacity 200ms linear;
   -o-transition: opacity 200ms linear;
   -ms-transition: opacity 200ms linear;
   transition: opacity 200ms linear;
}

If I explained it correctly that should let you have a fading background image button, hope it helps at least!

Hive: Convert String to Integer

It would return NULL but if taken as BIGINT would show the number

TypeError: string indices must be integers, not str // working with dict

I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:

from itertools import chain

def involved(courses, person):
    courses_info = chain.from_iterable(x.values() for x in courses.values())
    return filter(lambda x: x['teacher'] == person, courses_info)

print involved(courses, 'Dave')

The first thing I do is getting the list of the courses and then filter by teacher's name.

What does 'URI has an authority component' mean?

The solution was simply that the URI was malformed (because the location of my project was over a "\\" UNC path). This issue was fixed when I used a local workspace.

How to change the floating label color of TextInputLayout

Now, simply using colorAccent and colorPrimary will work perfectly.

How do I hide the bullets on my list for the sidebar?

its on you ul in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252

add this to your css

ul{
     list-style:none;
}

How can I dynamically add items to a Java array?

Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.

A bit similar to the PHP behaviour is this:

int[] addElement(int[] org, int added) {
    int[] result = Arrays.copyOf(org, org.length +1);
    result[org.length] = added;
    return result;
}

Then you can write:

x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);

System.out.println(Arrays.toString(x));

But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).

The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.

If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)

Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.

Find index of a value in an array

Try this...

var key = words.Where(x => x.IsKey == true);

Counting number of words in a file

So easy we can get the String from files by method: getText();

public class Main {

    static int countOfWords(String str) {
        if (str.equals("") || str == null) {
            return 0;
        }else{
            int numberWords = 0;
            for (char c : str.toCharArray()) {
                if (c == ' ') {
                    numberWords++;
                }
            }

            return ++numberWordss;
        }
    }
}

How to remove provisioning profiles from Xcode

I was able to delete my Provisioning Profile from XCode 6 by using the Member Center online. I then just did a refresh/Sync in XCode 6 and it disappeared.

In the Apple Developer Member Center I had to do two things to make it happen:

  • Under under Identifiers -> AP IDs I had to first delete the old AP ID still using the old Provisioning Profile that I wanted to delete.
    • This step was crucial for me. If I just deleted the Provisioning Profile alone without the APP ID still using it, the Profile re-appeared in XCode after a Sync.
  • Under Provisioning Profiles I then deleted the unwanted provisioning profile.

In XCode:

  • Under Preferences > Accounts, clicking on my apple ID and View Details... I Sync'd my online provisioning profiles.
  • The Provisioning Profile removed itself from the list.

How to resolve git status "Unmerged paths:"?

Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:

git reset

This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run

git add -p

which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached), you can commit, and then

git reset --hard

to destroy all the unwanted changes in your working directory.

How can I specify a display?

Try

export DISPLAY=localhost:0.0

Spring Resttemplate exception handling

You should catch a HttpStatusCodeException exception:

try {
    restTemplate.exchange(...);
} catch (HttpStatusCodeException exception) {
    int statusCode = exception.getStatusCode().value();
    ...
}

Center text output from Graphics.DrawString()

To align a text use the following:

StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;
e.Graphics.DrawString("My String", this.Font, Brushes.Black, ClientRectangle, sf);

Please note that the text here is aligned in the given bounds. In this sample this is the ClientRectangle.

How to pass command line arguments to a rake task

I use a regular ruby argument in the rake file:

DB = ARGV[1]

then I stub out the rake tasks at the bottom of the file (since rake will look for a task based on that argument name).

task :database_name1
task :database_name2

command line:

rake mytask db_name

this feels cleaner to me than the var=foo ENV var and the task args[blah, blah2] solutions.
the stub is a little jenky, but not too bad if you just have a few environments that are a one-time setup

UIImage: Resize, then Crop

Swift version:

    static func imageWithImage(image:UIImage, newSize:CGSize) ->UIImage {
    UIGraphicsBeginImageContextWithOptions(newSize, true, UIScreen.mainScreen().scale);
    image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))

    let newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    return newImage
}

How to drop a database with Mongoose?

beforeEach((done) => {
      mongoose.connection.dropCollection('products',(error ,result) => {
      if (error) {
        console.log('Products Collection is not dropped')
      } else {
        console.log(result)
      }
    done()
    })
  })

Import data into Google Colaboratory

On the left bar of any colaboratory there is a section called "Files". Upload your files there and use this path

"/content/YourFileName.extension"

ex: pd.read_csv('/content/Forbes2015.csv');

Are there constants in JavaScript?

Forget IE and use the const keyword.

Check if two lists are equal

Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement), 
                         SecondList.OrderBy(sElement => sElement))

convert NSDictionary to NSString

Above Solutions will only convert dictionary into string but you can't convert back that string to dictionary. For that it is the better way.

Convert to String

NSError * err;
NSData * jsonData = [NSJSONSerialization  dataWithJSONObject:yourDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData   encoding:NSUTF8StringEncoding];
NSLog(@"%@",myString);

Convert Back to Dictionary

NSError * err;
NSData *data =[myString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * response;
if(data!=nil){
 response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
}

How do you loop through each line in a text file using a windows batch file?

Modded examples here to list our Rails apps on Heroku - thanks!

cmd /C "heroku list > heroku_apps.txt"
find /v "=" heroku_apps.txt | find /v ".TXT" | findstr /r /v /c:"^$" > heroku_apps_list.txt
for /F "tokens=1" %%i in (heroku_apps_list.txt) do heroku run bundle show rails --app %%i

Full code here.

Comparing two NumPy arrays for equality, element-wise

(A==B).all()

test if all values of array (A==B) are True.

Note: maybe you also want to test A and B shape, such as A.shape == B.shape

Special cases and alternatives (from dbaupp's answer and yoavram's comment)

It should be noted that:

  • this solution can have a strange behavior in a particular case: if either A or B is empty and the other one contains a single element, then it return True. For some reason, the comparison A==B returns an empty array, for which the all operator returns True.
  • Another risk is if A and B don't have the same shape and aren't broadcastable, then this approach will raise an error.

In conclusion, if you have a doubt about A and B shape or simply want to be safe: use one of the specialized functions:

np.array_equal(A,B)  # test if same shape, same elements values
np.array_equiv(A,B)  # test if broadcastable shape, same elements values
np.allclose(A,B,...) # test if same shape, elements have close enough values

Get changes from master into branch in Git

You should be able to just git merge origin/master when you are on your aq branch.

git checkout aq
git merge origin/master

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!

Enter image description here

(Excel) Conditional Formatting based on Adjacent Cell Value

I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:

Under Conditional Formatting > Manage Rules:

  1. Make a new rule with "Use a formula to determine which cells to format"
  2. Make your rule, but put a dollar sign only in front of the letter: $A2<$B2
  3. Under "Applies to", Manually select the second column (It would not work for me if I changed the value in the box, it just kept snapping back to what was already there), so it looks like $B$2:$B$100 (assuming you have 100 rows)

This worked for me in Excel 2016.

Exception.Message vs Exception.ToString()

Depends on the information you need. For debugging the stack trace & inner exception are useful:

    string message =
        "Exception type " + ex.GetType() + Environment.NewLine +
        "Exception message: " + ex.Message + Environment.NewLine +
        "Stack trace: " + ex.StackTrace + Environment.NewLine;
    if (ex.InnerException != null)
    {
        message += "---BEGIN InnerException--- " + Environment.NewLine +
                   "Exception type " + ex.InnerException.GetType() + Environment.NewLine +
                   "Exception message: " + ex.InnerException.Message + Environment.NewLine +
                   "Stack trace: " + ex.InnerException.StackTrace + Environment.NewLine +
                   "---END Inner Exception";
    }

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

What's the best practice using a settings file in Python?

The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.

To use the yaml module is extremely simple:

import yaml
config = yaml.safe_load(open("path/to/config.yml"))

How to plot a function curve in R

plot has a plot.function method

plot(eq, 1, 1000)

Or

curve(eq, 1, 1000)

How to force Sequential Javascript Execution?

Put your code in a string, iterate, eval, setTimeout and recursion to continue with the remaining lines. No doubt I'll refine this or just throw it out if it doesn't hit the mark. My intention is to use it to simulate really, really basic user testing.

The recursion and setTimeout make it sequential.

Thoughts?

var line_pos = 0;
var string =`
    console.log('123');
    console.log('line pos is '+ line_pos);
SLEEP
    console.log('waited');
    console.log('line pos is '+ line_pos);
SLEEP
SLEEP
    console.log('Did i finish?');
`;

var lines = string.split("\n");
var r = function(line_pos){
    for (i = p; i < lines.length; i++) { 
        if(lines[i] == 'SLEEP'){
            setTimeout(function(){r(line_pos+1)},1500);
            return;
        }
        eval (lines[line_pos]);
    }
    console.log('COMPLETED READING LINES');
    return;
}
console.log('STARTED READING LINES');
r.call(this,line_pos);

OUTPUT

STARTED READING LINES
123
124
1 p is 0
undefined
waited
p is 5
125
Did i finish?
COMPLETED READING LINES

Remove unwanted parts from strings in a column

i'd use the pandas replace function, very simple and powerful as you can use regex. Below i'm using the regex \D to remove any non-digit characters but obviously you could get quite creative with regex.

data['result'].replace(regex=True,inplace=True,to_replace=r'\D',value=r'')

Disable XML validation in Eclipse

Window > Preferences > Validation > uncheck XML Validator Manual and Build enter image description here

How to convert the time from AM/PM to 24 hour format in PHP?

$s = '07:05:45PM';
$tarr = explode(':', $s);
if(strpos( $s, 'AM') === false && $tarr[0] !== '12'){
    $tarr[0] = $tarr[0] + 12;
}elseif(strpos( $s, 'PM') === false && $tarr[0] == '12'){
    $tarr[0] = '00';
}
echo preg_replace("/[^0-9 :]/", '', implode(':', $tarr));

Timing a command's execution in PowerShell

You can also get the last command from history and subtract its EndExecutionTime from its StartExecutionTime.

.\do_something.ps1  
$command = Get-History -Count 1  
$command.EndExecutionTime - $command.StartExecutionTime

Check if a key is down?

This works in Firefox and Chrome.

I had a need to open a special html file locally (by pressing Enter when the file is selected in the file explorer in Windows), either just for viewing the file or for editing it in a special online editor.

So I wanted to distinguish between these two options by holding down the Ctrl-key or not, while pressing Enter.

As you all have understood from all the answers here, this seems to be not really possible, but here is a way that mimics this behaviour in a way that was acceptable for me.

The way this works is like this:

If you hold down the Ctrl-key when opening the file then a keydown event will never fire in the javascript code. But a keyup event will fire (when you finally release the Ctrl-key). The code captures that.

The code also turns off keyevents (both keyup and keydown) as soon as one of them occurs. So if you press the Ctrl-key after the file has opened, nothing will happen.

window.onkeyup = up;
window.onkeydown = down;
function up(e) {
  if (e.key === 'F5') return; // if you want this to work also on reload with F5.

  window.onkeyup = null;
  window.onkeyup = null;
  if (e.key === 'Control') {
    alert('Control key was released. You must have held it down while opening the file, so we will now load the file into the editor.');
  }         
}
function down() {
  window.onkeyup = null;
  window.onkeyup = null;
}

Remove an array element and shift the remaining ones

If you are most concerned about code size and/or performance (also for WCET analysis, if you need one), I think this is probably going to be one of the more transparent solutions (for finding and removing elements):

unsigned int l=0, removed=0;

for( unsigned int i=0; i<count; i++ ) {
    if( array[i] != to_remove )
        array[l++] = array[i];
    else
        removed++;
}

count -= removed;

TypeError: 'float' object not iterable

for i in count: means for i in 7:, which won't work. The bit after the in should be of an iterable type, not a number. Try this:

for i in range(count):

"replace" function examples

If you look at the function (by typing it's name at the console) you will see that it is just a simple functionalized version of the [<- function which is described at ?"[". [ is a rather basic function to R so you would be well-advised to look at that page for further details. Especially important is learning that the index argument (the second argument in replace can be logical, numeric or character classed values. Recycling will occur when there are differing lengths of the second and third arguments:

You should "read" the function call as" "within the first argument, use the second argument as an index for placing the values of the third argument into the first":

> replace( 1:20, 10:15, 1:2)
 [1]  1  2  3  4  5  6  7  8  9  1  2  1  2  1  2 16 17 18 19 20

Character indexing for a named vector:

> replace(c(a=1, b=2, c=3, d=4), "b", 10)
 a  b  c  d 
 1 10  3  4 

Logical indexing:

> replace(x <- c(a=1, b=2, c=3, d=4), x>2, 10)
 a  b  c  d 
 1  2 10 10 

How to use a filter in a controller?

Answer provided by @Prashanth is correct, but there is even easier way of doing the same. Basically instead of injecting the $filter dependency and using awkward syntax of invoking it ($filter('filtername')(arg1,arg2);) one can inject dependency being: filter name plus the Filter suffix.

Taking example from the question one could write:

function myCtrl($scope, filter1Filter) { 
  filter1Filter(input, arg1);
}

It should be noted that you must append Filter to the filter name, no matter what naming convention you're using: foo is referenced by calling fooFilter
fooFilter is referenced by calling fooFilterFilter

How to import multiple .csv files at once?

Something like the following should result in each data frame as a separate element in a single list:

temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.delim)

This assumes that you have those CSVs in a single directory--your current working directory--and that all of them have the lower-case extension .csv.

If you then want to combine those data frames into a single data frame, see the solutions in other answers using things like do.call(rbind,...), dplyr::bind_rows() or data.table::rbindlist().

If you really want each data frame in a separate object, even though that's often inadvisable, you could do the following with assign:

temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))

Or, without assign, and to demonstrate (1) how the file name can be cleaned up and (2) show how to use list2env, you can try the following:

temp = list.files(pattern="*.csv")
list2env(
  lapply(setNames(temp, make.names(gsub("*.csv$", "", temp))), 
         read.csv), envir = .GlobalEnv)

But again, it's often better to leave them in a single list.

Convert string to boolean in C#

I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands

OP, you can convert a string to type Boolean by using any of the methods stated below:

 string sample = "True";
 bool myBool = bool.Parse(sample);

 ///or

 bool myBool = Convert.ToBoolean(sample);

bool.Parse expects one parameter which in this case is sample, .ToBoolean also expects one parameter.

You can use TryParse which is the same as Parse but it doesn't throw any exception :)

  string sample = "false";
  Boolean myBool;

  if (Boolean.TryParse(sample , out myBool))
  {
  }

Please note that you cannot convert any type of string to type Boolean because the value of a Boolean can only be True or False

Hope you understand :)

how to query child objects in mongodb

If it is exactly null (as opposed to not set):

db.states.find({"cities.name": null})

(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).

If it's the case that the property is not set:

db.states.find({"cities.name": {"$exists": false}})

I've tested the above with a collection created with these two inserts:

db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})

The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or query:

db.states.find({"$or": [
  {"cities.name": null}, 
  {"cities.name": {"$exists": false}}
]})

How to add a progress bar to a shell script?

It may be achieved in a pretty simple way:

  • iterate from 0 to 100 with for loop
  • sleep every step for 25ms (0.25 second)
  • append to the $bar variable another = sign to make the progress bar wider
  • echo progress bar and percentage (\r cleans line and returns to the beginning of the line; -ne makes echo doesn't add newline at the end and parses \r special character)
function progress {
    bar=''
    for (( x=0; x <= 100; x++ )); do
        sleep 0.25
        bar="${bar}="
        echo -ne "$bar ${x}%\r"
    done
    echo -e "\n"
}
$ progress
> ========== 10% # here: after 2.5 seconds
$ progress
> ============================== 30% # here: after 7.5 seconds

COLORED PROGRESS BAR

function progress {
    bar=''
    for (( x=0; x <= 100; x++ )); do
        sleep 0.05
        bar="${bar} "

        echo -ne "\r"
        echo -ne "\e[43m$bar\e[0m"

        local left="$(( 100 - $x ))"
        printf " %${left}s"
        echo -n "${x}%"
    done
    echo -e "\n"
}

To make a progress bar colorful, you can use formatting escape sequence - here the progress bar is yellow: \e[43m, then we reset custom settings with \e[0m, otherwise it would affect further input even when the progress bar is done.

custom progress bar

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

Clicking URLs opens default browser

The method boolean shouldOverrideUrlLoading(WebView view, String url) was deprecated in API 24. If you are supporting new devices you should use boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request).

You can use both by doing something like this:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    newsItem.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return true;
        }
    });
} else {
    newsItem.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
}

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Best way to log POST data in Apache?

I would do it in the application, actually. It's still configurable at runtime, depending on your logger system, of course. For example, if you use Apache Log (log4j/cxx) you could configure a dedicated logger for such URLs and then configure it at runtime from an XML file.

Import pfx file into particular certificate store from command line

Check these links: http://www.orcsweb.com/blog/james/powershell-ing-on-windows-server-how-to-import-certificates-using-powershell/

Import-Certificate: http://poshcode.org/1937

You can do something like:

dir -Path C:\Certs -Filter *.cer | Import-Certificate -CertFile $_ -StoreNames AuthRoot, Root -LocalMachine -Verbose

PHP reindex array?

array_values does the job :

$myArray  = array_values($myArray);

Also some other php function do not preserve the keys, i.e. reset the index.

How to get RegistrationID using GCM in android

In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.

In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.

How to print strings with line breaks in java

Use String buffer.

  final StringBuffer mText = new StringBuffer("SHOP MA\n"
        + "----------------------------\n"
        + "Pannampitiya\n"
        + "09-10-2012 harsha  no: 001\n"
        + "No  Item  Qty  Price  Amount\n"
        + "1 Bread 1 50.00  50.00\n"
        + "____________________________\n");

Change image onmouseover

I know someone answered this the same way, but I made my own research, and I wrote this before to see that answer. So: I was looking for something simple with inline JavaScript, with just on the img, without "wrapping" it into the a tag (so instead of the document.MyImage, I used this.src)

<img 
onMouseOver="this.src='ico/view.hover.png';" 
onMouseOut="this.src='ico/view.png';" 
src="ico/view.png" alt="hover effect" />

It works on all currently updated browsers; IE 11 (and I also tested it in the Developer Tools of IE from IE5 and above), Chrome, Firefox, Opera, Edge.

How to fix request failed on channel 0

try with option -NT

ssh -NT ...

How do I set browser width and height in Selenium WebDriver?

This works both with headless and non-headless, and will start the window with the specified size instead of setting it after:

from selenium.webdriver import Firefox, FirefoxOptions

opts = FirefoxOptions()
opts.add_argument("--width=2560")
opts.add_argument("--height=1440")

driver = Firefox(options=opts)

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

Use Jackson-annotations.jar will solve the problem, as it worked for me.

Decoding JSON String in Java

This is the best and easiest code:

public class test
{
    public static void main(String str[])
    {
        String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject newJSON = jsonObject.getJSONObject("stat");
        System.out.println(newJSON.toString());
        jsonObject = new JSONObject(newJSON.toString());
        System.out.println(jsonObject.getString("rcv"));
       System.out.println(jsonObject.getJSONArray("argv"));
    }
}

The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.

You can download the zip. And then create a package in your project with org.json as name. and paste all the downloaded codes there, and have fun.

I feel this to be the best and the most easiest JSON Decoding.

Writing a string to a cell in excel

I've had a few cranberry-vodkas tonight so I might be missing something...Is setting the range necessary? Why not use:

Activeworkbook.Sheets("Game").Range("A1").value = "Subtotal"

Does this fail as well?

Looks like you tried something similar:

'Worksheets("Game").Range("A1") = "Asdf"

However, Worksheets is a collection, so you can't reference "Game". I think you need to use the Sheets object instead.

Vue.JS: How to call function after page loaded?

Vue watch() life-cycle hook, can be used

html

<div id="demo">{{ fullName }}</div>

js

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})

Regex to split a CSV

The advantage of using JScript for classic ASP pages is that you can use one of the many, many libraries that have been written for JavaScript.

Like this one: https://github.com/gkindel/CSV-JS. Download it, include it in your ASP page, parse CSV with it.

<%@ language="javascript" %>

<script language="javascript" runat="server" src="scripts/csv.js"></script>
<script language="javascript" runat="server">

var text = '123,2.99,AMO024,Title,"Description, more info",,123987564',
    rows = CSV.parse(line);

    Response.Write(rows[0][4]);
</script>

How to create a oracle sql script spool file

This will spool the output from the anonymous block into a file called output_<YYYYMMDD>.txt located in the root of the local PC C: drive where <YYYYMMDD> is the current date:

SET SERVEROUTPUT ON FORMAT WRAPPED
SET VERIFY OFF

SET FEEDBACK OFF
SET TERMOUT OFF

column date_column new_value today_var
select to_char(sysdate, 'yyyymmdd') date_column
  from dual
/
DBMS_OUTPUT.ENABLE(1000000);

SPOOL C:\output_&today_var..txt

DECLARE
   ab varchar2(10) := 'Raj';
   cd varchar2(10);
   a  number := 10;
   c  number;
   d  number; 
BEGIN
   c := a+10;
   --
   SELECT ab, c 
     INTO cd, d 
     FROM dual;
   --
   DBMS_OUTPUT.put_line('cd: '||cd);
   DBMS_OUTPUT.put_line('d: '||d);
END; 

SPOOL OFF

SET TERMOUT ON
SET FEEDBACK ON
SET VERIFY ON

PROMPT
PROMPT Done, please see file C:\output_&today_var..txt
PROMPT

Hope it helps...

EDIT:

After your comment to output a value for every iteration of a cursor (I realise each value will be the same in this example but you should get the gist of what i'm doing):

BEGIN
   c := a+10;
   --
   FOR i IN 1 .. 10
   LOOP
      c := a+10;
      -- Output the value of C
      DBMS_OUTPUT.put_line('c: '||c);
   END LOOP;
   --
END; 

How do I convert number to string and pass it as argument to Execute Process Task?

Cause of the issue:

Arguments property in Execute Process Task available on the Control Flow tab is expecting a value of data type DT_WSTR and not DT_STR.

SSIS 2008 R2 package illustrating the issue and fix:

Create an SSIS package in Business Intelligence Development Studio (BIDS) 2008 R2 and name it as SO_13177007.dtsx. Create a package variable with the following information.

Name   Scope        Data Type  Value
------ ------------ ---------- -----
IdVar  SO_13177007  Int32      123

Variables pane

Drag and drop an Execute Process Task onto the Control Flow tab and name it as Pass arguments

Control Flow tab

Double-click the Execute Process Task to open the Execute Process Task Editor. Click Expressions page and then click the Ellipsis button against the Expressions property to view the Property Expression Editor.

Execute Process Task Editor

On the Property Expression Editor, select the property Arguments and click the Ellipsis button against the property to open the Expression Builder.

Property Expression Editor

On the Expression Builder, enter the following expression and click Evaluate Expression. This expression tries to convert the integer value in the variable IdVar to string data type.

(DT_STR, 10, 1252) @[User::IdVar]

Expression Builder - DT_STR

Clicking Evaluate Expression will display the following error message because the Arguments property on Execute Process Task expects a value of data type DT_WSTR.

Integer to ANSI string conversion error

To fix the issue, update the expression as shown below to convert the integer value to data type DT_WSTR. Clicking Evaluate Expression will display the value in the Evaluated value text area.

(DT_WSTR, 10) @[User::IdVar]

Expression Builder - DT_WSTR

References:

To understand the differences between the data types DT_STR and DT_WSTR in SSIS, read the documentation Integration Services Data Types on MSDN. Here are the quotes from the documentation about these two string data types.

DT_STR

A null-terminated ANSI/MBCS character string with a maximum length of 8000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)

DT_WSTR

A null-terminated Unicode character string with a maximum length of 4000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Yes, use the commercial but inexpensive SSMS Tools Pack addin which has a nifty "Generate Insert statements from resultsets, tables or database" feature

Difference between an API and SDK

You use an SDK to access functionality of a library, and an API to control it.

\n or \n in php echo not print

Better use PHP_EOL ("End Of Line") instead. It's cross-platform.

E.g.:

$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>' . PHP_EOL;
echo '<p>' . $unit2 . '</p>';

JavaScript string with new line - but not using \n

I don't think you understand how \n works. The resulting string still just contains a byte with value 10. This is represented in javascript source code with \n.

The code snippet you posted doesn't actually work, but if it did, the newline would be equivalent to \n, unless it's a windows-style newline, in which case it would be \r\n. (but even that the replace would still work).

find the array index of an object with a specific key value in underscore

you can use indexOf method from lodash

var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
var index=_.indexOf(tv,data);

How/When does Execute Shell mark a build as failure in Jenkins?

In Jenkins ver. 1.635, it is impossible to show a native environment variable like this:

$BUILD_NUMBER or ${BUILD_NUMBER}

In this case, you have to set it in an other variable.

set BUILDNO = $BUILD_NUMBER
$BUILDNO

Node/Express file upload

I needed to be walked through with a bit more detail than the other answers provided (e.g. how do I write the file to a location I decide at runtime?). Hopefully this is of help to others:  

get connect-busboy:

npm install connect-busboy --save

In your server.js, add these lines

let busboy = require('connect-busboy')

// ... 

app.use(busboy());

// ... 

app.post('/upload', function(req, res) {
    req.pipe(req.busboy);
    req.busboy.on('file', function(fieldname, file, filename) {
        var fstream = fs.createWriteStream('./images/' + filename); 
        file.pipe(fstream);
        fstream.on('close', function () {
            res.send('upload succeeded!');
        });
    });
});

This would seem to omit error handling though... will edit it in if I find it.

How to get std::vector pointer to the raw data?

&something gives you the address of the std::vector object, not the address of the data it holds. &something.begin() gives you the address of the iterator returned by begin() (as the compiler warns, this is not technically allowed because something.begin() is an rvalue expression, so its address cannot be taken).

Assuming the container has at least one element in it, you need to get the address of the initial element of the container, which you can get via

  • &something[0] or &something.front() (the address of the element at index 0), or

  • &*something.begin() (the address of the element pointed to by the iterator returned by begin()).

In C++11, a new member function was added to std::vector: data(). This member function returns the address of the initial element in the container, just like &something.front(). The advantage of this member function is that it is okay to call it even if the container is empty.

Two statements next to curly brace in an equation

Or this:

f(x)=\begin{cases}
0, & -\pi\leqslant x <0\\
\pi, & 0 \leqslant x \leqslant +\pi
\end{cases}

Local Storage vs Cookies

It is also worth mentioning that localStorage cannot be used when users browse in "private" mode in some versions of mobile Safari.

Quoted from MDN (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage):

Note: Starting with iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short. Safari Mobile's Private Browsing mode also prevents writing to localStorage entirely.

Stretch Image to Fit 100% of Div Height and Width

Or you can put in the CSS,

<style>
div#img {
  background-image: url(“file.png");
  color:yellow (this part doesn't matter;
  height:100%;
  width:100%;
}
</style>

Limiting number of displayed results when using ngRepeat

This works better in my case if you have object or multi-dimensional array. It will shows only first items, other will be just ignored in loop.

.filter('limitItems', function () {
  return function (items) {
    var result = {}, i = 1;
    angular.forEach(items, function(value, key) {
      if (i < 5) {
        result[key] = value;
      }
      i = i + 1;
    });
    return result;
  };
});

Change 5 on what you want.

Binary search (bisection) in Python

I needed binary search in python and generic for Django models. In Django models, one model can have foreign key to another model and I wanted to perform some search on the retrieved models objects. I wrote following function you can use this.

def binary_search(values, key, lo=0, hi=None, length=None, cmp=None):
    """
    This is a binary search function which search for given key in values.
    This is very generic since values and key can be of different type.
    If they are of different type then caller must specify `cmp` function to
    perform a comparison between key and values' item.
    :param values:  List of items in which key has to be search
    :param key: search key
    :param lo: start index to begin search
    :param hi: end index where search will be performed
    :param length: length of values
    :param cmp: a comparator function which can be used to compare key and values
    :return: -1 if key is not found else index
    """
    assert type(values[0]) == type(key) or cmp, "can't be compared"
    assert not (hi and length), "`hi`, `length` both can't be specified at the same time"

    lo = lo
    if not lo:
        lo = 0
    if hi:
        hi = hi
    elif length:
        hi = length - 1
    else:
        hi = len(values) - 1

    while lo <= hi:
        mid = lo + (hi - lo) // 2
        if not cmp:
            if values[mid] == key:
                return mid
            if values[mid] < key:
                lo = mid + 1
            else:
                hi = mid - 1
        else:
            val = cmp(values[mid], key)
            # 0 -> a == b
            # > 0 -> a > b
            # < 0 -> a < b
            if val == 0:
                return mid
            if val < 0:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1

CSS hide scroll bar if not needed

You can use overflow:auto;

You can also control the x or y axis individually with the overflow-x and overflow-y properties.

Example:

.content {overflow:auto;}
.content {overflow-y:auto;}
.content {overflow-x:auto;}

GitHub "fatal: remote origin already exists"

If you need to check which remote repos you have connected with your local repos, theres a cmd:

git remote -v

Now if you want to remove the remote repo (say, origin) then what you can do is:

git remote rm origin

ImageView - have height match width?

For people passing by now, in 2017, the new best way to achieve what you want is by using ConstraintLayout like this:

<ImageView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scaleType="centerCrop"
    app:layout_constraintDimensionRatio="1:1" />

And don't forget to add constraints to all of the four directions as needed by your layout.

Build a Responsive UI with ConstraintLayout

Furthermore, by now, PercentRelativeLayout has been deprecated (see Android documentation).

pandas read_csv index_col=None not working with delimiters at the end of each line

Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:

df = pd.read_csv('file.csv', index_col=0)

The above will set the first column as the index (and not add a range index in my "common case").

Update

Given the popularity of this answer, I thought i'd add some context/ a demo:

# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})

In [2]: df
Out[2]:
   A  B
0  1  4
1  2  5
2  3  6

In [3]: df.to_csv('file.csv', index=None)
File[3]:
A  B
1  4
2  5
3  6

Reading without index_col or with None/False will all result in a range index:

In [4]: pd.read_csv('file.csv')
Out[4]:
   A  B
0  1  4
1  2  5
2  3  6

# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
   A  B
0  1  4
1  2  5
2  3  6

In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
   A  B
0  1  4
1  2  5
2  3  6

However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:

In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
   B
A
1  4
2  5
3  6

Laravel Eloquent ORM Transactions

I'm Sure you are not looking for a closure solution, try this for a more compact solution

 try{
    DB::beginTransaction();

    /*
     * Your DB code
     * */

    DB::commit();
}catch(\Exception $e){
    DB::rollback();
}

PHP: How to check if image file exists?

if (file_exists('http://www.mydomain.com/images/'.$filename)) {}

This didn't work for me. The way I did it was using getimagesize.

$src = 'http://www.mydomain.com/images/'.$filename;

if (@getimagesize($src)) {

Note that the '@' will mean that if the image does not exist (in which case the function would usually throw an error: getimagesize(http://www.mydomain.com/images/filename.png) [function.getimagesize]: failed) it will return false.

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

This is a total hack, but here's what I did...

So while playing with setting up a DocumentsProvider, I noticed that the sample code (in getDocIdForFile, around line 450) generates a unique id for a selected document based on the file's (unique) path relative to the specified root you give it (that is, what you set mBaseDir to on line 96).

So the URI ends up looking something like:

content://com.example.provider/document/root:path/to/the/file

As the docs say, it's assuming only a single root (in my case that's Environment.getExternalStorageDirectory() but you may use somewhere else... then it takes the file path, starting at the root, and makes it the unique ID, prepending "root:". So I can determine the path by eliminating the "/document/root:" part from uri.getPath(), creating an actual file path by doing something like this:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
// check resultcodes and such, then...
uri = data.getData();
if (uri.getAuthority().equals("com.example.provider"))  {
    String path = Environment.getExternalStorageDirectory(0.toString()
                 .concat("/")
                 .concat(uri.getPath().substring("/document/root:".length())));
    doSomethingWithThePath(path); }
else {
    // another provider (maybe a cloud-based service such as GDrive)
    // created this uri.  So handle it, or don't.  You can allow specific
    // local filesystem providers, filter non-filesystem path results, etc.
}

I know. It's shameful, but it worked. Again, this relies on you using your own documents provider in your app to generate the document ID.

(Also, there's a better way to build the path that don't assume "/" is the path separator, etc. But you get the idea.)

Mysql adding user for remote access

for what DB is the user? look at this example

mysql> create database databasename;
Query OK, 1 row affected (0.00 sec)
mysql> grant all on databasename.* to cmsuser@localhost identified by 'password';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

so to return to you question the "%" operator means all computers in your network.

like aspesa shows I'm also sure that you have to create or update a user. look for all your mysql users:

SELECT user,password,host FROM user;

as soon as you got your user set up you should be able to connect like this:

mysql -h localhost -u gmeier -p

hope it helps

How to create a JPA query with LEFT OUTER JOIN

If you have entities A and B without any relation between them and there is strictly 0 or 1 B for each A, you could do:

select a, (select b from B b where b.joinProperty = a.joinProperty) from A a

This would give you an Object[]{a,b} for a single result or List<Object[]{a,b}> for multiple results.

Directing print output to a .txt file

You can redirect stdout into a file "output.txt":

import sys
sys.stdout = open('output.txt','wt')
print ("Hello stackoverflow!")
print ("I have a question.")

How to remove an iOS app from the App Store

You can "Deselect All" to remove the app (temporarily) from all App Stores, as Noah mentioned.

And you can "Select All" to get the App back to all App Stores.

You can find it in: iTunes Connect Link

Rubymine: How to make Git ignore .idea files created by Rubymine

While it's not been too long that I made the switch to Rubymine, I found it challenging ignoring .idea files of Rubymine from been committed to git.

Here's how I fixed it

If you've not done any staging/commit at all, or you just spinned up a new project in Ruby mine, then simply do this

Option 1

Add the line below to the .gitignore file which is usually placed at the root of your repository.

# Ignore .idea files
.idea/

This will ensure that all .idea files are ignored from been tracked by git, although they will still remain in your project folder locally.

Option 2

If you've however done some staging/commit, or you just opened up an existing project in Ruby mine, then simply do this

Run the code in your terminal/command line

git rm -r --cached .idea

This deletes already tracked .idea files in git

Next, include .idea/ to the .gitignore file which is usually placed at the root of your repository.

# Ignore .idea files
.idea/

This will ensure that all .idea files are ignored from been tracked by git, although they will still remain in your project folder locally.

Option 3

If you've however done some staging/commit, or you just opened up an existing project in Ruby mine, and want to totally delete .idea files locally and in git, then simply do this

Run the code in your terminal/command line

git rm -r --cached .idea

This deletes already tracked .idea files in git

Run the code in your terminal/command line

rm -r .idea

This deletes all .idea files including the folder locally

Next, include .idea/ to the .gitignore file which is usually placed at the root of your repository.

# Ignore .idea files
.idea/

This will ensure that all .idea files are ignored from been tracked by git, and also deleted from your project folder locally.

That's all

I hope this helps

Convert char to int in C#

Try This

char x = '9'; // '9' = ASCII 57

int b = x - '0'; //That is '9' - '0' = 57 - 48 = 9

How can I create a copy of an Oracle table without copying the data?

Create table target_table 
As
Select * 
from source_table 
where 1=2;

Source_table is the table u wanna copy the structure of.

How to get 2 digit year w/ Javascript?

another version:

var yy = (new Date().getFullYear()+'').slice(-2);

Vertical Menu in Bootstrap

With a few CSS overrides, I find the accordion / collapse plugin works well as a sidebar vertical menu. Here's a small sample of some overrides I use for a menu on a white background. The accordion is placed within a section container:

.accordion-group
{
    margin-bottom: 1px;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    border-radius: 0px;
    border-bottom: 1px solid #E5E5E5;
    border-top: none;
    border-left: none;
    border-right: none;
}

.accordion-heading:hover
{
    background-color: #FFFAD9;
}

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

Get current cursor position

GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.

Hiding the cursor can be done with ShowCursor().

Structure of a PDF file?

If You want to parse PDF using Python please have a look at PDFMINER. This is the best library to parse PDF files till date.

Kotlin Ternary Conditional Operator

Java's equivalent of ternary operator

a ? b : c

is a simple IF in Kotlin in one line

if(a) b else c

there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

https://kotlinlang.org/docs/reference/control-flow.html#if-expression


Special case for Null comparison

you can use the Elvis operator

if ( a != null ) a else b
// equivalent to
a ?: b

How to skip over an element in .map()?

I think the most simple way to skip some elements from an array is by using the filter() method.

By using this method (ES5) and the ES6 syntax you can write your code in one line, and this will return what you want:

_x000D_
_x000D_
let images = [{src: 'img.png'}, {src: 'j1.json'}, {src: 'img.png'}, {src: 'j2.json'}];_x000D_
_x000D_
let sources = images.filter(img => img.src.slice(-4) != 'json').map(img => img.src);_x000D_
_x000D_
console.log(sources);
_x000D_
_x000D_
_x000D_

Why is there no String.Empty in Java?

String.EMPTY is 12 characters, and "" is two, and they would both be referencing exactly the same instance in memory at runtime. I'm not entirely sure why String.EMPTY would save on compile time, in fact I think it would be the latter.

Especially considering Strings are immutable, it's not like you can first get an empty String, and perform some operations on it - best to use a StringBuilder (or StringBuffer if you want to be thread-safe) and turn that into a String.

Update
From your comment to the question:

What inspired this is actually TextBox.setText("");

I believe it would be totally legitimate to provide a constant in your appropriate class:

private static final String EMPTY_STRING = "";

And then reference it as in your code as

TextBox.setText(EMPTY_STRING);

As this way at least you are explicit that you want an empty String, rather than you forgot to fill in the String in your IDE or something similar.

Android ImageView setImageResource in code

you use that code

ImageView[] ivCard = new ImageView[1];

@override    
protected void onCreate(Bundle savedInstanceState)  

ivCard[0]=(ImageView)findViewById(R.id.imageView1);

Remove Top Line of Text File with PowerShell

Using variable notation, you can do it without a temporary file:

${C:\file.txt} = ${C:\file.txt} | select -skip 1

function Remove-Topline ( [string[]]$path, [int]$skip=1 ) {
  if ( -not (Test-Path $path -PathType Leaf) ) {
    throw "invalid filename"
  }

  ls $path |
    % { iex "`${$($_.fullname)} = `${$($_.fullname)} | select -skip $skip" }
}

The type initializer for 'MyClass' threw an exception

Check the InnerException property of the TypeInitializationException; it is likely to contain information about the underlying problem, and exactly where it occurred.

Scanner only reads first word instead of line

Use input.nextLine(); instead of input.next();

Is it ok to use `any?` to check if an array is not empty?

I don't think it's bad to use any? at all. I use it a lot. It's clear and concise.

However if you are concerned about all nil values throwing it off, then you are really asking if the array has size > 0. In that case, this dead simple extension (NOT optimized, monkey-style) would get you close.

Object.class_eval do

  def size?
    respond_to?(:size) && size > 0
  end

end

> "foo".size?
 => true
> "".size?
 => false
> " ".size?
 => true
> [].size?
 => false
> [11,22].size?
 => true
> [nil].size?
 => true

This is fairly descriptive, logically asking "does this object have a size?". And it's concise, and it doesn't require ActiveSupport. And it's easy to build on.

Some extras to think about:

  1. This is not the same as present? from ActiveSupport.
  2. You might want a custom version for String, that ignores whitespace (like present? does).
  3. You might want the name length? for String or other types where it might be more descriptive.
  4. You might want it custom for Integer and other Numeric types, so that a logical zero returns false.

define a List like List<int,string>?

Use C# Dictionary datastructure it good for you...

Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("one", 1);
dict.Add("two", 2);

You can retrieve data from Ditionary in a simple way..

foreach (KeyValuePair<string, int> pair in dict)
{
    MessageBox.Show(pair.Key.ToString ()+ "  -  "  + pair.Value.ToString () );
}

For more example using C# Dictionary... C# Dictionary

Navi.

How to cancel/abort jQuery AJAX request?

Why should you abort the request?

If each request takes more than five seconds, what will happen?

You shouldn't abort the request if the parameter passing with the request is not changing. eg:- the request is for retrieving the notification data. In such situations, The nice approach is that set a new request only after completing the previous Ajax request.

$(document).ready(

    var fn = function(){

        $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            },

            complete: function(){setTimeout(fn, 500);}
        });
    };

     var interval = setTimeout(fn, 500);

);

Failed Apache2 start, no error log

On Apache on Linux there might be a problem that the configuration cannot be checked because of a problem with environment variables not being set. This is a false positive which only occurs when running apache2 -S from commandline (See previous answer from @simhumileco). For instance Config variable ${APACHE_RUN_DIR} is not defined.

In order to fix this run source /etc/apache2/envvars from the commandline and then run `apache2 -S' to get to the real (possible) problems.

root@fileserver:~# apache2 -S
[Thu Apr 30 10:42:06.822719 2020] [core:warn] [pid 24624] AH00111: Config variable ${APACHE_RUN_DIR} is not defined
apache2: Syntax error on line 80 of /etc/apache2/apache2.conf: DefaultRuntimeDir must be a valid directory, absolute or relative to ServerRoot
root@fileserver:~# source /etc/apache2/envvars
root@fileserver:/root# apache2 -S
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
VirtualHost configuration:
<----snip---->
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex ldap-cache: using_defaults
Mutex default: dir="/var/run/apache2/" mechanism=default
Mutex mpm-accept: using_defaults
Mutex watchdog-callback: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33
root@fileserver:/root#

Pattern matching using a wildcard

glob2rx() converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.

If you want to match "blue*" where * has the usual wildcard, not regular expression, meaning we use glob2rx() to convert the wildcard pattern into a useful regular expression:

> glob2rx("blue*")
[1] "^blue"

The returned object is a regular expression.

Given your data:

x <- c('red','blue1','blue2', 'red2')

we can pattern match using grep() or similar tools:

> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE  TRUE  TRUE FALSE

As for the selecting rows problem you posted

> a <- data.frame(x =  c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2

or via subset():

> with(a, subset(a, subset = grepl(grx, x)))
      x
2 blue1
3 blue2

Hope that explains what grob2rx() does and how to use it?