Programs & Examples On #Sentry

Sentry is an event logging platform primarily focused on capturing and aggregating exceptions.

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

You must add a reference to assembly 'netstandard, Version=2.0.0.0

I have run into this before and trying a number of things has fixed it for me:

  • Delete a bin folder if it exists
  • Delete the hidden .vs folder
  • Make sure the 4.6.1 targeting pack is installed
  • Last Ditch Effort: Add a reference to System.Runtime (right click project -> add -> reference -> tick the box next to System.Runtime), although I think I've always figured out one of the above has solved it instead of doing this.

Also, if this is a .net core app running on the full framework, I've found you have to include a global.json file at the root of your project and point it to the SDK you want to use for that project:

{
  "sdk": {
    "version": "1.0.0-preview2-003121"
  }
}

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

For me the issue was caused by com.google.android.exoplayer conflicting with com.facebook.android:audience-network-sdk.

I fixed the problem by excluding the exoplayer library from the audience-network-sdk :

compile ('com.facebook.android:audience-network-sdk:4.24.0') {
    exclude group: 'com.google.android.exoplayer'
}

Laravel: Auth::user()->id trying to get a property of a non-object

You may access the authenticated user via the Auth facade:

use Illuminate\Support\Facades\Auth;

// Get the currently authenticated user...
$user = Auth::user();

// Get the currently authenticated user's ID...
$id = Auth::id();

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

In my case it was something else: the object I was saving should first have an id(e.g. save() should be called) before I could set any kind of relationship with it.

EF Code First "Invalid column name 'Discriminator'" but no inheritance

Another scenario where this occurs is when you have a base class and one or more subclasses, where at least one of the subclasses introduce extra properties:

class Folder {
  [key]
  public string Id { get; set; }

  public string Name { get; set; }
}

// Adds no props, but comes from a different view in the db to Folder:
class SomeKindOfFolder: Folder {
}

// Adds some props, but comes from a different view in the db to Folder:
class AnotherKindOfFolder: Folder {
  public string FolderAttributes { get; set; }
}

If these are mapped in the DbContext like below, the "'Invalid column name 'Discriminator'" error occurs when any type based on Folder base type is accessed:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Folder>().ToTable("All_Folders");
  modelBuilder.Entity<SomeKindOfFolder>().ToTable("Some_Kind_Of_Folders");
  modelBuilder.Entity<AnotherKindOfFolder>().ToTable("Another_Kind_Of_Folders");
}

I found that to fix the issue, we extract the props of Folder to a base class (which is not mapped in OnModelCreating()) like so - OnModelCreating should be unchanged:

class FolderBase {
  [key]
  public string Id { get; set; }

  public string Name { get; set; }
}

class Folder: FolderBase {
}

class SomeKindOfFolder: FolderBase {
}

class AnotherKindOfFolder: FolderBase {
  public string FolderAttributes { get; set; }
}

This eliminates the issue, but I don't know why!

Convert JSON string to dict using Python

json.loads()

import json

d = json.loads(j)
print d['glossary']['title']

XAMPP Object not found error

Drixson Oseña you are right but when you newly install xampp on your system "Object not found!

"The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again. If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.6"

However all folder in the htdocs but only open is that xampp website because of index.php error, so that's not a big deal just remove the index.html and index.php and try to open localhost again you'll be succeed.

How to set DateTime to null

DateTime is a non-nullable value type

DateTime? newdate = null;

You can use a Nullable<DateTime>

c# Nullable Datetime

How can I know if a process is running?

It depends on how reliable you want this function to be. If you want to know if the particular process instance you have is still running and available with 100% accuracy then you are out of luck. The reason being that from the managed process object there are only 2 ways to identify the process.

The first is the Process Id. Unfortunately, process ids are not unique and can be recycled. Searching the process list for a matching Id will only tell you that there is a process with the same id running, but it's not necessarily your process.

The second item is the Process Handle. It has the same problem though as the Id and it's more awkward to work with.

If you're looking for medium level reliability then checking the current process list for a process of the same ID is sufficient.

Adding a slide effect to bootstrap dropdown

On click it can be done using below code

$('.dropdown-toggle').click(function() {
  $(this).next('.dropdown-menu').slideToggle(500);
});

How to convert string values from a dictionary, into int/float datatypes?

To handle the possibility of int, float, and empty string values, I'd use a combination of a list comprehension, dictionary comprehension, along with conditional expressions, as shown:

dicts = [{'a': '1' , 'b': '' , 'c': '3.14159'},
         {'d': '4' , 'e': '5' , 'f': '6'}]

print [{k: int(v) if v and '.' not in v else float(v) if v else None
            for k, v in d.iteritems()}
               for d in dicts]

# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]

However dictionary comprehensions weren't added to Python 2 until version 2.7. It can still be done in earlier versions as a single expression, but has to be written using the dict constructor like the following:

# for pre-Python 2.7

print [dict([k, int(v) if v and '.' not in v else float(v) if v else None]
            for k, v in d.iteritems())
                for d in dicts]

# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]

Note that either way this creates a new dictionary of lists, instead of modifying the original one in-place (which would need to be done differently).

HTML CSS Invisible Button

you must use the following properties for a button element to make it transparent.

Transparent Button With No Text

button {

    background: transparent;
    border: none !important;
    font-size:0;
}

Transparent Button With Visible Text

button {

    background: transparent;
    border: none !important;
}?

and use absolute position to position the element.

For Example

you have the button element under a div. Use position : relative on div and position: absolute on the button to position it within the div.

here is a working JSFiddle

here is an updated JSFiddle that displays only text from the button.

How to prevent Right Click option using jquery

Try this:

$(document).bind("contextmenu",function(e){
    return false;
});

Make a dictionary in Python from input values

record = int(input("Enter the student record need to add :"))

stud_data={}

for i in range(0,record):
    Name = input("Enter the student name :").split()
    Age = input("Enter the {} age :".format(Name))
    Grade = input("Enter the {} grade :".format(Name)).split()
    Nam_key =  Name[0]
    Age_value = Age[0]
    Grade_value = Grade[0]
    stud_data[Nam_key] = {Age_value,Grade_value}

print(stud_data)

DNS caching in linux

Firefox contains a dns cache. To disable the DNS cache:

  1. Open your browser
  2. Type in about:config in the address bar
  3. Right click on the list of Properties and select New > Integer in the Context menu
  4. Enter 'network.dnsCacheExpiration' as the preference name and 0 as the integer value

When disabled, Firefox will use the DNS cache provided by the OS.

How to _really_ programmatically change primary and accent color in Android Lollipop?

This is what you CAN do:

write a file in drawable folder, lets name it background.xml

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

then set your Layout's (or what so ever the case is) android:background="@drawable/background"

on setting your theme this color would represent the same.

MySQL: Convert INT to DATETIME

SELECT  FROM_UNIXTIME(mycolumn)
FROM    mytable

Setting focus on an HTML input box on page load

And you can use HTML5's autofocus attribute (works in all current browsers except IE9 and below). Only call your script if it's IE9 or earlier, or an older version of other browsers.

<input type="text" name="fname" autofocus>

Eclipse - Unable to install breakpoint due to missing line number attributes

We also have this message when starting the Java EE project with the Spring Tool Suite (STS), but we are in the good position just to ignore this message, as everything works fine.

How to set tint for an image view programmatically in android?

Don't use PoterDuff.Mode, Use setColorFilter() it works for all.

ImageView imageView = (ImageView) listItem.findViewById(R.id.imageView);
imageView.setColorFilter(getContext().getResources().getColor(R.color.msg_read));

Communication between tabs or windows

There's a tiny open-source component to sync/communicate between tabs/windows of the same origin (disclaimer - I'm one of the contributors!) based around localStorage.

TabUtils.BroadcastMessageToAllTabs("eventName", eventDataString);

TabUtils.OnBroadcastMessage("eventName", function (eventDataString) {
    DoSomething();
});

TabUtils.CallOnce("lockname", function () {
    alert("I run only once across multiple tabs");
});

https://github.com/jitbit/TabUtils

P.S. I took the liberty to recommend it here since most of the "lock/mutex/sync" components fail on websocket connections when events happen almost simultaneously

How can I remove an element from a list?

Using lapply and grep:

lst <- list(a = 1:4, b = 4:8, c = 8:10)
# say you want to remove a and c
toremove<-c("a","c")
lstnew<-lst[-unlist(lapply(toremove, function(x) grep(x, names(lst)) ) ) ]
#or
pattern<-"a|c"
lstnew<-lst[-grep(pattern, names(lst))]

Type converting slices of interfaces

In case you need more shorting your code, you can creating new type for helper

type Strings []string

func (ss Strings) ToInterfaceSlice() []interface{} {
    iface := make([]interface{}, len(ss))
    for i := range ss {
        iface[i] = ss[i]
    }
    return iface
}

then

a := []strings{"a", "b", "c", "d"}
sliceIFace := Strings(a).ToInterfaceSlice()

"Cannot start compilation: the output path is not specified for module..."

I'm answering this so that I can find the solution when I have to google this error again.

Set project compile output path to path_of_the_project_folder/out. That's what is working today. The intellj documentation makes it seem like we can select any folder but that's not the case.

How to calculate the time interval between two time strings

I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps. Not sure if it has some cons.

But looks neat for me :)

from datetime import datetime
from dateutil.relativedelta import relativedelta

t_a = datetime.now()
t_b = datetime.now()

def diff(t_a, t_b):
    t_diff = relativedelta(t_b, t_a)  # later/end time comes first!
    return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)

Regarding to the question you still need to use datetime.strptime() as others said earlier.

How to display binary data as image - extjs 4

Need to convert it in base64.

JS have btoa() function for it.

For example:

var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data');
document.body.appendChild(img);

But i think what your binary data in pastebin is invalid - the jpeg data must be ended on 'ffd9'.

Update:

Need to write simple hex to base64 converter:

function hexToBase64(str) {
    return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}

And use it:

img.src = 'data:image/jpeg;base64,' + hexToBase64('your-binary-data');

See working example with your hex data on jsfiddle

Save and load MemoryStream to/from a file

The stream should really by disposed of even if there's an exception (quite likely on file I/O) - using clauses are my favourite approach for this, so for writing your MemoryStream, you can use:

using (FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write)) {
    memoryStream.WriteTo(file);
}

And for reading it back:

using (FileStream file = new FileStream("file.bin", FileMode.Open, FileAccess.Read)) {
    byte[] bytes = new byte[file.Length];
    file.Read(bytes, 0, (int)file.Length);
    ms.Write(bytes, 0, (int)file.Length);
}

If the files are large, then it's worth noting that the reading operation will use twice as much memory as the total file size. One solution to that is to create the MemoryStream from the byte array - the following code assumes you won't then write to that stream.

MemoryStream ms = new MemoryStream(bytes, writable: false);

My research (below) shows that the internal buffer is the same byte array as you pass it, so it should save memory.

byte[] testData = new byte[] { 104, 105, 121, 97 };
var ms = new MemoryStream(testData, 0, 4, false, true);
Assert.AreSame(testData, ms.GetBuffer());

Max size of URL parameters in _GET

Ok, it seems that some versions of PHP have a limitation of length of GET params:

Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add suhosin.get.max_value_length = <limit> in php.ini

Source: http://www.php.net/manual/en/reserved.variables.get.php#101469

System.Net.Http: missing from namespace? (using .net 4.5)

Visual Studio Package Manager Console > Install-Package Microsoft.AspNet.WebApi.Client

PHP check whether property exists in object or class

Solution

echo $person->middleName ?? 'Person does not have a middle name';

To show how this would look in an if statement for more clarity on how this is working.

if($person->middleName ?? false) {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

Explanation

The traditional PHP way to check for something's existence is to do:

if(isset($person->middleName)) {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

OR for a more class specific way:

if(property_exists($person, 'middleName')) {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

These are both fine in long form statements but in ternary statements they become unnecessarily cumbersome like so:

isset($person->middleName) ? echo $person->middleName : echo 'Person does not have a middle name';

You can also achieve this with just the ternary operator like so:

echo $person->middleName ?: 'Person does not have a middle name';

But... if the value does not exist (is not set) it will raise an E_NOTICE and is not best practise. If the value is null it will not raise the exception.

Therefore ternary operator to the rescue making this a neat little answer:

echo $person->middleName ?? 'Person does not have a middle name';

What Does 'zoom' do in CSS?

Only IE and WebKit support zoom, and yes, in theory it does exactly what you're saying.

Try it out on an image to see it's full effect :)

How to print jquery object/array

I was having similar problem and

var dataObj = JSON.parse(data);

console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie

This solved my problem. Thanks Selvakumar Arumugam

How to perform grep operation on all files in a directory?

In Linux, I normally use this command to recursively grep for a particular text within a dir

grep -rni "string" *

where,

r = recursive i.e, search subdirectories within the current directory
n = to print the line numbers to stdout
i = case insensitive search

How to determine the Boost version on a system?

@Vertexwahns answer, but written in bash. For the people who are lazy:

boost_version=$(cat /usr/include/boost/version.hpp | grep define | grep "BOOST_VERSION " | cut -d' ' -f3)
echo "installed boost version: $(echo "$boost_version / 100000" | bc).$(echo "$boost_version / 100 % 1000" | bc).$(echo "$boost_version % 100 " | bc)"

Gives me installed boost version: 1.71.0

What is the default value for enum variable?

I think it's quite dangerous to rely on the order of the values in a enum and to assume that the first is always the default. This would be good practice if you are concerned about protecting the default value.

enum E
{
    Foo = 0, Bar, Baz, Quux
}

Otherwise, all it takes is a careless refactor of the order and you've got a completely different default.

Linux Process States

While waiting for read() or write() to/from a file descriptor return, the process will be put in a special kind of sleep, known as "D" or "Disk Sleep". This is special, because the process can not be killed or interrupted while in such a state. A process waiting for a return from ioctl() would also be put to sleep in this manner.

An exception to this is when a file (such as a terminal or other character device) is opened in O_NONBLOCK mode, passed when its assumed that a device (such as a modem) will need time to initialize. However, you indicated block devices in your question. Also, I have never tried an ioctl() that is likely to block on a fd opened in non blocking mode (at least not knowingly).

How another process is chosen depends entirely on the scheduler you are using, as well as what other processes might have done to modify their weights within that scheduler.

Some user space programs under certain circumstances have been known to remain in this state forever, until rebooted. These are typically grouped in with other "zombies", but the term would not be correct as they are not technically defunct.

How to disable Paste (Ctrl+V) with jQuery?

This now works for IE FF Chrome properly... I have not tested for other browsers though

$(document).ready(function(){
   $('#txtInput').on("cut copy paste",function(e) {
      e.preventDefault();
   });
});

Edit: As pointed out by webeno, .bind() is deprecated hence it is recommended to use .on() instead.

Set a cookie to never expire

I believe that there isn't a way to make a cookie last forever, but you just need to set it to expire far into the future, such as the year 2100.

What is the difference between dim and set in vba

Dim is short for Dimension and is used in VBA and VB6 to declare local variables.

Set on the other hand, has nothing to do with variable declarations. The Set keyword is used to assign an object variable to a new object.

Hope that clarifies the difference for you.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

I found that there was a syntax error in the related module and it wasn't compiling - the compiler didn't tell me that though. Just gave me the error regarding the app.config stuff. VS2010. Once I had fixed the syntax error, all was good.

Clear the value of bootstrap-datepicker

I came across this thread while trying to figure out why the dates weren't being cleared in IE7/IE8.
It has to do with the fact that IE8 and older require a second parameter for the Array.prototype.splice() method. Here's the original code in bootstrap.datepicker.js:

clear: function(){
    this.splice(0);
},

Adding the second parameter resolved my issue:

clear: function(){
    this.splice(0,this.length);
},

Change value of input placeholder via model?

The accepted answer still threw a Javascript error in IE for me (for Angular 1.2 at least). It is a bug but the workaround is to use ngAttr detailed on https://docs.angularjs.org/guide/interpolation

<input type="text" ng-model="inputText" ng-attr-placeholder="{{somePlaceholder}}" />

Issue: https://github.com/angular/angular.js/issues/5025

Bulk insert with SQLAlchemy ORM

Piere's answer is correct but one issue is that bulk_save_objects by default does not return the primary keys of the objects, if that is of concern to you. Set return_defaults to True to get this behavior.

The documentation is here.

foos = [Foo(bar='a',), Foo(bar='b'), Foo(bar='c')]
session.bulk_save_objects(foos, return_defaults=True)
for foo in foos:
    assert foo.id is not None
session.commit()

How to make function decorators and chain them together?

A decorator takes the function definition and creates a new function that executes this function and transforms the result.

@deco
def do():
    ...

is equivalent to:

do = deco(do)

Example:

def deco(func):
    def inner(letter):
        return func(letter).upper()  #upper
    return inner

This

@deco
def do(number):
    return chr(number)  # number to letter

is equivalent to this

def do2(number):
    return chr(number)

do2 = deco(do2)

65 <=> 'a'

print(do(65))
print(do2(65))
>>> B
>>> B

To understand the decorator, it is important to notice, that decorator created a new function do which is inner that executes function and transforms the result.

How to scroll table's "tbody" independent of "thead"?

mandatory parts:

tbody {
    overflow-y: scroll;  (could be: 'overflow: scroll' for the two axes)
    display: block;
    with: xxx (a number or 100%)
}

thead {
    display: inline-block;
}

How to check if the docker engine and a docker container are running?

Run this command in the terminal:

docker ps

If docker is not running, you wil get this message:

Error response from daemon: dial unix docker.raw.sock: connect: connection refused

How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

Reading/Writing a MS Word file in PHP

You can use Antiword, it is a free MS Word reader for Linux and most popular OS.

$document_file = 'c:\file.doc';
$text_from_doc = shell_exec('/usr/local/bin/antiword '.$document_file);

Apply CSS styles to an element depending on its child elements

Basically, no. The following would be what you were after in theory:

div.a < div { border: solid 3px red; }

Unfortunately it doesn't exist.

There are a few write-ups along the lines of "why the hell not". A well fleshed out one by Shaun Inman is pretty good:

http://www.shauninman.com/archive/2008/05/05/css_qualified_selectors

stale element reference: element is not attached to the page document

try {
    WebElement button = driver.findElement(By.xpath("xpath"));
            button.click();
}
catch(org.openqa.selenium.StaleElementReferenceException ex)
{
    WebElement button = driver.findElement(By.xpath("xpath"));
            button.click();
}

This try/catch code actually worked for me. I got the same stale element error.

How to detect escape key press with pure JS or jQuery?

The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.

Update May 2016

keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).

Update September 2018 evt.key is now supported by all modern browsers.

_x000D_
_x000D_
document.onkeydown = function(evt) {_x000D_
    evt = evt || window.event;_x000D_
    var isEscape = false;_x000D_
    if ("key" in evt) {_x000D_
        isEscape = (evt.key === "Escape" || evt.key === "Esc");_x000D_
    } else {_x000D_
        isEscape = (evt.keyCode === 27);_x000D_
    }_x000D_
    if (isEscape) {_x000D_
        alert("Escape");_x000D_
    }_x000D_
};
_x000D_
Click me then press the Escape key
_x000D_
_x000D_
_x000D_

Unlink of file Failed. Should I try again?

This might be useful for someone; if all the above didn't work for you, follow these steps:

  1. Close your IDE (mine was Eclipse, not sure if it applies to Intellij and others) or any other app that might be using git.

  2. Open git from the command line (in my case I had git bash) and run git gc as mentioned by others.

This did the magic for me.

Pass array to ajax request in $.ajax()

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

Using an array from Observable Object with ngFor and Async Pipe Angular 2

If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below assuming you only care about adding objects to the observable, not deleting them.

If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:

Component

this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));

Html

<div class="message-list" *ngFor="let item of messages$ | async">

Hiding button using jQuery

Try this:

$('input[name=Comanda]')
.click(
     function ()
     {
         $(this).hide();
     }
);

For doing everything else you can use something like this one:

$('input[name=Comanda]')
.click(
     function ()
     {
         $(this).hide();

         $(".ClassNameOfShouldBeHiddenElements").hide();
     }
);

For hidding any other elements based on their IDs, use this one:

$('input[name=Comanda]')
.click(
     function ()
     {
         $(this).hide();

         $("#FirstElement").hide();
         $("#SecondElement").hide();
         $("#ThirdElement").hide();
     }
);

How to export data as CSV format from SQL Server using sqlcmd?

This answer builds on the solution from @iain-elder, which works well except for the large database case (as pointed out in his solution). The entire table needs to fit in your system's memory, and for me this was not an option. I suspect the best solution would use the System.Data.SqlClient.SqlDataReader and a custom CSV serializer (see here for an example) or another language with an MS SQL driver and CSV serialization. In the spirit of the original question which was probably looking for a no dependency solution, the PowerShell code below worked for me. It is very slow and inefficient especially in instantiating the $data array and calling Export-Csv in append mode for every $chunk_size lines.

$chunk_size = 10000
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = "SELECT * FROM <TABLENAME>"
$command.Connection = $connection
$connection.open()
$reader = $command.ExecuteReader()

$read = $TRUE
while($read){
    $counter=0
    $DataTable = New-Object System.Data.DataTable
    $first=$TRUE;
    try {
        while($read = $reader.Read()){

            $count = $reader.FieldCount
            if ($first){
                for($i=0; $i -lt $count; $i++){
                    $col = New-Object System.Data.DataColumn $reader.GetName($i)
                    $DataTable.Columns.Add($col)
                }
                $first=$FALSE;
            }

            # Better way to do this?
            $data=@()
            $emptyObj = New-Object System.Object
            for($i=1; $i -le $count; $i++){
                $data +=  $emptyObj
            }

            $reader.GetValues($data) | out-null
            $DataRow = $DataTable.NewRow()
            $DataRow.ItemArray = $data
            $DataTable.Rows.Add($DataRow)
            $counter += 1
            if ($counter -eq $chunk_size){
                break
            }
        }
        $DataTable | Export-Csv "output.csv" -NoTypeInformation -Append
    }catch{
        $ErrorMessage = $_.Exception.Message
        Write-Output $ErrorMessage
        $read=$FALSE
        $connection.Close()
        exit
    }
}
$connection.close()

Cannot connect to repo with TortoiseSVN

Look into this as well:

Issue: After invoking SVN on the command line on a firewalled server, nothing visible happens for 15 seconds, then the program quits with the following error:

svn: E170013: Unable to connect to a repository at URL 'SVN.REPOSITORY.REDACTED'

svn: E730054: Error running context: An existing connection was forcibly closed by the remote host.

Investigation: Internet research on the above errors did not uncover any pertinent information.

Process Tracing (procmon) showed a connection attempt to an Akamai (cloud services) server after the SSL/TLS handshake to the SVN Server. The hostname for the server was not shown in Process tracing. Reverse DNS lookup showed a184-51-112-88.deploy.static.akamaitechnologies.com or a184-51-112-80.deploy.static.akamaitechnologies.com as the hostname, and the IP was either 184.51.112.88 or 184.51.112.80 (2 entries in DNS cache).

Packet capture tool (MMA) showed a connection attempt to the hostname ctldl.windowsupdate.com after the SSL/TLS Handshake to the SVN server.

The windows Crypto API was attempting to connect to Windows Update to retrieve Certificate revocation information (CRL – certificate revocation list). The default timeout for CRL retrieval is 15 seconds. The timeout for authentication on the server is 10 seconds; as 15 is greater than 10, this fails.

Resolution: Internet research uncovered the following: (also see picture at bottom)

Solution 1: Decrease CRL timeout Group Policy -> Computer Config ->Windows Settings -> Security Settings -> Public Key Policies -> Certificate Path Validation Settings -> Network Retrieval – see picture below.

https://subversion.open.collab.net/ds/viewMessage.do?dsForumId=4&dsMessageId=470698

support.microsoft.com/en-us/kb/2625048

blogs.technet.com/b/exchange/archive/2010/05/14/3409948.aspx

Solution 2: Open firewall for CRL traffic

support.microsoft.com/en-us/kb/2677070

Solution 3: SVN command line flags (untested)

serverfault.com/questions/716845/tortoise-svn-initial-connect-timeout - alternate svn command line flag solution.

Additional Information: Debugging this issue was particularly difficult. SVN 1.8 disabled support for the Neon HTTP RA (repository access) library in favor of the Serf library which removed client debug logging. [1] In addition, the SVN error code returned did not match the string given in svn_error_codes.h [2] Also, SVN Error codes cannot be mapped back to their ENUM label easily, this case SVN error code E170013 maps to SVN_ERR_RA_CANNOT_CREATE_SESSION.

  1. stackoverflow.com/questions/8416989/is-it-possible-to-get-svn-client-debug-output
  2. people.apache.org/~brane/svndocs/capi/svn__error__codes_8h.html#ac8784565366c15a28d456c4997963660a044e5248bb3a652768e5eb3105d6f28f
  3. code.google.com/archive/p/serf/issues/172

Suggested SVN Changes:

  1. Enable Verbosity on the command like for all operations

  2. Add error ENUM name to stderr

  3. Add config flag for Serf Library debug logging.

Detect Route Change with react-router

If you want to listen to the history object globally, you'll have to create it yourself and pass it to the Router. Then you can listen to it with its listen() method:

// Use Router from react-router, not BrowserRouter.
import { Router } from 'react-router';

// Create history object.
import createHistory from 'history/createBrowserHistory';
const history = createHistory();

// Listen to history changes.
// You can unlisten by calling the constant (`unlisten()`).
const unlisten = history.listen((location, action) => {
  console.log(action, location.pathname, location.state);
});

// Pass history to Router.
<Router history={history}>
   ...
</Router>

Even better if you create the history object as a module, so you can easily import it anywhere you may need it (e.g. import history from './history';

Prevent users from submitting a form by hitting Enter

Go into your css and add that to it then will automatically block the submission of your formular as long as you have submit input if you no longer want it you can delete it or type activate and deactivate instead

 input:disabled {
        background: gainsboro;
      }
      input[value]:disabled {
        color: whitesmoke;
      }

Force div element to stay in same place, when page is scrolled

There is something wrong with your code.

position : absolute makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll

This can be solved with position : fixed This property will make the element position fixed and still relative to the scroll.

Or

You can check it out Here

Difference between "git add -A" and "git add ."

The -A option adds, modifies, and removes index entries to match the working tree.

In Git 2 the -A option is now the default.

When a . is added that limits the scope of the update to the directory you are currently in, as per the Git documentation

If no <pathspec> is given when -A option is used, all files in the entire working tree are updated (old versions of Git used to limit the update to the current directory and its subdirectories).

One thing that I would add is that if the --interactive or -p mode is used then git add will behave as if the update (-u) flag was used and not add new files.

Calling a user defined function in jQuery

If you want to call a normal function via a jQuery event, you can do it like this:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#btnSun').click(myFunction);_x000D_
});_x000D_
_x000D_
function myFunction() {_x000D_
  alert('hi');_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="btnSun">Say hello!</button>
_x000D_
_x000D_
_x000D_

C# DLL config file

It is not trivial to create a .NET configuration file for a .DLL, and for good reason. The .NET configuration mechanism has a lot of features built into it to facilitate easy upgrading/updating of the app, and to protect installed apps from trampling each others configuration files.

There is a big difference between how a DLL is used and how an application is used. You are unlikely to have multiple copies of an application installed on the same machine for the same user. But you may very well have 100 different apps or libraries all making use of some .NET DLL.

Whereas there is rarely a need to track settings separately for different copies of an app within one user profile, it's very unlikely that you would want all of the different usages of a DLL to share configuration with each other. For this reason, when you retrieve a Configuration object using the "normal" method, the object you get back is tied to the configuration of the App Domain you are executing in, rather than the particular assembly.

The App Domain is bound to the root assembly which loaded the assembly which your code is actually in. In most cases this will be the assembly of your main .EXE, which is what loaded up the .DLL. It is possible to spin up other app domains within an application, but you must explicitly provide information on what the root assembly of that app domain is.

Because of all this, the procedure for creating a library-specific config file is not so convenient. It is the same process you would use for creating an arbitrary portable config file not tied to any particular assembly, but for which you want to make use of .NET's XML schema, config section and config element mechanisms, etc. This entails creating an ExeConfigurationFileMap object, loading in the data to identify where the config file will be stored, and then calling ConfigurationManager.OpenMappedExeConfiguration to open it up into a new Configuration instance. This will cut you off from the version protection offered by the automatic path generation mechanism.

Statistically speaking, you're probably using this library in an in-house setting, and it's unlikely you'll have multiple apps making use of it within any one machine/user. But if not, there is something you should keep in mind. If you use a single global config file for your DLL, regardless of the app that is referencing it, you need to worry about access conflicts. If two apps referencing your library happen to be running at the same time, each with their own Configuration object open, then when one saves changes, it will cause an exception next time you try to retrieve or save data in the other app.

The safest and simplest way of getting around this is to require that the assembly which is loading your DLL also provide some information about itself, or to detect it by examining the App Domain of the referencing assembly. Use this to create some sort of folder structure for keeping separate user config files for each app referencing your DLL.

If you are certain you want to have global settings for your DLL no matter where it is referenced, you'll need to determine your location for it rather than .NET figuring out an appropriate one automatically. You'll also need to be aggressive about managing access to the file. You'll need to cache as much as possible, keeping the Configuration instance around ONLY as long as it takes to load or to save, opening immediately before and disposing immediately after. And finally, you'll need a lock mechanism to protect the file while it's being edited by one of the apps that use the library.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

The valueChangeListener is only necessary, if you are interested in both the old and the new value.

If you are only interested in the new value, the use of <p:ajax> or <f:ajax> is the better choice.

There are several possible reasons, why the ajax call won't work. First you should change the method signature of the handler method: drop the parameter. Then you can access your managed bean variable directly:

public void handleChange(){  
  System.out.println("here "+ getEmp().getEmployeeName());
}

At the time, the listener is called, the new value is already set. (Note that I implicitly assume that the el expression mymb.emp.employeeName is correctly backed by the corresponding getter/setter methods.)

Routing HTTP Error 404.0 0x80070002

The solution suggested

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="UrlRoutingModule"/>    
  </modules>
</system.webServer>

works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.

A more sensible solution is to include this in your web.config:

<system.webServer>
  <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  </modules>
</system.webServer>

Credit for his goes to Colin Farr. Check-out his post about this topic at http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html.

The CSRF token is invalid. Please try to resubmit the form

This seems to be an issue when using bootstrap unless you are rendering the form by {{ form(form)}}. In addition, the issues seems to only occur on input type="hidden". If you inspect the page the with the form, you'll find that the hidden input is not part of the markup at all or it's being rendered but not submitted for some reason. As suggested above, adding {{form_rest(form)}} or wrapping the input like below should do the trick.

<div class="form-group">
    <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
</div>

Difference between decimal, float and double in .NET?

The problem with all these types is that a certain imprecision subsists AND that this problem can occur with small decimal numbers like in the following example

Dim fMean as Double = 1.18
Dim fDelta as Double = 0.08
Dim fLimit as Double = 1.1

If fMean - fDelta < fLimit Then
    bLower = True
Else
    bLower = False
End If

Question: Which value does bLower variable contain ?

Answer: On a 32 bit machine bLower contains TRUE !!!

If I replace Double by Decimal, bLower contains FALSE which is the good answer.

In double, the problem is that fMean-fDelta = 1.09999999999 that is lower that 1.1.

Caution: I think that same problem can certainly exists for other number because Decimal is only a double with higher precision and the precision has always a limit.

In fact, Double, Float and Decimal correspond to BINARY decimal in COBOL !

It is regrettable that other numeric types implemented in COBOL don't exist in .Net. For those that don't know COBOL, there exist in COBOL following numeric type

BINARY or COMP like float or double or decimal
PACKED-DECIMAL or COMP-3 (2 digit in 1 byte)
ZONED-DECIMAL (1 digit in 1 byte) 

JSONResult to String

You're looking for the JavaScriptSerializer class, which is used internally by JsonResult:

string json = new JavaScriptSerializer().Serialize(jsonResult.Data);

JavaScript loop through json array?

There's a few problems in your code, first your json must look like :

var json = [{
"id" : "1", 
"msg"   : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id" : "2", 
"msg"   : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];

Next, you can iterate like this :

for (var key in json) {
if (json.hasOwnProperty(key)) {
  alert(json[key].id);
  alert(json[key].msg);
}
}

And it gives perfect result.

See the fiddle here : http://jsfiddle.net/zrSmp/

Trigger change event <select> using jquery

If you want to do some checks then use this way

 <select size="1" name="links" onchange="functionToTriggerClick(this.value)">
    <option value="">Select a Search Engine</option>        
    <option value="http://www.google.com">Google</option>
    <option value="http://www.yahoo.com">Yahoo</option>
</select>

<script>

   function functionToTriggerClick(link) {

     if(link != ''){
        window.location.href=link;
        }
    }  

</script>

How to delete history of last 10 commands in shell?

history -c will clear all histories.

AngularJS dynamic routing

Not sure why this works but dynamic (or wildcard if you prefer) routes are possible in angular 1.2.0-rc.2...

http://code.angularjs.org/1.2.0-rc.2/angular.min.js
http://code.angularjs.org/1.2.0-rc.2/angular-route.min.js

angular.module('yadda', [
  'ngRoute'
]).

config(function ($routeProvider, $locationProvider) {
  $routeProvider.
    when('/:a', {
  template: '<div ng-include="templateUrl">Loading...</div>',
  controller: 'DynamicController'
}).


controller('DynamicController', function ($scope, $routeParams) {
console.log($routeParams);
$scope.templateUrl = 'partials/' + $routeParams.a;
}).

example.com/foo -> loads "foo" partial

example.com/bar-> loads "bar" partial

No need for any adjustments in the ng-view. The '/:a' case is the only variable I have found that will acheive this.. '/:foo' does not work unless your partials are all foo1, foo2, etc... '/:a' works with any partial name.

All values fire the dynamic controller - so there is no "otherwise" but, I think it is what you're looking for in a dynamic or wildcard routing scenario..

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

bash:

for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done

What to do on TransactionTooLargeException

Try to use EventBus or ContentProvider like solution.

If you are in the same process(normally all your activities would be), try to use EventBus, cause in process data exchange does NOT need a somewhat buffer, so you do not need to worry about your data is too large. (You can just use method call to pass data indeed, and EventBus hide the ugly things) Here is the detail:

// one side
startActivity(intentNotTooLarge);
EventBus.getDefault().post(new FooEvent(theHugeData));

// the other side
@Subscribe public void handleData(FooEvent event) { /* get and handle data */ }

If the two sides of Intent are not in the same process, try somewhat ContentProvider.


See TransactionTooLargeException

The Binder transaction failed because it was too large.

During a remote procedure call, the arguments and the return value of the call are transferred as Parcel objects stored in the Binder transaction buffer. If the arguments or the return value are too large to fit in the transaction buffer, then the call will fail and TransactionTooLargeException will be thrown.

How to restart counting from 1 after erasing table in MS Access?

In addition to all the concerns expressed about why you give a rat's ass what the ID value is (all are correct that you shouldn't), let me add this to the mix:

If you've deleted all the records from the table, compacting the database will reset the seed value back to its original value.

For a table where there are still records, and you've inserted a value into the Autonumber field that is lower than the highest value, you have to use @Remou's method to reset the seed value. This also applies if you want to reset to the Max+1 in a table where records have been deleted, e.g., 300 records, last ID of 300, delete 201-300, compact won't reset the counter (you have to use @Remou's method -- this was not the case in earlier versions of Jet, and, indeed, in early versions of Jet 4, the first Jet version that allowed manipulating the seed value programatically).

Maven: The packaging for this project did not assign a file to the build artifact

This worked for me when I got the same error message...

mvn install deploy

Recursively list all files in a directory including files in symlink directories

Using ls:

  ls -LR

from 'man ls':

   -L, --dereference
          when showing file information for a symbolic link, show informa-
          tion  for  the file the link references rather than for the link
          itself

Or, using find:

find -L .

From the find manpage:

-L     Follow symbolic links.

If you find you want to only follow a few symbolic links (like maybe just the toplevel ones you mentioned), you should look at the -H option, which only follows symlinks that you pass to it on the commandline.

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

None of the previous answers either applied or worked for me. In my case, updating the settings of the test project, as follows, fixed it:

enter image description here

mat-form-field must contain a MatFormFieldControl

You might have missed to import MatInputModule

How do I get the object if it exists, or None if it does not exist?

Since django 1.6 you can use first() method like so:

Content.objects.filter(name="baby").first()

Copying the cell value preserving the formatting from one cell to another in excel using VBA

I prefer to avoid using select

     With sheets("sheetname").range("I10") 
          .PasteSpecial Paste:=xlPasteValues, _
                  Operation:=xlNone, _
                  SkipBlanks:=False, _
                  Transpose:=False
          .PasteSpecial Paste:=xlPasteFormats, _
                  Operation:=xlNone, _
                  SkipBlanks:=False, _
                  Transpose:=False
          .font.color = sheets("sheetname").range("F10").font.color
      End With
      sheets("sheetname").range("I10:J10").merge

Rename MySQL database

I used following method to rename the database

  1. take backup of the file using mysqldump or any DB tool eg heidiSQL,mysql administrator etc

  2. Open back up (eg backupfile.sql) file in some text editor.

  3. Search and replace the database name and save file.

  4. Restore the edited SQL file

html select scroll bar

Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:

1. First create a css class

<style type="text/css">
 .scrollable{
   overflow: auto;
   width: 70px; /* adjust this width depending to amount of text to display */
   height: 80px; /* adjust height depending on number of options to display */
   border: 1px silver solid;
 }
 .scrollable select{
   border: none;
 }
</style>

2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.

<div class="scrollable">
<select size="6" multiple="multiple">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>
</div>

how to return index of a sorted list?

You can do this with numpy's argsort method if you have numpy available:

>>> import numpy
>>> vals = numpy.array([2,3,1,4,5])
>>> vals
array([2, 3, 1, 4, 5])
>>> sort_index = numpy.argsort(vals)
>>> sort_index
array([2, 0, 1, 3, 4])

If not available, taken from this question, this is the fastest method:

>>> vals = [2,3,1,4,5]
>>> sorted(range(len(vals)), key=vals.__getitem__)
[2, 0, 1, 3, 4]

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

try this method

$("your id or class name").css({ 'margin-top': '18px' });  

What is the purpose of a plus symbol before a variable?

The + operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d is a non-zero number.

Reference here. And, as pointed out in comments, here.

Setting Spring Profile variable

In the <tomcat-home>\conf\catalina.properties file, add this new line:

spring.profiles.active=dev

Maximum concurrent Socket.IO connections

This article may help you along the way: http://drewww.github.io/socket.io-benchmarking/

I wondered the same question, so I ended up writing a small test (using XHR-polling) to see when the connections started to fail (or fall behind). I found (in my case) that the sockets started acting up at around 1400-1800 concurrent connections.

This is a short gist I made, similar to the test I used: https://gist.github.com/jmyrland/5535279

how to rename an index in a cluster?

Starting with ElasticSearch 7.4, the best method to rename an index is to copy the index using the newly introduced Clone Index API, then to delete the original index using the Delete Index API.

The main advantage of the Clone Index API over the use of the Snapshot API or the Reindex API for the same purpose is speed, since the Clone Index API hardlinks segments from the source index to the target index, without reprocessing any of its content (on filesystems that support hardlinks, obviously; otherwise, files are copied at the file system level, which is still much more efficient that the alternatives). Clone Index also guarantee that the target index is identical in every point to the source index (that is, there is no need to manually copy settings and mappings, contrary to the Reindex approach), and doesn't require a local snapshot directory be configured.

Side note: even though this procedure is much faster than previous solutions, it still implies down time. There are real use cases that justify renaming indices (for example, as a step in a split, shrink or backup workflow), but renaming indices should not be part of day-to-day operations. If your workflow requires frequent index renaming, then you should consider using Indices Aliases instead.

Here is an example of a complete sequence of operations to rename index source_index to target_index. It can be executed using some ElasticSearch specific console, such as the one integrated in Kibana. See this gist for an alternative version of this example, using curl instead of an Elastic Search console.

# Make sure the source index is actually open
POST /source_index/_open

# Put the source index in read-only mode
PUT /source_index/_settings
{
  "settings": {
    "index.blocks.write": "true"
  }
}

# Clone the source index to the target name, and set the target to read-write mode
POST /source_index/_clone/target_index
{
  "settings": {
    "index.blocks.write": null 
  }
}

# Wait until the target index is green;
# it should usually be fast (assuming your filesystem supports hard links).
GET /_cluster/health/target_index?wait_for_status=green&timeout=30s

# If it appears to be taking too much time for the cluster to get back to green,
# the following requests might help you identify eventual outstanding issues (if any)
GET /_cat/indices/target_index
GET /_cat/recovery/target_index
GET /_cluster/allocation/explain

# Delete the source index
DELETE /source_index

Find Locked Table in SQL Server

You can use sp_lock (and sp_lock2), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks:

select  
    object_name(p.object_id) as TableName, 
    resource_type, resource_description
from
    sys.dm_tran_locks l
    join sys.partitions p on l.resource_associated_entity_id = p.hobt_id

Assign a login to a user created without login (SQL Server)

You have an orphaned user and this can't be remapped with ALTER USER (yet) becauses there is no login to map to. So, you need run CREATE LOGIN first.

If the database level user is

  • a Windows Login, the mapping will be fixed automatcially via the AD SID
  • a SQL Login, use "sid" from sys.database_principals for the SID option for the login

Then run ALTER USER

Edit, after comments and updates

The sid from sys.database_principals is for a Windows login.

So trying to create and re-map to a SQL Login will fail

Run this to get the Windows login

SELECT SUSER_SNAME(0x0105000000000009030000001139F53436663A4CA5B9D5D067A02390)

Editing an item in a list<T>

You don't need to use linq since List<T> provides the methods to do this:

int index = lst.FindLastIndex(c => c.Number == textBox6.Text);
if(index != -1)
{
    lst[index] = new Class1() { ... };
}

Confusing "duplicate identifier" Typescript error message

You could also use the exclude option in tsconfig.json file like so:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "noLib": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "exclude": [
    "node_modules"
  ]
}

Convert string to int if string is a number

Just use Val():

currentLoad = Int(Val([f4]))

Now currentLoad has a integer value, zero if [f4] is not numeric.

HTML.ActionLink vs Url.Action in ASP.NET Razor

I used the code below to create a Button and it worked for me.

<input type="button" value="PDF" onclick="location.href='@Url.Action("Export","tblOrder")'"/>

What's the difference between nohup and ampersand

The nohup command is a signal masking utility and catches the hangup signal. Where as ampersand doesn’t catch the hang up signals. The shell will terminate the sub command with the hang up signal when running a command using & and exiting the shell. This can be prevented by using nohup, as it catches the signal. Nohup command accept hang up signal which can be sent to a process by the kernel and block them. Nohup command is helpful in when a user wants to start long running application log out or close the window in which the process was initiated. Either of these actions normally prompts the kernel to hang up on the application, but a nohup wrapper will allow the process to continue. Using the ampersand will run the command in a child process and this child of the current bash session. When you exit the session, all of the child processes of that process will be killed. The ampersand relates to job control for the active shell. This is useful for running a process in a session in the background.

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

You don't have permission to the Python folder.

sudo chown -R $USER /usr/local/lib/python2.7

How to output a comma delimited list in jinja python template?

You want your if check to be:

{% if not loop.last %}
    ,
{% endif %}

Note that you can also shorten the code by using If Expression:

{{ ", " if not loop.last else "" }}

PHP XML Extension: Not installed

Had the same problem running PHP 7.2. I had to do the following :

sudo apt-get install php7.2-xml

Mockito: Mock private field initialization

Following code can be used to initialize mapper in REST client mock. The mapper field is private and needs to be set during unit test setup.

import org.mockito.internal.util.reflection.FieldSetter;

new FieldSetter(client, Client.class.getDeclaredField("mapper")).set(new Mapper());

Change Title of Javascript Alert

As others have said, you can't do that either using alert()or confirm().

You can, however, create an external HTML document containing your error message and an OK button, set its <title> element to whatever you want, then display it in a modal dialog box using showModalDialog().

TCP: can two different sockets share a port?

No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.

Resize Google Maps marker icon image

MarkerImage has been deprecated for Icon

Until version 3.10 of the Google Maps JavaScript API, complex icons were defined as MarkerImage objects. The Icon object literal was added in 3.10, and replaces MarkerImage from version 3.11 onwards. Icon object literals support the same parameters as MarkerImage, allowing you to easily convert a MarkerImage to an Icon by removing the constructor, wrapping the previous parameters in {}'s, and adding the names of each parameter.

Phillippe's code would now be:

 var icon = {
     url: "../res/sit_marron.png", // url
     scaledSize: new google.maps.Size(width, height), // size
     origin: new google.maps.Point(0,0), // origin
     anchor: new google.maps.Point(anchor_left, anchor_top) // anchor 
 };

 position = new google.maps.LatLng(latitud,longitud)
 marker = new google.maps.Marker({
  position: position,
  map: map,
  icon: icon
 });

node and Error: EMFILE, too many open files

I did installing watchman, changing limit etc. and it didn't work in Gulp.

Restarting iterm2 actually helped though.

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

Along the same lines as previous answers, but a very short addition that Allows to use all Control properties without having cross thread invokation exception.

Helper Method

    /// <summary>
    /// Helper method to determin if invoke required, if so will rerun method on correct thread.
    /// if not do nothing.
    /// </summary>
    /// <param name="c">Control that might require invoking</param>
    /// <param name="a">action to preform on control thread if so.</param>
    /// <returns>true if invoke required</returns>
    public bool ControlInvokeRequired(Control c,Action a)
    {
        if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate { a(); }));
        else return false;

        return true;
    }

Sample Usage

    // usage on textbox
    public void UpdateTextBox1(String text)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(textBox1, () => UpdateTextBox1(text))) return;
        textBox1.Text = ellapsed;
    }

    //Or any control
    public void UpdateControl(Color c,String s)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(myControl, () => UpdateControl(c,s))) return;
        myControl.Text = s;
        myControl.BackColor = c;
    }

Change IPython/Jupyter notebook working directory

A neat trick for those using IPython in windows is that you can make an ipython icon in each of your project directories designed to open with the notebook pointing at that chosen project. This helps keep things separate.

For example if you have a new project in C:\fake\example\directory

Copy an ipython notebook icon to the directory or create a new link to the windows "cmd" shell. Then right click on the icon and "Edit Properties"

Set the shortcut properties to:

Target:
C:\Windows\System32\cmd.exe /k "cd C:\fake\example\directory & C: & ipython notebook --pylab inline"

Start in:
C:\fake\example\directory\

(Note the added slash at the end of "start in")

This runs windows command line, changes to your working directory, and runs the ipython notebook pointed at that directory.

Drop one of these in each project folder and you'll have ipython notebook groups kept nice and separate while still just a doubleclick away.

UPDATE: IPython has removed support for the command line inlining of pylab so the fix for that with this trick is to just eliminate "--pylab inline" if you have a newer IPython version (or just don't want pylab obviously).

UPDATE FOR JUPYTER NOTEBOOK ~ version 4.1.1

On my test machines and as reported in comments below, the newest jupyter build appears to check the start directory and launch with that as the working directory. This means that the working directory override is not needed.

Thus your shortcut can be as simple as:

Target (if jupyter notebook in path):
    jupyter notebook

Target (if jupyter notebook NOT in path):
    C:\Users\<Your Username Here>\Anaconda\Scripts\jupyter.exe notebook

If jupyter notebook is not in your PATH you just need to add the full directory reference in front of the command. If that doesn't work please try working from the earlier version. Very conveniently, now "Start in:" can be empty in my tests with 4.1.1 and later. Perhaps they read this entry on SO and liked it, so long upvotes, nobody needs this anymore :)

Trusting all certificates using HttpClient over HTTPS

The code above in https://stackoverflow.com/a/6378872/1553004 is correct, except it MUST also call the hostname verifier:

    @Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
    SSLSocket sslSocket = (SSLSocket)sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    getHostnameVerifier().verify(host, sslSocket);
    return sslSocket;
}

I signed up to stackoverflow expressly to add this fix. Heed my warning!

connecting to phpMyAdmin database with PHP/MySQL

Set up a user, a host the user is allowed to talk to MySQL by using (e.g. localhost), grant that user adequate permissions to do what they need with the database .. and presto.

The user will need basic CRUD privileges to start, that's sufficient to store data received from a form. The rest of the permissions are self explanatory, i.e. permission to alter tables, etc. Give the user no more, no less power than it needs to do its work.

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

In newer versions of Git for Windows, Bash is started with --login which causes Bash to not read .bashrc directly. Instead it reads .bash_profile.

If this file does not exist, create it with the following content:

if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

This will cause Bash to read the .bashrc file. From my understanding of this issue, Git for Windows should do this automatically. However, I just installed version 2.5.1, and it did not.

How can I get the first two digits of a number?

Comparing the O(n) time solution with the "constant time" O(1) solution provided in other answers goes to show that if the O(n) algorithm is fast enough, n may have to get very large before it is slower than a slow O(1).

The strings version is approx. 60% faster than the "maths" version for numbers of 20 or fewer digits. They become closer only when then number of digits approaches 200 digits

# the "maths" version
import math

def first_n_digits1(num, n):
    return num // 10 ** (int(math.log(num, 10)) - n + 1)

%timeit first_n_digits1(34523452452, 2)
1.21 µs ± 75 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits1(34523452452, 8)
1.24 µs ± 47.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 22 digits
%timeit first_n_digits1(3423234239472523452452, 2)
1.33 µs ± 59.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits1(3423234239472523452452, 15)
1.23 µs ± 61.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 196 digits
%timeit first_n_digits1(3423234239472523409283475908723908723409872390871243908172340987123409871234012089172340987734507612340981344509873123401234670350981234098123140987314509812734091823509871345109871234098172340987125988123452452, 39)
1.86 µs ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

# The "string" verions
def first_n_digits2(num, n):
    return int(str(num)[:n])

%timeit first_n_digits2(34523452452, 2)
744 ns ± 28.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits2(34523452452, 8)
768 ns ± 42.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 22 digits
%timeit first_n_digits2(3423234239472523452452, 2)
767 ns ± 33.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits2(3423234239472523452452, 15)
830 ns ± 55.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 196 digits
%timeit first_n_digits2(3423234239472523409283475908723908723409872390871243908098712340987123401208917234098773450761234098134450987312340123467035098123409812314098734091823509871345109871234098172340987125988123452452, 39)
1.87 µs ± 140 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

SelectedValue vs SelectedItem.Value of DropDownList

One important distinction between the two (which is visible in the Reflected code) is that SelectedValue will return an empty string if a nothing is selected, whereas SelectedItem.Value will throw a NullReference exception.

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

The connect router has now been removed (https://github.com/senchalabs/connect/issues/262), the author stating that you should use a framework on top of connect (like Express) for routing.

Express currently treats app.get("/foo*") as app.get(/\/foo(.*)/), removing the need for two separate routes. This is in contrast to the previous answer (referring to the now removed connect router) which stated that "* in a path is replaced with .+".

Update: Express now uses the "path-to-regexp" module (since Express 4.0.0) which maintains the same behavior in the version currently referenced. It's unclear to me whether the latest version of that module keeps the behavior, but for now this answer stands.

What happened to console.log in IE8?

Make your own console in html .... ;-) This can be imprved but you can start with :

if (typeof console == "undefined" || typeof console.log === "undefined") {
    var oDiv=document.createElement("div");
    var attr = document.createAttribute('id'); attr.value = 'html-console';
    oDiv.setAttributeNode(attr);


    var style= document.createAttribute('style');
    style.value = "overflow: auto; color: red; position: fixed; bottom:0; background-color: black; height: 200px; width: 100%; filter: alpha(opacity=80);";
    oDiv.setAttributeNode(style);

    var t = document.createElement("h3");
    var tcontent = document.createTextNode('console');
    t.appendChild(tcontent);
    oDiv.appendChild(t);

    document.body.appendChild(oDiv);
    var htmlConsole = document.getElementById('html-console');
    window.console = {
        log: function(message) {
            var p = document.createElement("p");
            var content = document.createTextNode(message.toString());
            p.appendChild(content);
            htmlConsole.appendChild(p);
        }
    };
}

python catch exception and continue try block

You can achieve what you want, but with a different syntax. You can use a "finally" block after the try/except. Doing this way, python will execute the block of code regardless the exception was thrown, or not.

Like this:

try:
    do_smth1()
except:
    pass
finally:
    do_smth2()

But, if you want to execute do_smth2() only if the exception was not thrown, use a "else" block:

try:
    do_smth1()
except:
    pass
else:
    do_smth2()

You can mix them too, in a try/except/else/finally clause. Have fun!

Export and import table dump (.sql) using pgAdmin

follow he steps. in pgadmin

host-DataBase-Schemas- public (click right) CREATE script- open file -(choose xxx.sql) , then click over the option execute query write result to file -export data file ok- then click in save.its all. it work to me.

note: error in version command script enter image description herede sql over pgadmin can be search, example: http://www.forosdelweb.com/f21/campo-tipo-datetime-postgresql-245389/

enter image description here

Should have subtitle controller already set Mediaplayer error Android

Also you can only set mediaPlayer.reset() and in onDestroy set it to release.

Understanding "VOLUME" instruction in DockerFile

The VOLUME command in a Dockerfile is quite legit, totally conventional, absolutely fine to use and it is not deprecated in anyway. Just need to understand it.

We use it to point to any directories which the app in the container will write to a lot. We don't use VOLUME just because we want to share between host and container like a config file.

The command simply needs one param; a path to a folder, relative to WORKDIR if set, from within the container. Then docker will create a volume in its graph(/var/lib/docker) and mount it to the folder in the container. Now the container will have somewhere to write to with high performance. Without the VOLUME command the write speed to the specified folder will be very slow because now the container is using it's copy on write strategy in the container itself. The copy on write strategy is a main reason why volumes exist.

If you mount over the folder specified by the VOLUME command, the command is never run because VOLUME is only executed when the container starts, kind of like ENV.

Basically with VOLUME command you get performance without externally mounting any volumes. Data will save across container runs too without any external mounts. Then when ready simply mount something over it.

Some good example use cases:
- logs
- temp folders

Some bad use cases:
- static files
- configs
- code

How to filter JSON Data in JavaScript or jQuery?

You can use jQuery each function as it is explained below:

Define your data:

var jsonStr = '[{"name":"Lenovo Thinkpad 41A4298,"website":"google"},{"name":"Lenovo Thinkpad 41A2222,"website":"google"},{"name":"Lenovo Thinkpad 41Awww33,"website":"yahoo"},{"name":"Lenovo Thinkpad 41A424448,"website":"google"},{"name":"Lenovo Thinkpad 41A429rr8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ff8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ss8,"website":"rediff"},{"name":"Lenovo Thinkpad 41A429sg8,"website":"yahoo"}]';

Parse JSON string to JSON object:

var json = JSON.parse(jsonStr);

Iterate and filter:

$.each(JSON.parse(json), function (idx, obj) {
    if (obj.website == 'yahoo') {
        // do whatever you want
    }
});

HTML display result in text (input) field?

With .value and INPUT tag

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').value = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
    </FORM>

  </BODY>
</HTML>

with innerHTML and DIV

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').innerHTML = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <DIV  ID="add"></DIV>
    </FORM>

  </BODY>
</HTML>

How to retrieve available RAM from Windows command line?

This cannot be done in pure java. But you can run external programs using java and get the result.

Process p=Runtime.getRuntime().exec("systeminfo");
Scanner scan=new Scanner(p.getInputStream());
while(scan.hasNext()){
    String temp=scan.nextLine();
    if(temp.equals("Available Physical Memmory")){
       System.out.println("RAM :"temp.split(":")[1]);
       break;
    }
}

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

the following will do:

date -d "$(date +%Y-%m-1) -1 month" +%-m
date -d "$(date +%Y-%m-1) 0 month" +%-m
date -d "$(date +%Y-%m-1) 1 month" +%-m

or as you need:

LAST_MONTH=`date -d "$(date +%Y-%m-1) -1 month" +%-m`
NEXT_MONTH=`date -d "$(date +%Y-%m-1) 1 month" +%-m`
THIS_MONTH=`date -d "$(date +%Y-%m-1) 0 month" +%-m`

you asked for output like 9,10,11, so I used the %-m

%m (without -) will produce output like 09,... (leading zero)

this also works for more/less than 12 months:

date -d "$(date +%Y-%m-1) -13 month" +%-m

just try

date -d "$(date +%Y-%m-1) -13 month"

to see full result

ADB No Devices Found

It was a bad USB cable for me. After trying a suite of solutions, I changed to a different USB cable and my device showed up.

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

ESLint not working in VS Code?

If ESLint is running in the terminal but not inside VSCode, it is probably because the extension is unable to detect both the local and the global node_modules folders.

To verify, press Ctrl+Shift+U in VSCode to open the Output panel after opening a JavaScript file with a known eslint issue. If it shows Failed to load the ESLint library for the document {documentName}.js -or- if the Problems tab shows an error or a warning that refers to eslint, then VSCode is having a problem trying to detect the path.

If yes, then set it manually by configuring the eslint.nodePath in the VSCode settings (settings.json). Give it the full path (for example, like "eslint.nodePath": "C:\\Program Files\\nodejs",) -- using environment variables is currently not supported.
This option has been documented at the ESLint extension page.

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

There is a lot of nice answers here using analogies but a friend at work gave me an example that I liked more than all of the ones mentioned here... Eyes and Glasses!

Tight Coupling

Tight coupling would be the eyes. If I want to fix my vision, I'ts very expensive to get an eye transplant and holds a fair amount of risk. But what if the designer (being the human race) found a better way. Add a feature that is loosely coupled to the body so it can be easily changed! (yes.. glasses)

Loose coupling

I can easily replace my glasses without breaking my underlying vision. I can take off the glasses and my vision will be how it was before (not better or worse). Using different pairs of glasses changes how we see the world through our eyes with little risk and easy maintainability.

Summary

So next time someone asks you "who cares if my code is tightly-coupled?" The answer is all about effort to change, effort to maintain and risk of change.

So how is this done in C#? Interfaces and Dependency Injection!

EDIT

This a good example of the Decorator pattern as well, where the the eyes are the class we are decorating by meeting interface requirements but giving different functionality (e.g. sunglasses, reading glasses, magnifying glasses for jewelers e.t.c)

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

With the GnuWin32 tools I found the openssl.cnf under C:\gnuwin32\share

set OPENSSL_CONF=C:\gnuwin32\share\openssl.cnf

Installing Java on OS X 10.9 (Mavericks)

The new Mavericks (10.9) showed me the "Requesting install", but nothing happened.

The solution was to manually download and install the official Java package for OS X, which is in Java for OS X 2013-005.

Update: As mentioned in the comments below, there is a newer version of this same package:

Java for OS X 2014-001

Java for OS X 2014-001 (Correcting dead line above)

Java for OS X 2014-001 includes installation improvements, and supersedes all previous versions of Java for OS X. This package installs the same version of Java 6 included in Java for OS X 2013-005.

The requested URL /about was not found on this server

It worked for me like this:

Go to Wordpress Admin Dashboard > “Settings” > “Permalinks” > “Common settings”, set the radio button to “Custom Structure” and paste into the text box:

/index.php/%year%/%monthnum%/%day%/%postname%/

and click the Save button.

I got this solution from this link

Solving a "communications link failure" with JDBC and MySQL

In case you are having problem with a set of Docker containers, then make sure that you do not only EXPOSE the port 3306, but as well map the port from outside the container -p 3306:3306. For docker-compose.yml:

version: '2'

services:
    mdb:
        image: mariadb:10.1
        ports:
            - "3306:3306"
        …

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

Count how many files in directory PHP

<?php echo(count(array_slice(scandir($directory),2))); ?>

array_slice works similary like substr function, only it works with arrays.

For example, this would chop out first two array keys from array:

$key_zero_one = array_slice($someArray, 0, 2);

And if You ommit the first parameter, like in first example, array will not contain first two key/value pairs *('.' and '..').

Remove Item in Dictionary based on Value

Here is a method you can use:

    public static void RemoveAllByValue<K, V>(this Dictionary<K, V> dictionary, V value)
    {
        foreach (var key in dictionary.Where(
                kvp => EqualityComparer<V>.Default.Equals(kvp.Value, value)).
                Select(x => x.Key).ToArray())
            dictionary.Remove(key);
    }

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

! [rejected] master -> master (fetch first)

this work for me

  1. git init

  2. git add --all

3.git commit -m "name"

4.git push origin master --force

Returning from a void function

The first way is "more correct", what intention could there be to express? If the code ends, it ends. That's pretty clear, in my opinion.

I don't understand what could possibly be confusing and need clarification. If there's no looping construct being used, then what could possibly happen other than that the function stops executing?

I would be severly annoyed by such a pointless extra return statement at the end of a void function, since it clearly serves no purpose and just makes me feel the original programmer said "I was confused about this, and now you can be too!" which is not very nice.

What is the difference between screenX/Y, clientX/Y and pageX/Y?

What helped me was to add an event directly to this page and click around for myself! Open up your console in developer tools/Firebug etc and paste this:

_x000D_
_x000D_
document.addEventListener('click', function(e) {_x000D_
  console.log(_x000D_
    'page: ' + e.pageX + ',' + e.pageY,_x000D_
    'client: ' + e.clientX + ',' + e.clientY,_x000D_
    'screen: ' + e.screenX + ',' + e.screenY)_x000D_
}, false);
_x000D_
Click anywhere
_x000D_
_x000D_
_x000D_

With this snippet, you can track your click position as you scroll, move the browser window, etc.

Notice that pageX/Y and clientX/Y are the same when you're scrolled all the way to the top!

Android: Vertical alignment for multi line EditText (Text area)

Use this:

android:gravity="top"

or

android:gravity="top|left"

Logging with Retrofit 2

Kotlin Code

        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
        val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        return retrofit.create(PointApi::class.java)

return, return None, and no return at all?

Yes, they are all the same.

We can review the interpreted machine code to confirm that that they're all doing the exact same thing.

import dis

def f1():
  print "Hello World"
  return None

def f2():
  print "Hello World"
  return

def f3():
  print "Hello World"

dis.dis(f1)
    4   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    5   5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f2)
    9   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    10  5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f3)
    14  0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE            
        5 LOAD_CONST    0 (None)
        8 RETURN_VALUE      

How to deal with floating point number precision in JavaScript?

You just have to make up your mind on how many decimal digits you actually want - can't have the cake and eat it too :-)

Numerical errors accumulate with every further operation and if you don't cut it off early it's just going to grow. Numerical libraries which present results that look clean simply cut off the last 2 digits at every step, numerical co-processors also have a "normal" and "full" lenght for the same reason. Cuf-offs are cheap for a processor but very expensive for you in a script (multiplying and dividing and using pov(...)). Good math lib would provide floor(x,n) to do the cut-off for you.

So at the very least you should make global var/constant with pov(10,n) - meaning that you decided on the precision you need :-) Then do:

Math.floor(x*PREC_LIM)/PREC_LIM  // floor - you are cutting off, not rounding

You could also keep doing math and only cut-off at the end - assuming that you are only displaying and not doing if-s with results. If you can do that, then .toFixed(...) might be more efficient.

If you are doing if-s/comparisons and don't want to cut of then you also need a small constant, usually called eps, which is one decimal place higher than max expected error. Say that your cut-off is last two decimals - then your eps has 1 at the 3rd place from the last (3rd least significant) and you can use it to compare whether the result is within eps range of expected (0.02 -eps < 0.1*0.2 < 0.02 +eps).

How to draw checkbox or tick mark in GitHub Markdown table?

Now emojis are supported! :white_check_mark: / :heavy_check_mark: gives a good impression and is widely supported:

Function | MySQL / MariaDB | PostgreSQL | SQLite
:------------ | :-------------| :-------------| :-------------
substr | :heavy_check_mark: |  :white_check_mark: | :heavy_check_mark:

renders to (here on older chromium 65.0.3x) :

enter image description here

How to delete specific columns with VBA?

You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.

Sub deleteCol()

On Error Resume Next

Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer

Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
    If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
        wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
    End If
Next i

End Sub

With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.

EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) change the "1" in Cells(1, i) to whatever row your headers are in.

EDIT 2: Changed the For section of the code to account for completely empty columns.

How to save python screen output to a text file

Let me summarize all the answers and add some more.

  • To write to a file from within your script, user file I/O tools that are provided by Python (this is the f=open('file.txt', 'w') stuff.

  • If don't want to modify your program, you can use stream redirection (both on windows and on Unix-like systems). This is the python myscript > output.txt stuff.

  • If you want to see the output both on your screen and in a log file, and if you are on Unix, and you don't want to modify your program, you may use the tee command (windows version also exists, but I have never used it)

  • Even better way to send the desired output to screen, file, e-mail, twitter, whatever is to use the logging module. The learning curve here is the steepest among all the options, but in the long run it will pay for itself.

Plot two graphs in same plot in R

tl;dr: You want to use curve (with add=TRUE) or lines.


I disagree with par(new=TRUE) because that will double-print tick-marks and axis labels. Eg

sine and parabola

The output of plot(sin); par(new=T); plot( function(x) x**2 ).

Look how messed up the vertical axis labels are! Since the ranges are different you would need to set ylim=c(lowest point between the two functions, highest point between the two functions), which is less easy than what I'm about to show you---and way less easy if you want to add not just two curves, but many.


What always confused me about plotting is the difference between curve and lines. (If you can't remember that these are the names of the two important plotting commands, just sing it.)

Here's the big difference between curve and lines.

curve will plot a function, like curve(sin). lines plots points with x and y values, like: lines( x=0:10, y=sin(0:10) ).

And here's a minor difference: curve needs to be called with add=TRUE for what you're trying to do, while lines already assumes you're adding to an existing plot.

id & sine

Here's the result of calling plot(0:2); curve(sin).


Behind the scenes, check out methods(plot). And check body( plot.function )[[5]]. When you call plot(sin) R figures out that sin is a function (not y values) and uses the plot.function method, which ends up calling curve. So curve is the tool meant to handle functions.

Listen to changes within a DIV and act accordingly

Though the event DOMSubtreeModified is deprecated, its working as of now, so for any makeshift projects you can use it as following.

$("body").on('DOMSubtreeModified', "#mydiv", function() {
    alert('changed');
});

In the long term though, you'll have to use the MutationObserver API.

How do I pass a value from a child back to the parent form?

Many ways to skin the cat here and @Mitch's suggestion is a good way. If you want the client form to have more 'control', you may want to pass the instance of the parent to the child when created and then you can call any public parent method on the child.

Remove empty elements from an array in Javascript

foo = [0, 1, 2, "", , false, 3, "four", null]

foo.filter(function(e) {
    return e === 0 ? '0' : e
})

returns

[0, 1, 2, 3, "four"]

What does EntityManager.flush do and why do I need to use it?

A call to EntityManager.flush(); will force the data to be persist in the database immediately as EntityManager.persist() will not (depending on how the EntityManager is configured : FlushModeType (AUTO or COMMIT) by default it's set to AUTO and a flush will be done automatically by if it's set to COMMIT the persitence of the data to the underlying database will be delayed when the transaction is commited).

How do I prevent an Android device from going to sleep programmatically?

I found another working solution: add the following line to your app under the onCreate event.

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

My sample Cordova project looks like this:

package com.apps.demo;
import android.os.Bundle;
import android.view.WindowManager;
import org.apache.cordova.*;

public class ScanManActivity extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.loadUrl("http://stackoverflow.com");
    }
}

After that, my app would not go to sleep while it was open. Thanks for the anwer goes to xSus.

How to detect Esc Key Press in React and how to handle it

React uses SyntheticKeyboardEvent to wrap native browser event and this Synthetic event provides named key attribute,
which you can use like this:

handleOnKeyDown = (e) => {
  if (['Enter', 'ArrowRight', 'Tab'].includes(e.key)) {
    // select item
    e.preventDefault();
  } else if (e.key === 'ArrowUp') {
    // go to top item
    e.preventDefault();
  } else if (e.key === 'ArrowDown') {
    // go to bottom item
    e.preventDefault();
  } else if (e.key === 'Escape') {
    // escape
    e.preventDefault();
  }
};

How do I compile jrxml to get jasper?

Using Version 5.1.0:

Just click preview and it will create a YourReportName.jasper for you in the same working directory.

How to make the 'cut' command treat same sequental delimiters as one?

Try:

tr -s ' ' <text.txt | cut -d ' ' -f4

From the tr man page:

-s, --squeeze-repeats   replace each input sequence of a repeated character
                        that is listed in SET1 with a single occurrence
                        of that character

Make div (height) occupy parent remaining height

check the demo - http://jsfiddle.net/S8g4E/6/

use css -

#container { width: 300px; height: 300px; border:1px solid red; display: table;}
#up { background: green; display: table-row; }
#down { background:pink; display: table-row;}

How to filter (key, value) with ng-repeat in AngularJs?

Angular filters can only be applied to arrays and not objects, from angular's API -

"Selects a subset of items from array and returns it as a new array."

You have two options here:
1) move $scope.items to an array or -
2) pre-filter the ng-repeat items, like this:

<div ng-repeat="(k,v) in filterSecId(items)">
    {{k}} {{v.pos}}
</div>

And on the Controller:

$scope.filterSecId = function(items) {
    var result = {};
    angular.forEach(items, function(value, key) {
        if (!value.hasOwnProperty('secId')) {
            result[key] = value;
        }
    });
    return result;
}

jsfiddle: http://jsfiddle.net/bmleite/WA2BE/

Android SQLite: Update Statement

You can use the code below.

String strFilter = "_id=" + Id;
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
myDB.update("titles", args, strFilter, null);

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

Python strip() multiple characters?

For example string s="(U+007c)"

To remove only the parentheses from s, try the below one:

import re
a=re.sub("\\(","",s)
b=re.sub("\\)","",a)
print(b)

How to schedule a periodic task in Java?

You should take a look to Quartz it's a java framework wich works with EE and SE editions and allows to define jobs to execute an specific time

Convert List(of object) to List(of string)

List<string> myList Str = myList.Select(x=>x.Value).OfType<string>().ToList();

Use "Select" to select a particular column

How does Java handle integer underflows and overflows and how would you check for it?

If it overflows, it goes back to the minimum value and continues from there. If it underflows, it goes back to the maximum value and continues from there.

You can check that beforehand as follows:

public static boolean willAdditionOverflow(int left, int right) {
    if (right < 0 && right != Integer.MIN_VALUE) {
        return willSubtractionOverflow(left, -right);
    } else {
        return (~(left ^ right) & (left ^ (left + right))) < 0;
    }
}

public static boolean willSubtractionOverflow(int left, int right) {
    if (right < 0) {
        return willAdditionOverflow(left, -right);
    } else {
        return ((left ^ right) & (left ^ (left - right))) < 0;
    }
}

(you can substitute int by long to perform the same checks for long)

If you think that this may occur more than often, then consider using a datatype or object which can store larger values, e.g. long or maybe java.math.BigInteger. The last one doesn't overflow, practically, the available JVM memory is the limit.


If you happen to be on Java8 already, then you can make use of the new Math#addExact() and Math#subtractExact() methods which will throw an ArithmeticException on overflow.

public static boolean willAdditionOverflow(int left, int right) {
    try {
        Math.addExact(left, right);
        return false;
    } catch (ArithmeticException e) {
        return true;
    }
}

public static boolean willSubtractionOverflow(int left, int right) {
    try {
        Math.subtractExact(left, right);
        return false;
    } catch (ArithmeticException e) {
        return true;
    }
}

The source code can be found here and here respectively.

Of course, you could also just use them right away instead of hiding them in a boolean utility method.

Match the path of a URL, minus the filename extension

A regular expression might not be the most effective tool for this job.

Try using parse_url(), combined with pathinfo():

$url      = 'http://php.net/manual/en/function.preg-match.php';
$path     = parse_url($url, PHP_URL_PATH);
$pathinfo = pathinfo($path);

echo $pathinfo['dirname'], '/', $pathinfo['filename'];

The above code outputs:

/manual/en/function.preg-match

How can I display the current branch and folder path in terminal?

It's not about a plugin. It's about prompt tricks in the shell.

For a cool setup in bash, check out the dotfiles project of this guy:

https://github.com/mathiasbynens/dotfiles

To get a fancy prompt, include the .bash_prompt in your ~/.bash_profile or ~/.bashrc.

To get the exact same prompt as in your question, change the export PS1 line at the end of .bash_prompt like this:

export PS1="\[${BOLD}${MAGENTA}\]\u\[$WHITE\]@\[$ORANGE\]\h\[$WHITE\]: [\[$GREEN\]\w\[$WHITE\]\$([[ -n \$(git branch 2> /dev/null) ]] && echo \" - \")\[$PURPLE\]\$(parse_git_branch)\[$WHITE\]] \$ \[$RESET\]"

I ended up using all the .bash* files from this repository about a month ago, and it's been really useful for me.

For Git, there are extra goodies in .gitconfig.

And since you're a mac user, there are even more goodies in .osx.

JFrame: How to disable window resizing?

You can use this.setResizable(false); or frameObject.setResizable(false);

How to make <div> fill <td> height

CSS height: 100% only works if the element's parent has an explicitly defined height. For example, this would work as expected:

td {
    height: 200px;
}

td div {
    /* div will now take up full 200px of parent's height */
    height: 100%;
}

Since it seems like your <td> is going to be variable height, what if you added the bottom right icon with an absolutely positioned image like so:

.thatSetsABackgroundWithAnIcon {
    /* Makes the <div> a coordinate map for the icon */
    position: relative;

    /* Takes the full height of its parent <td>.  For this to work, the <td>
       must have an explicit height set. */
    height: 100%;
}

.thatSetsABackgroundWithAnIcon .theIcon {        
    position: absolute;
    bottom: 0;
    right: 0;
}

With the table cell markup like so:

<td class="thatSetsABackground">  
  <div class="thatSetsABackgroundWithAnIcon">    
    <dl>
      <dt>yada
      </dt>
      <dd>yada
      </dd>
    </dl>
    <img class="theIcon" src="foo-icon.png" alt="foo!"/>
  </div>
</td>

Edit: using jQuery to set div's height

If you keep the <div> as a child of the <td>, this snippet of jQuery will properly set its height:

// Loop through all the div.thatSetsABackgroundWithAnIcon on your page
$('div.thatSetsABackgroundWithAnIcon').each(function(){
    var $div = $(this);

    // Set the div's height to its parent td's height
    $div.height($div.closest('td').height());
});

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

Nice Explanation from http://www.programmerinterview.com/index.php/data-structures/dfs-vs-bfs/

An example of BFS

Here’s an example of what a BFS would look like. This is something like Level Order Tree Traversal where we will use QUEUE with ITERATIVE approach (Mostly RECURSION will end up with DFS). The numbers represent the order in which the nodes are accessed in a BFS:

enter image description here

In a depth first search, you start at the root, and follow one of the branches of the tree as far as possible until either the node you are looking for is found or you hit a leaf node ( a node with no children). If you hit a leaf node, then you continue the search at the nearest ancestor with unexplored children.

An example of DFS

Here’s an example of what a DFS would look like. I think post order traversal in binary tree will start work from the Leaf level first. The numbers represent the order in which the nodes are accessed in a DFS:

enter image description here

Differences between DFS and BFS

Comparing BFS and DFS, the big advantage of DFS is that it has much lower memory requirements than BFS, because it’s not necessary to store all of the child pointers at each level. Depending on the data and what you are looking for, either DFS or BFS could be advantageous.

For example, given a family tree if one were looking for someone on the tree who’s still alive, then it would be safe to assume that person would be on the bottom of the tree. This means that a BFS would take a very long time to reach that last level. A DFS, however, would find the goal faster. But, if one were looking for a family member who died a very long time ago, then that person would be closer to the top of the tree. Then, a BFS would usually be faster than a DFS. So, the advantages of either vary depending on the data and what you’re looking for.

One more example is Facebook; Suggestion on Friends of Friends. We need immediate friends for suggestion where we can use BFS. May be finding the shortest path or detecting the cycle (using recursion) we can use DFS.

Sleep/Wait command in Batch

You want to use timeout. timeout 10 will sleep 10 seconds

How do you easily horizontally center a <div> using CSS?

Please use the below code and your div will be in the center.

.class-name {
    display:block;
    margin:0 auto;
}

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

including parameters in OPENQUERY

SELECT field1 FROM OPENQUERY 
                   ([NameOfLinkedSERVER], 
                   'SELECT field1 FROM TABLENAME') 
                           WHERE field1=@someParameter T1 
                                 INNER JOIN MYSQLSERVER.DATABASE.DBO.TABLENAME           
                                 T2 ON T1.PK = T2.PK

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

If you're using transitioningDelegate (not the case in this question's example), also set modalPresentationStyle to .Custom.

Swift

let vc = storyboard.instantiateViewControllerWithIdentifier("...")
vc.transitioningDelegate = self
vc.modalPresentationStyle = .Custom

How to use MapView in android using google map V2?

yes you can use MapView in v2... for further details you can get help from this

https://gist.github.com/joshdholtz/4522551


SomeFragment.java

public class SomeFragment extends Fragment implements OnMapReadyCallback{
 
    MapView mapView;
    GoogleMap map;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.some_layout, container, false);
 
        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
 
    
        mapView.getMapAsync(this);
        
 
        return v;
    }
 
   @Override
   public void onMapReady(GoogleMap googleMap) {
       map = googleMap;
       map.getUiSettings().setMyLocationButtonEnabled(false);
       map.setMyLocationEnabled(true);
       /*
       //in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
        try {
            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        } 
       */
        
        // Updates the location and zoom of the MapView
        /*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
        map.animateCamera(cameraUpdate);*/
        map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));

    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
 
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
 
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    
    <permission
        android:name="com.example.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_key"/>
        
        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
    </application>
 
</manifest>

some_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    
    <com.google.android.gms.maps.MapView android:id="@+id/mapview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" />
 
</LinearLayout>

Why can't I display a pound (£) symbol in HTML?

Use &#163;. I had the same problem and solved it using jQuery:

$(this).text('&amp;#163;');
  • If you try this and it does not work, just change the jQuery methods,
$(this).html('&amp;#163;');
  • This always work in all contexts...

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Add days Oracle SQL

Some disadvantage of "INTERVAL '1' DAY" is that bind variables cannot be used for the number of days added. Instead, numtodsinterval can be used, like in this small example:

select trunc(sysdate) + numtodsinterval(:x, 'day') tag
from dual

See also: NUMTODSINTERVAL in Oracle Database Online Documentation

How can I find whitespace in a String?

Use org.apache.commons.lang.StringUtils.

  1. to search for whitespaces

boolean withWhiteSpace = StringUtils.contains("my name", " ");

  1. To delete all whitespaces in a string

StringUtils.deleteWhitespace(null) = null StringUtils.deleteWhitespace("") = "" StringUtils.deleteWhitespace("abc") = "abc" StringUtils.deleteWhitespace(" ab c ") = "abc"

Simple Android RecyclerView example

Here's a much newer Kotlin solution for this which is much simpler than many of the answers written here, it uses anonymous class.

val items = mutableListOf<String>()

inner class ItemHolder(view: View): RecyclerView.ViewHolder(view) {
    var textField: TextView = view.findViewById(android.R.id.text1) as TextView
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    rvitems.layoutManager = LinearLayoutManager(context)
    rvitems.adapter = object : RecyclerView.Adapter<ItemHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
            return ItemHolder(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false))
        }

        override fun getItemCount(): Int {
            return items.size
        }

        override fun onBindViewHolder(holder: ItemHolder, position: Int) {
            holder.textField.text = items[position]
            holder.textField.setOnClickListener {
                Toast.makeText(context, "Clicked $position", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

I took the liberty to use android.R.layout.simple_list_item_1 as it's simpler. I wanted to simplify it even further and put ItemHolder as an inner class but couldn't quite figure out how to reference it in a type in the outer class parameter.

instantiate a class from a variable in PHP?

If You Use Namespaces

In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.

MyClass.php

namespace com\company\lib;
class MyClass {
}

index.php

namespace com\company\lib;

//Works fine
$i = new MyClass();

$cname = 'MyClass';

//Errors
//$i = new $cname;

//Works fine
$cname = "com\\company\\lib\\".$cname;
$i = new $cname;

Numpy - add row to array

If you can do the construction in a single operation, then something like the vstack-with-fancy-indexing answer is a fine approach. But if your condition is more complicated or your rows come in on the fly, you may want to grow the array. In fact the numpythonic way to do something like this - dynamically grow an array - is to dynamically grow a list:

A = np.array([[1,2,3],[4,5,6]])
Alist = [r for r in A]
for i in range(100):
    newrow = np.arange(3)+i
    if i%5:
        Alist.append(newrow)
A = np.array(Alist)
del Alist

Lists are highly optimized for this kind of access pattern; you don't have convenient numpy multidimensional indexing while in list form, but for as long as you're appending it's hard to do better than a list of row arrays.

How to check if a variable is an integer in JavaScript?

var x = 1.5;
if(!isNaN(x)){
 console.log('Number');
 if(x % 1 == 0){
   console.log('Integer');
 }
}else {
 console.log('not a number');
}

Proper Linq where clauses

The first one will be implemented:

Collection.Where(x => x.Age == 10)
          .Where(x => x.Name == "Fido") // applied to the result of the previous
          .Where(x => x.Fat == true)    // applied to the result of the previous

As opposed to the much simpler (and far fasterpresumably faster):

// all in one fell swoop
Collection.Where(x => x.Age == 10 && x.Name == "Fido" && x.Fat == true)

Custom HTTP Authorization Header

The format defined in RFC2617 is credentials = auth-scheme #auth-param. So, in agreeing with fumanchu, I think the corrected authorization scheme would look like

Authorization: FIRE-TOKEN apikey="0PN5J17HBGZHT7JJ3X82", hash="frJIUN8DYpKDtOLCwo//yllqDzg="

Where FIRE-TOKEN is the scheme and the two key-value pairs are the auth parameters. Though I believe the quotes are optional (from Apendix B of p7-auth-19)...

auth-param = token BWS "=" BWS ( token / quoted-string )

I believe this fits the latest standards, is already in use (see below), and provides a key-value format for simple extension (if you need additional parameters).

Some examples of this auth-param syntax can be seen here...

http://tools.ietf.org/html/draft-ietf-httpbis-p7-auth-19#section-4.4

https://developers.google.com/youtube/2.0/developers_guide_protocol_clientlogin

https://developers.google.com/accounts/docs/AuthSub#WorkingAuthSub

Git push error: "origin does not appear to be a git repository"

Here is how I resolved this issue

Go to the remote repository on Github and copy the project's repository url.

On git bash type: git remote add origin the remote repository url goes here

PHP XML how to output nice format

Tried all the answers but none worked. Maybe it's because I'm appending and removing childs before saving the XML. After a lot of googling found this comment in the php documentation. I only had to reload the resulting XML to make it work.

$outXML = $xml->saveXML(); 
$xml = new DOMDocument(); 
$xml->preserveWhiteSpace = false; 
$xml->formatOutput = true; 
$xml->loadXML($outXML); 
$outXML = $xml->saveXML(); 

Is there a simple JavaScript slider?

Here is a simple slider object for easy to use

pagecolumn_webparts_sliders

How do I set up cron to run a file just once at a specific time?

Try this out to execute a command on 30th March 2011 at midnight:

0 0 30 3 ? 2011  /command

WARNING: As noted in comments, the year column is not supported in standard/default implementations of cron. Please refer to TomOnTime answer below, for a proper way to run a script at a specific time in the future in standard implementations of cron.

How can I tell when HttpClient has timed out?

From http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.timeout.aspx

A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.

You then get access to the Status property, see WebExceptionStatus

Converting milliseconds to a date (jQuery/JavaScript)

Assume the date as milliseconds date is 1526813885836, so you can access the date as string with this sample code:

console.log(new Date(1526813885836).toString());

For clearness see below code:

const theTime = new Date(1526813885836);
console.log(theTime.toString());

How to get complete month name from DateTime

You can use Culture to get month name for your country like:

System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("ar-EG");
string FormatDate = DateTime.Now.ToString("dddd., MMM dd yyyy, hh:MM tt", culture);

Why is IoC / DI not common in Python?

Django makes great use of inversion of control. For instance, the database server is selected by the configuration file, then the framework provides appropriate database wrapper instances to database clients.

The difference is that Python has first-class types. Data types, including classes, are themselves objects. If you want something to use a particular class, simply name the class. For example:

if config_dbms_name == 'postgresql':
    import psycopg
    self.database_interface = psycopg
elif config_dbms_name == 'mysql':
    ...

Later code can then create a database interface by writing:

my_db_connection = self.database_interface()
# Do stuff with database.

Instead of the boilerplate factory functions that Java and C++ need, Python does it with one or two lines of ordinary code. This is the strength of functional versus imperative programming.

Where should I put the log4j.properties file?

As already stated, log4j.properties should be in a directory included in the classpath, I want to add that in a mavenized project a good place can be src/main/resources/log4j.properties

CSS selector - element with a given child

I agree that it is not possible in general.

The only thing CSS3 can do (which helped in my case) is to select elements that have no children:

table td:empty
{
   background-color: white;
}

Or have any children (including text):

table td:not(:empty)
{
   background-color: white;
}

node.js string.replace doesn't work?

If you just want to clobber all of the instances of a substring out of a string without using regex you can using:

    var replacestring = "A B B C D"
    const oldstring = "B";
    const newstring = "E";
    while (replacestring.indexOf(oldstring) > -1) {
        replacestring = replacestring.replace(oldstring, newstring);
    }        
    //result: "A E E C D"

How to use double or single brackets, parentheses, curly braces

The difference between test, [ and [[ is explained in great details in the BashFAQ.

To cut a long story short: test implements the old, portable syntax of the command. In almost all shells (the oldest Bourne shells are the exception), [ is a synonym for test (but requires a final argument of ]). Although all modern shells have built-in implementations of [, there usually still is an external executable of that name, e.g. /bin/[.

[[ is a new improved version of it, which is a keyword, not a program. This has beneficial effects on the ease of use, as shown below. [[ is understood by KornShell and BASH (e.g. 2.03), but not by the older POSIX or BourneShell.

And the conclusion:

When should the new test command [[ be used, and when the old one [? If portability to the BourneShell is a concern, the old syntax should be used. If on the other hand the script requires BASH or KornShell, the new syntax is much more flexible.

How to render an array of objects in React?

https://facebook.github.io/react/docs/jsx-in-depth.html#javascript-expressions

You can pass any JavaScript expression as children, by enclosing it within {}. For example, these expressions are equivalent:

<MyComponent>foo</MyComponent>

<MyComponent>{'foo'}</MyComponent>

This is often useful for rendering a list of JSX expressions of arbitrary length. For example, this renders an HTML list:

function Item(props) {
  return <li>{props.message}</li>;
}

function TodoList() {
  const todos = ['finish doc', 'submit pr', 'nag dan to review'];
  return (
    <ul>
      {todos.map((message) => <Item key={message} message={message} />)}
    </ul>
  );
}

_x000D_
_x000D_
class First extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.state = {_x000D_
      data: [{name: 'bob'}, {name: 'chris'}],_x000D_
    };_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    return (_x000D_
      <ul>_x000D_
        {this.state.data.map(d => <li key={d.name}>{d.name}</li>)}_x000D_
      </ul>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <First />,_x000D_
  document.getElementById('root')_x000D_
);_x000D_
  
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Node - how to run app.js?

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Local package.json exists, but node_modules missing

npm start runs a script that the app maker built for easy starting of the app npm install installs all the packages in package.json

run npm install first

then run npm start

What is the bower (and npm) version syntax?

Bower uses semver syntax, but here are a few quick examples:

You can install a specific version:

$ bower install jquery#1.11.1

You can use ~ to specify 'any version that starts with this':

$ bower install jquery#~1.11

You can specify multiple version requirements together:

$ bower install "jquery#<2.0 >1.10"

What is the difference between Set and List?

Ordering... a list has an order, a set does not.

How to get last key in an array?

I just took the helper-function from Xander and improved it with the answers before:

function last($array){
  $keys = array_keys($array);
  return end($keys);
}


$arr = array("one" => "apple", "two" => "orange", "three" => "pear");    
echo last($arr);
echo $arr(last($arr));

The calling thread cannot access this object because a different thread owns it

this happened with me because I tried to access UI component in another thread insted of UI thread

like this

private void button_Click(object sender, RoutedEventArgs e)
{
    new Thread(SyncProcces).Start();
}

private void SyncProcces()
{
    string val1 = null, val2 = null;
    //here is the problem 
    val1 = textBox1.Text;//access UI in another thread
    val2 = textBox2.Text;//access UI in another thread
    localStore = new LocalStore(val1);
    remoteStore = new RemoteStore(val2);
}

to solve this problem, wrap any ui call inside what Candide mentioned above in his answer

private void SyncProcces()
{
    string val1 = null, val2 = null;
    this.Dispatcher.Invoke((Action)(() =>
    {//this refer to form in WPF application 
        val1 = textBox.Text;
        val2 = textBox_Copy.Text;
    }));
    localStore = new LocalStore(val1);
    remoteStore = new RemoteStore(val2 );
}

How to make a simple modal pop up form using jquery and html?

I have placed here complete bins for above query. you can check demo link too.

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

HTML

<div id="panel">
  <input type="button" class="button" value="1" id="btn1">
  <input type="button" class="button" value="2" id="btn2">
  <input type="button" class="button" value="3" id="btn3">
  <br>
  <input type="text" id="valueFromMyModal">
  <!-- Dialog Box-->
  <div class="dialog" id="myform">
    <form>
      <label id="valueFromMyButton">
      </label>
      <input type="text" id="name">
      <div align="center">
        <input type="button" value="Ok" id="btnOK">
      </div>
    </form>
  </div>
</div>

JQuery

$(function() {
    $(".button").click(function() {
        $("#myform #valueFromMyButton").text($(this).val().trim());
        $("#myform input[type=text]").val('');
        $("#myform").show(500);
    });
    $("#btnOK").click(function() {
        $("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
        $("#myform").hide(400);
    });
});

CSS

.button{
  border:1px solid #333;
  background:#6479fd;
}
.button:hover{
  background:#a4a9fd;
}
.dialog{
  border:5px solid #666;
  padding:10px;
  background:#3A3A3A;
  position:absolute;
  display:none;
}
.dialog label{
  display:inline-block;
  color:#cecece;
}
input[type=text]{
  border:1px solid #333;
  display:inline-block;
  margin:5px;
}
#btnOK{
  border:1px solid #000;
  background:#ff9999;
  margin:5px;
}

#btnOK:hover{
  border:1px solid #000;
  background:#ffacac;
}

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

How can I specify the default JVM arguments for programs I run from eclipse?

Yes, right click the project. Click Run as then Run Configurations. You can change the parameters passed to the JVM in the Arguments tab in the VM Arguments box.

That configuration can then be used as the default when running the project.