Programs & Examples On #Stringescapeutils

Connect Android Studio with SVN

Go to File->Settings->Version Control->Subversion enter the path for your SVN executable in the General tab under Subversion configuration directory. Also, you can download a latest SVN client such as VisualSVN and point the path to the executable as mentioned above. That will most likely solve your problem.

Storing Objects in HTML5 localStorage

localStorage.setItem('user', JSON.stringify(user));

Then to retrieve it from the store and convert to an object again:

var user = JSON.parse(localStorage.getItem('user'));

If we need to delete all entries of the store we can simply do:

localStorage.clear();

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.

python how to pad numpy array with zeros

Very simple, you create an array containing zeros using the reference shape:

result = np.zeros(b.shape)
# actually you can also use result = np.zeros_like(b) 
# but that also copies the dtype not only the shape

and then insert the array where you need it:

result[:a.shape[0],:a.shape[1]] = a

and voila you have padded it:

print(result)
array([[ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

You can also make it a bit more general if you define where your upper left element should be inserted

result = np.zeros_like(b)
x_offset = 1  # 0 would be what you wanted
y_offset = 1  # 0 in your case
result[x_offset:a.shape[0]+x_offset,y_offset:a.shape[1]+y_offset] = a
result

array([[ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  1.,  1.],
       [ 0.,  1.,  1.,  1.,  1.,  1.],
       [ 0.,  1.,  1.,  1.,  1.,  1.]])

but then be careful that you don't have offsets bigger than allowed. For x_offset = 2 for example this will fail.


If you have an arbitary number of dimensions you can define a list of slices to insert the original array. I've found it interesting to play around a bit and created a padding function that can pad (with offset) an arbitary shaped array as long as the array and reference have the same number of dimensions and the offsets are not too big.

def pad(array, reference, offsets):
    """
    array: Array to be padded
    reference: Reference array with the desired shape
    offsets: list of offsets (number of elements must be equal to the dimension of the array)
    """
    # Create an array of zeros with the reference shape
    result = np.zeros(reference.shape)
    # Create a list of slices from offset to offset + shape in each dimension
    insertHere = [slice(offset[dim], offset[dim] + array.shape[dim]) for dim in range(a.ndim)]
    # Insert the array in the result at the specified offsets
    result[insertHere] = a
    return result

And some test cases:

import numpy as np

# 1 Dimension
a = np.ones(2)
b = np.ones(5)
offset = [3]
pad(a, b, offset)

# 3 Dimensions

a = np.ones((3,3,3))
b = np.ones((5,4,3))
offset = [1,0,0]
pad(a, b, offset)

How to set Java classpath in Linux?

export CLASSPATH=/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar

or, if you already have some classpath set

export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar

and, if also you want to include current directory

export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar:.

Terminal Commands: For loop with echo

for ((i=0; i<=1000; i++)); do
    echo "http://example.com/$i.jpg"
done

How to get the data-id attribute?

If you are not concerned about old IE browsers, you can also use HTML5 dataset API

HTML

<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>

JS

var myDiv = document.querySelector('#my-div');

myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"

Demo: http://html5demos.com/dataset

Full browser support list: http://caniuse.com/#feat=dataset

Android Studio - Failed to notify project evaluation listener error

In my case I solved this error only by Invalidating caches.

File > Invalidate caches / Restart

Floating elements within a div, floats outside of div. Why?

Put your floating div(s) in a div and in CSS give it overflow:hidden;
it will work fine.

DOM element to corresponding vue.js component

In Vue.js 2 Inside a Vue Instance or Component:

  • Use this.$el to get the HTMLElement the instance/component was mounted to

From an HTMLElement:

  • Use .__vue__ from the HTMLElement
    • E.g. var vueInstance = document.getElementById('app').__vue__;

Having a VNode in a variable called vnode you can:

  • use vnode.elm to get the element that VNode was rendered to
  • use vnode.context to get the VueComponent instance that VNode's component was declared (this usually returns the parent component, but may surprise you when using slots.
  • use vnode.componentInstance to get the Actual VueComponent instance that VNode is about

Source, literally: vue/flow/vnode.js.

Runnable Demo:

_x000D_
_x000D_
Vue.config.productionTip = false; // disable developer version warning
console.log('-------------------')

Vue.component('my-component', {
  template: `<input>`,
  mounted: function() {
    console.log('[my-component] is mounted at element:', this.$el);
  }
});

Vue.directive('customdirective', {
  bind: function (el, binding, vnode) {
    console.log('[DIRECTIVE] My Element is:', vnode.elm);
    console.log('[DIRECTIVE] My componentInstance is:', vnode.componentInstance);
    console.log('[DIRECTIVE] My context is:', vnode.context);
    // some properties, such as $el, may take an extra tick to be set, thus you need to...
    Vue.nextTick(() => console.log('[DIRECTIVE][AFTER TICK] My context is:', vnode.context.$el))
  }
})

new Vue({
  el: '#app',
  mounted: function() {
    console.log('[ROOT] This Vue instance is mounted at element:', this.$el);
    
    console.log('[ROOT] From the element to the Vue instance:', document.getElementById('app').__vue__);
    console.log('[ROOT] Vue component instance of my-component:', document.querySelector('input').__vue__);
  }
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>

<h1>Open the browser's console</h1>
<div id="app">
  <my-component v-customdirective=""></my-component>
</div>
_x000D_
_x000D_
_x000D_

Add Favicon to Website

Simply put a file named favicon.ico in the webroot.

If you want to know more, please start reading:

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

Using Pairs or 2-tuples in Java

As an extension to @maerics nice answer, I've added a few useful methods:

public class Tuple<X, Y> { 
    public final X x; 
    public final Y y; 
    public Tuple(X x, Y y) { 
        this.x = x; 
        this.y = y; 
    }

    @Override
    public String toString() {
        return "(" + x + "," + y + ")";
    }

    @Override
    public boolean equals(Object other) {
        if (other == this) {
            return true;
        }

        if (!(other instanceof Tuple)){
            return false;
        }

        Tuple<X,Y> other_ = (Tuple<X,Y>) other;

        // this may cause NPE if nulls are valid values for x or y. The logic may be improved to handle nulls properly, if needed.
        return other_.x.equals(this.x) && other_.y.equals(this.y);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((x == null) ? 0 : x.hashCode());
        result = prime * result + ((y == null) ? 0 : y.hashCode());
        return result;
    }
}

Create instance of generic type in Java?

When you are working with E at compile time you don't really care the actual generic type "E" (either you use reflection or work with base class of generic type) so let the subclass provide instance of E.

abstract class SomeContainer<E>
{
    abstract protected E createContents();
    public void doWork(){
        E obj = createContents();
        // Do the work with E 
     }
}

class BlackContainer extends SomeContainer<Black>{
    protected Black createContents() {
        return new Black();
    }
}

Protecting cells in Excel but allow these to be modified by VBA script

As a workaround, you can create a hidden worksheet, which would hold the changed value. The cell on the visible, protected worksheet should display the value from the hidden worksheet using a simple formula.

You will be able to change the displayed value through the hidden worksheet, while your users won't be able to edit it.

Asus Zenfone 5 not detected by computer

This are the steps :

  1. Download and install latest version of pclink for PC from here.
  2. Make sure PCLink is running in Foreground on Asus Zenfone 5 and in settings on rightmost topmost corner click on USB icon and then check the MTP checkbox.
  3. Click connect on PCLink on PC.
  4. If Asus USB Driver for Zenfone 5 is properly installed on your PC.You will see 'Asus Android Device' in your Device Manager otherwise install Asus USB Driver for Zenfone 5 from here then try again
  5. Now you will be able to see your device online in Android Studio and screen of your device on PCLink software on your PC.

I haven't tried for eclipse but it might work for that also.

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

Weird error, you can try methods given by james goooseling and also I have done it by following ways:

  • Remove all jars or libraries from build path and lib folders and add them again in lib folder or build path as you wish.

  • Check if you have servlet annotation @WebServlet for given servlet and if it has mapping in web.xml as well .. this is most common error due to which tomcat gets confused , that what url pattern must he use.

ng serve not detecting file changes automatically

I had the same problem, using sudo ng serve seemed to "solve" the problem unsatisfactorily. Using sudo is not satisfactory IMO.

I checked my INotify count versus my default limit (8192) using: lsof | grep inotify | wc -l The value returned by the above command was way less than the limit. So the INotify solution didn't seem to apply to my problem.

I also checked permissions and ownership, both seemed ok, comparable to another project that worked.

Out of frustration I restarted VS Code. Basically I closed all instances, I had two running and re-opened both following which the problem went away.

I am leaning towards a possible bug somewhere. This is something to consider before turning your system inside out. Fortunately/Unfortunately this problem hasn't occurred again, I'll dig deeper if it does.

open() in Python does not create a file if it doesn't exist

open('myfile.dat', 'a') works for me, just fine.

in py3k your code raises ValueError:

>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode

in python-2.6 it raises IOError.

How to get user name using Windows authentication in asp.net?

These are the different variables you have access to and their values, depending on the IIS configuration.

Scenario 1: Anonymous Authentication in IIS with impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           ASPNET                   
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 2: Windows Authentication in IIS, impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1   
HttpContext.Current.Request.IsAuthenticated           True             
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1   
System.Environment.UserName                           ASPNET           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 3: Anonymous Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           IUSR_SERVER1           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\IUSR_SERVER1 

Scenario 4: Windows Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated           True          
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1
System.Environment.UserName                           USER1         
Security.Principal.WindowsIdentity.GetCurrent().Name  MYDOMAIN\USER1

Legend
SERVER1\ASPNET: Identity of the running process on server.
SERVER1\IUSR_SERVER1: Anonymous guest user defined in IIS.
MYDOMAIN\USER1: The user of the remote client.

Source

Why is there no tuple comprehension in Python?

Raymond Hettinger (one of the Python core developers) had this to say about tuples in a recent tweet:

#python tip: Generally, lists are for looping; tuples for structs. Lists are homogeneous; tuples heterogeneous. Lists for variable length.

This (to me) supports the idea that if the items in a sequence are related enough to be generated by a, well, generator, then it should be a list. Although a tuple is iterable and seems like simply a immutable list, it's really the Python equivalent of a C struct:

struct {
    int a;
    char b;
    float c;
} foo;

struct foo x = { 3, 'g', 5.9 };

becomes in Python

x = (3, 'g', 5.9)

assembly to compare two numbers

It varies from assembler to assembler. Most machines offer registers, which have symbolic names like R1, or EAX (the Intel x86), and have instruction names like "CMP" for compare. And for a compare instruction, you need another operand, sometimes a register, sometimes a literal. Often assemblers allow comments to the right of instruction.

An instruction line looks like:

<opcode>   <register> <operand>   ; comment

Your assembler may vary somewhat.

For the Microsoft X86 assembler, you can write:

CMP EAX, 23 ; compare register EAX with the constant 23

or

CMP EAX, XYZ ; compare register EAX with contents of memory location named XYZ

Often one can write complex "expressions" in the operand field that enable the instruction, if it has the capability, to address memory in variety of ways. But I think this answers your question.

Find all tables containing column with specified name - MS SQL Server

select  
        s.[name]            'Schema',
        t.[name]            'Table',
        c.[name]            'Column',
        d.[name]            'Data Type',
        c.[max_length]      'Length',
        d.[max_length]      'Max Length',
        d.[precision]       'Precision',
        c.[is_identity]     'Is Id',
        c.[is_nullable]     'Is Nullable',
        c.[is_computed]     'Is Computed',
        d.[is_user_defined] 'Is UserDefined',
        t.[modify_date]     'Date Modified',
        t.[create_date]     'Date created'
from        sys.schemas s
inner join  sys.tables  t
on s.schema_id = t.schema_id
inner join  sys.columns c
on t.object_id = c.object_id
inner join  sys.types   d
on c.user_type_id = d.user_type_id
where c.name like '%ColumnName%'

This here will give you a little extra information about the schema, tables and columns that you may or may not choose to use extra conditions in your where clause to filter on. For example, if you only wanted to see the fields which must have values add

and c.is_nullable = 0

You could add other conditionals, I also added the columns in the select clause in this vertical manner so it was easy to reorder, remove, rename, or add others based on your needs. Alternately you could search for just tables by using T.Name. Its very customisable.

Enjoy.

What method in the String class returns only the first N characters?

string.Substring(0,n); // 0 - start index and n - number of characters

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

I had this when build my application with "All cpu" target while it referenced a 3rd party x64-only (managed) dll.

How do I add items to an array in jQuery?

Since $.getJSON is async, I think your console.log(list.length); code is firing before your array has been populated. To correct this put your console.log statement inside your callback:

var list = new Array();
$.getJSON("json.js", function(data) {
    $.each(data, function(i, item) {
        console.log(item.text);
        list.push(item.text);
    });
    console.log(list.length);
});

ScrollTo function in AngularJS

Thanks Andy for the example, this was very helpful. I ended implementing a slightly different strategy since I am developing a single-page scroll and did not want Angular to refresh when using the hashbang URL. I also want to preserve the back/forward action of the browser.

Instead of using the directive and the hash, I am using a $scope.$watch on the $location.search, and obtaining the target from there. This gives a nice clean anchor tag

<a ng-href="#/?scroll=myElement">My element</a>

I chained the watch code to the my module declaration in app.js like so:

.run(function($location, $rootScope) {
   $rootScope.$watch(function() { return $location.search() }, function(search) { 
     var scrollPos = 0;
     if (search.hasOwnProperty('scroll')) {
       var $target = $('#' + search.scroll);
       scrollPos = $target.offset().top;
     }   
     $("body,html").animate({scrollTop: scrollPos}, "slow");
   });
})

The caveat with the code above is that if you access by URL directly from a different route, the DOM may not be loaded in time for jQuery's $target.offset() call. The solution is to nest this code within a $viewContentLoaded watcher. The final code looks something like this:

.run(function($location, $rootScope) {
  $rootScope.$on('$viewContentLoaded', function() {
     $rootScope.$watch(function() { return $location.search() }, function(search) {
       var scrollPos = 0 
       if (search.hasOwnProperty('scroll')) {
         var $target = $('#' + search.scroll);
         var scrollPos = $target.offset().top;
       }
       $("body,html").animate({scrollTop: scrollPos}, "slow");                                                                                                                                                                    
     });  
   });    
 })

Tested with Chrome and FF

How to retry image pull in a kubernetes Pods?

In case of not having the yaml file:

kubectl get pod PODNAME -n NAMESPACE -o yaml | kubectl replace --force -f -

C# Wait until condition is true

After digging a lot of stuff, finally, I came up with a good solution that doesn't hang the CI :) Suit it to your needs!

public static Task WaitUntil<T>(T elem, Func<T, bool> predicate, int seconds = 10)
{
    var tcs = new TaskCompletionSource<int>();
    using(var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(seconds)))
    {
        cancellationTokenSource.Token.Register(() =>
        {
            tcs.SetException(
                new TimeoutException($"Waiting predicate {predicate} for {elem.GetType()} timed out!"));
            tcs.TrySetCanceled();
        });

        while(!cancellationTokenSource.IsCancellationRequested)
        {
            try
            {
                if (!predicate(elem))
                {
                    continue;
                }
            }
            catch(Exception e)
            {
                tcs.TrySetException(e);
            }

            tcs.SetResult(0);
            break;
        }

        return tcs.Task;
    }
}

Get href attribute on jQuery

Use this:

$(function(){
    $("tr.b_row").each(function(){
    var a_href = $(this).find('div.cpt h2 a').attr('href');
    alert ("Href is: "+a_href);

    });
});

See a working demo: http://jsfiddle.net/usmanhalalit/4Ea4k/1/

Conditionally formatting cells if their value equals any value of another column

I was looking into this and loved the approach from peege using a for loop! (because I'm learning VBA at the moment)

However, if we are trying to match "any" value of another column, how about using nested loops like the following?

Sub MatchAndColor()

Dim lastRow As Long
Dim sheetName As String


sheetName = "Sheet1"            'Insert your sheet name here
lastRow = Sheets(sheetName).Range("A" & Rows.Count).End(xlUp).Row

For lRowA = 1 To lastRow         'Loop through all rows
    For lRowB = 1 To lastRow
        If Sheets(sheetName).Cells(lRowA, "A") = Sheets(sheetName).Cells(lRowB, "B") Then

        Sheets(sheetName).Cells(lRowA, "A").Interior.ColorIndex = 3  'Set Color to RED
    End If

Next lRowB
Next lRowA

End Sub

Add a column with a default value to an existing table in SQL Server

ALTER TABLE Table1 ADD Col3 INT NOT NULL DEFAULT(0)

How to completely remove a dialog on close

An ugly solution that works like a charm for me:

$("#mydialog").dialog(
    open: function(){
        $('div.ui-widget-overlay').hide();
        $("div.ui-dialog").not(':first').remove();
}
});

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

If your table columns contains duplicate data and If you directly apply row_ number() and create PARTITION on column, there is chance to have result in duplicated row and with row number value.

To remove duplicate row, you need one more INNER query in from clause which eliminates duplicate rows and then it will give output to it's foremost outer FROM clause where you can apply PARTITION and ROW_NUMBER ().

As like below example:

SELECT DATE, STATUS, TITLE, ROW_NUMBER() OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM (
     SELECT DISTINCT <column names>...
) AS tbl

Creating an Instance of a Class with a variable in Python

Rather than use multiple classes or class inheritance, perhaps a single Toy class that knows what "kind" it is:

class Toy:
    num = 0
    def __init__(self, name, kind, *args):
        self.name = name
        self.kind = kind
        self.data = args
        self.num = Toy.num
        Toy.num += 1

    def __repr__(self):
        return ' '.join([self.name,self.kind,str(self.num)])

    def playWith(self):
        print self

def getNewToy(name, kind):
    return Toy(name, kind)

t1 = Toy('Suzie', 'doll')
t2 = getNewToy('Jack', 'robot')
print t1
t2.playWith()

Running it:

$ python toy.py 
Suzie doll 0
Jack robot 1

As you can see, getNewToy is really unnecessary. Now you can modify playWith to check the value of self.kind and change behavior, you can redefine playWith to designate a playmate:

def playWith(self, who=None):
    if who:  pass
    print self

t1.playWith(t2)

How to find when a web page was last updated

For checking the Last Modified header, you can use httpie (docs).

Installation

pip install httpie --user

Usage

$ http -h https://martin-thoma.com/author/martin-thoma/ | grep 'Last-Modified\|Date'
Date: Fri, 06 Jan 2017 10:06:43 GMT
Last-Modified: Fri, 06 Jan 2017 07:42:34 GMT

The Date is important as this reports the server time, not your local time. Also, not every server sends Last-Modified (e.g. superuser seems not to do it).

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

MySQL CURRENT_TIMESTAMP on create and on update

i think it is possible by using below technique

`ts_create` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`ts_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

react native get TextInput value

Try Console log the object and you will find your entered text inside nativeEvent.text

example:

handelOnChange = (enteredText) => {
    console.log(enteredText.nativeEvent.text)
}
render()
return (
    <SafeAreaView>
        <TextInput
            onChange={this.handelOnChange}
        >
</SafeAreaView>

)

How to speed up insertion performance in PostgreSQL

If you happend to insert colums with UUIDs (which is not exactly your case) and to add to @Dennis answer (I can't comment yet), be advise than using gen_random_uuid() (requires PG 9.4 and pgcrypto module) is (a lot) faster than uuid_generate_v4()

=# explain analyze select uuid_generate_v4(),* from generate_series(1,10000);
                                                        QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=11.674..10304.959 rows=10000 loops=1)
 Planning time: 0.157 ms
 Execution time: 13353.098 ms
(3 filas)

vs


=# explain analyze select gen_random_uuid(),* from generate_series(1,10000);
                                                        QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=252.274..418.137 rows=10000 loops=1)
 Planning time: 0.064 ms
 Execution time: 503.818 ms
(3 filas)

Also, it's the suggested official way to do it

Note

If you only need randomly-generated (version 4) UUIDs, consider using the gen_random_uuid() function from the pgcrypto module instead.

This droped insert time from ~2 hours to ~10 minutes for 3.7M of rows.

window.close() doesn't work - Scripts may close only the windows that were opened by it

You can't close a current window or any window or page that is opened using '_self' But you can do this

var customWindow = window.open('', '_blank', '');
    customWindow.close();

Setting up a websocket on Apache?

I can't answer all questions, but I will do my best.

As you already know, WS is only a persistent full-duplex TCP connection with framed messages where the initial handshaking is HTTP-like. You need some server that's listening for incoming WS requests and that binds a handler to them.

Now it might be possible with Apache HTTP Server, and I've seen some examples, but there's no official support and it gets complicated. What would Apache do? Where would be your handler? There's a module that forwards incoming WS requests to an external shared library, but this is not necessary with the other great tools to work with WS.

WS server trends now include: Autobahn (Python) and Socket.IO (Node.js = JavaScript on the server). The latter also supports other hackish "persistent" connections like long polling and all the COMET stuff. There are other little known WS server frameworks like Ratchet (PHP, if you're only familiar with that).

In any case, you will need to listen on a port, and of course that port cannot be the same as the Apache HTTP Server already running on your machine (default = 80). You could use something like 8080, but even if this particular one is a popular choice, some firewalls might still block it since it's not supposed to be Web traffic. This is why many people choose 443, which is the HTTP Secure port that, for obvious reasons, firewalls do not block. If you're not using SSL, you can use 80 for HTTP and 443 for WS. The WS server doesn't need to be secure; we're just using the port.

Edit: According to Iharob Al Asimi, the previous paragraph is wrong. I have no time to investigate this, so please see his work for more details.

About the protocol, as Wikipedia shows, it looks like this:

Client sends:

GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com

Server replies:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

and keeps the connection alive. If you can implement this handshaking and the basic message framing (encapsulating each message with a small header describing it), then you can use any client-side language you want. JavaScript is only used in Web browsers because it's built-in.

As you can see, the default "request method" is an initial HTTP GET, although this is not really HTTP and looses everything in common with HTTP after this handshaking. I guess servers that do not support

Upgrade: websocket
Connection: Upgrade

will reply with an error or with a page content.

Updating to latest version of CocoaPods?

Open the Terminal -> copy below command

sudo gem install cocoapods

It will install the latest stable version of cocoapods.

after that, you need to update pod using below command

pod setup

You can check pod version using below command

pod --version

What is the difference between connection and read timeout for sockets?

These are timeout values enforced by JVM for TCP connection establishment and waiting on reading data from socket.

If the value is set to infinity, you will not wait forever. It simply means JVM doesn't have timeout and OS will be responsible for all the timeouts. However, the timeouts on OS may be really long. On some slow network, I've seen timeouts as long as 6 minutes.

Even if you set the timeout value for socket, it may not work if the timeout happens in the native code. We can reproduce the problem on Linux by connecting to a host blocked by firewall or unplugging the cable on switch.

The only safe approach to handle TCP timeout is to run the connection code in a different thread and interrupt the thread when it takes too long.

Wait one second in running program

Maybe try this code:

void wait (double x) {
    DateTime t = DateTime.Now;
    DateTime tf = DateTime.Now.AddSeconds(x);

    while (t < tf) {
        t = DateTime.Now;
    }
}

Setting paper size in FPDF

They say it right there in the documentation for the FPDF constructor:

FPDF([string orientation [, string unit [, mixed size]]])

This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...

size

The size used for pages. It can be either one of the following values (case insensitive):

A3 A4 A5 Letter Legal

or an array containing the width and the height (expressed in the unit given by unit).

They even give an example with custom size:

Example with a custom 100x150 mm page size:

$pdf = new FPDF('P','mm',array(100,150));

Checking Date format from a string in C#

Use an array of valid dates format, check docs:

string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
DateTime parsedDate;
var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);

if(isValidFormat)
{
    string.Format("{0:d/MM/yyyy}", parsedDate);
}
else
{
    // maybe throw an Exception
}

Server Discovery And Monitoring engine is deprecated

If you are using a MongoDB server then after using connect in the cluster clock on connect and finding the URL, the URL will be somehing like this

<mongodb+srv://Rohan:<password>@cluster0-3kcv6.mongodb.net/<dbname>?retryWrites=true&w=majority>

In this case, don't forget to replace the password with your database password and db name and then use

const client = new MongoClient(url,{useUnifiedTopology:true});

TypeError: sequence item 0: expected string, int found

Replace

values = ",".join(value_list)

with

values = ','.join([str(i) for i in value_list])

OR

values = ','.join(str(value_list)[1:-1])

How to check if pytorch is using the GPU?

Simply from command prompt or Linux environment run the following command.

python -c 'import torch; print(torch.cuda.is_available())'

The above should print True

python -c 'import torch; print(torch.rand(2,3).cuda())'

This one should print the following:

tensor([[0.7997, 0.6170, 0.7042], [0.4174, 0.1494, 0.0516]], device='cuda:0')

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

Css height in percent not working

You need to set a 100% height on all your parent elements, in this case your body and html. This fiddle shows it working.

_x000D_
_x000D_
html, body { height: 100%; width: 100%; margin: 0; }_x000D_
div { height: 100%; width: 100%; background: #F52887; }
_x000D_
<html><body><div></div></body></html>
_x000D_
_x000D_
_x000D_

String.replaceAll single backslashes with double backslashes

Yes... by the time the regex compiler sees the pattern you've given it, it sees only a single backslash (since Java's lexer has turned the double backwhack into a single one). You need to replace "\\\\" with "\\\\", believe it or not! Java really needs a good raw string syntax.

Convert Enum to String

Enum.GetName(...)

This is the most elegant method that is meant for it.

var enumValueString = Enum.GetName(typeof (MyEnum), MyEnum.MyValue);

Although I don't see any issues with calling .ToString() as it is simply shorter.

var enumValueString = MyEnum.MyValue.ToString();

With new C# 6 syntax you can use:

nameof(MyEnum.MyValue)

Change Volley timeout duration

int MY_SOCKET_TIMEOUT_MS=500;

 stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                MY_SOCKET_TIMEOUT_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Why doesn't Python have a sign function?

Try running this, where x is any number

int_sign = bool(x > 0) - bool(x < 0)

The coercion to bool() handles the possibility that the comparison operator doesn't return a boolean.

adding directory to sys.path /PYTHONPATH

As to me, i need to caffe to my python path. I can add it's path to the file /home/xy/.bashrc by add

export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH.

to my /home/xy/.bashrc file.

But when I use pycharm, the path is still not in.

So I can add path to PYTHONPATH variable, by run -> edit Configuration.

enter image description here

How to show math equations in general github's markdown(not github's blog)

But github show nothing for the math symbols! please help me, thanks!

GitHub markdown parsing is performed by the SunDown (ex libUpSkirt) library.

The motto of the library is "Standards compliant, fast, secure markdown processing library in C". The important word being "secure" there, considering your question :).

Indeed, allowing javascript to be executed would be a bit off of the MarkDown standard text-to-HTML contract.

Moreover, everything that looks like a HTML tag is either escaped or stripped out.

Tell me how to show math symbols in general github markdown.

Your best bet would be to find a website similar to yuml.me which can generate on-the-fly images from by parsing the provided URL querystring.

Update

I've found some sites providing users with such service: codedogs.com (no longer seems to support embedding) or iTex2Img. You may want to try them out. Of course, others may exist and some Google-fu will help you find them.

given the following markdown syntax

![equation](http://www.sciweavers.org/tex2img.php?eq=1%2Bsin%28mc%5E2%29&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=)

it will display the following image

equation http://www.sciweavers.org/tex2img.php?eq=1%2Bsin%28mc%5E2%29&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=

Note: In order for the image to be properly displayed, you'll have to ensure the querystring part of the url is percent encoded. You can easily find online tools to help you with that task, such as www.url-encode-decode.com

How do I change file permissions in Ubuntu

If you just want to change file permissions, you want to be careful about using -R on chmod since it will change anything, files or folders. If you are doing a relative change (like adding write permission for everyone), you can do this:

sudo chmod -R a+w /var/www

But if you want to use the literal permissions of read/write, you may want to select files versus folders:

sudo find /var/www -type f -exec chmod 666 {} \;

(Which, by the way, for security reasons, I wouldn't recommend either of these.)

Or for folders:

sudo find /var/www -type d -exec chmod 755 {} \;

How do I implement Cross Domain URL Access from an Iframe using Javascript?

Good article here: Cross-domain communication with iframes

Also you can directly set document.domain the same in both frames (even

document.domain = document.domain;

code has sense because resets port to null), but this trick is not general-purpose.

Global npm install location on windows?

These are typical npm paths if you install a package globally:

Windows XP -             %USERPROFILE%\Application Data\npm\node_modules
Newer Windows Versions - %AppData%\npm\node_modules
or -                     %AppData%\roaming\npm\node_modules

Dealing with float precision in Javascript

Check out this link.. It helped me a lot.

http://www.w3schools.com/jsref/jsref_toprecision.asp

The toPrecision(no_of_digits_required) function returns a string so don't forget to use the parseFloat() function to convert to decimal point of required precision.

finished with non zero exit value

BuildToolsVersion & Dependencies must be same with Base API version.

buildToolsVersion '23.0.2' & compile 

&

com.android.support:appcompat-v7:24.0.0-alpha1

can not match with base API level.

It should be

compile 'com.android.support:appcompat-v7:21.0.3'

Done

javac error: Class names are only accepted if annotation processing is explicitly requested

I was stumped by this too because I was including the .Java extension ... then I noticed the capital J.

This will also cause the "annotation processing" error:

javac myclass.Java 

Instead, it should be:

javac myclass.java 

'Conda' is not recognized as internal or external command

If you have a newer version of the Anaconda Navigator, open the Anaconda Prompt program that came in the install. Type all the usual conda update/conda install commands there.

I think the answers above explain this, but I could have used a very simple instruction like this. Perhaps it will help others.

custom facebook share button

Given that we are in a php code context and the variable $url contains the link the user wants to share, you can try this to use a custom image :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank"><img src="/img/facebook-share-button.png" /></a>

or this for just plain text :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank">share</a>

You can also style the link purely with css.

The html code :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank"></a>

The css code :

.facebook-share-button {
    background-image: url("/img/facebook-share-button.png");
    display: inline-block;
    height: 32px;
    width: 32px;
}

.facebook-share-button:active,
.facebook-share-button:focus,
.facebook-share-button:hover {
    background-image: url("/img/facebook-share-button-hover.png");
}

How to add/update an attribute to an HTML element using JavaScript?

You can read here about the behaviour of attributes in many different browsers, including IE.

element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn't work, then maybe element.attributeName = 'value' might work.

".addEventListener is not a function" why does this error occur?

Another important thing you need to note with ".addEventListener is not a function" error is that the error might be coming a result of assigning it a wrong object eg consider

let myImages = ['images/pic1.jpg','images/pic2.jpg','images/pic3.jpg','images/pic4.jpg','images/pic5.jpg'];
let i = 0;
while(i < myImages.length){
  const newImage = document.createElement('img');
  newImage.setAttribute('src',myImages[i]);
  thumbBar.appendChild(newImage);

 //Code just below will bring the said error 
 myImages[i].addEventListener('click',fullImage);

 //Code just below execute properly 
  newImage.addEventListener('click',fullImage);




  i++;
}

In the code Above I am basically assigning images to a div element in my html dynamically using javascript. I've done this by writing the images in an array and looping them through a while loop and adding all of them to the div element.

I've then added a click event listener for all images.

The code "myImages[i].addEventListener('click',fullImage);" will give you an error of "addEventListener is not a function" because I am chaining an addEventListener to an array object which does not have the addEventListener() function.

However for the code "newImage.addEventListener('click',fullImage);" it executes properly because the newImage object has access the function addEventListener() while the array object does not.

For more clarification follow the link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function

If you can decode JWT, how are they secure?

Ref - JWT Structure and Security

It is important to note that JWT are used for authorization and not authentication. So a JWT will be created for you only after you have been authenticated by the server by may be specifying the credentials. Once JWT has been created for all future interactions with server JWT can be used. So JWT tells that server that this user has been authenticated, let him access the particular resource if he has the role.
Information in the payload of the JWT is visible to everyone. There can be a "Man in the Middle" attack and the contents of the JWT can be changed. So we should not pass any sensitive information like passwords in the payload. We can encrypt the payload data if we want to make it more secure. If Payload is tampered with server will recognize it.
So suppose a user has been authenticated and provided with a JWT. Generated JWT has a claim specifying role of Admin. Also the Signature is generated with

enter image description here

This JWT is now tampered with and suppose the role is changed to Super Admin
Then when the server receives this token it will again generate the signature using the secret key(which only the server has) and the payload. It will not match the signature in the JWT. So the server will know that the JWT has been tampered with.

How to retrieve current workspace using Jenkins Pipeline Groovy script?

I have successfully used as shown below in Jenkinsfile:

steps {
  script {
    def reportPath = "${WORKSPACE}/target/report"
    ...
  }
}

Is there a way to pass javascript variables in url?

Try this:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+elemA+"&lon="+elemB+"&setLatLon=Set";

To put a variable in a string enclose the variable in quotes and addition signs like this:

var myname = "BOB";
var mystring = "Hi there "+myname+"!"; 

Just remember that one rule!

How to vertically center <div> inside the parent element with CSS?

I found a way that works great for me. The next script inserts an invisible image (same as bgcolor or a transparant gif) with height equal to half the size of the white-space on the screen. The effect is a perfect vertical-alignment.

Say you have a header div (height=100) and a footer div (height=50) and the content in the main div that you would like to align has a height of 300:

<script type="text/javascript" charset="utf-8">
var screen = window.innerHeight;
var content = 150 + 300;
var imgheight = ( screen - content) / 2 ;
document.write("<img src='empty.jpg' height='" + imgheight + "'>"); 
</script>   

You place the script just before the content that you want to align!

In my case the content I liked to align was an image (width=95%) with an aspect ratio of 100:85 (width:height).Meaning the height of the image is 85% of it's width. And the Width being 95% of the screenwidth.

I therefore used:

var content = 150 + ( 0.85 * ( 0.95 * window.innerWidth ));

Combine this script with

<body onResize="window.location.href = window.location.href;">

and you have a smooth vertical alignment.

Hope this works for you too!

AngularJS format JSON string output

Angular has a built-in filter for showing JSON

<pre>{{data | json}}</pre>

Note the use of the pre-tag to conserve whitespace and linebreaks

Demo:

_x000D_
_x000D_
angular.module('app', [])_x000D_
  .controller('Ctrl', ['$scope',_x000D_
    function($scope) {_x000D_
_x000D_
      $scope.data = {_x000D_
        a: 1,_x000D_
        b: 2,_x000D_
        c: {_x000D_
          d: "3"_x000D_
        },_x000D_
      };_x000D_
_x000D_
    }_x000D_
  ]);
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="app">_x000D_
_x000D_
  <head>_x000D_
    <script data-require="[email protected]" data-semver="1.2.15" src="//code.angularjs.org/1.2.15/angular.js"></script>_x000D_
  </head>_x000D_
_x000D_
  <body ng-controller="Ctrl">_x000D_
    <pre>{{data | json}}</pre>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

There's also an angular.toJson method, but I haven't played around with that (Docs)

Quickly reading very large tables as dataframes

I am reading data very quickly using the new arrow package. It appears to be in a fairly early stage.

Specifically, I am using the parquet columnar format. This converts back to a data.frame in R, but you can get even deeper speedups if you do not. This format is convenient as it can be used from Python as well.

My main use case for this is on a fairly restrained RShiny server. For these reasons, I prefer to keep data attached to the Apps (i.e., out of SQL), and therefore require small file size as well as speed.

This linked article provides benchmarking and a good overview. I have quoted some interesting points below.

https://ursalabs.org/blog/2019-10-columnar-perf/

File Size

That is, the Parquet file is half as big as even the gzipped CSV. One of the reasons that the Parquet file is so small is because of dictionary-encoding (also called “dictionary compression”). Dictionary compression can yield substantially better compression than using a general purpose bytes compressor like LZ4 or ZSTD (which are used in the FST format). Parquet was designed to produce very small files that are fast to read.

Read Speed

When controlling by output type (e.g. comparing all R data.frame outputs with each other) we see the the performance of Parquet, Feather, and FST falls within a relatively small margin of each other. The same is true of the pandas.DataFrame outputs. data.table::fread is impressively competitive with the 1.5 GB file size but lags the others on the 2.5 GB CSV.


Independent Test

I performed some independent benchmarking on a simulated dataset of 1,000,000 rows. Basically I shuffled a bunch of things around to attempt to challenge the compression. Also I added a short text field of random words and two simulated factors.

Data

library(dplyr)
library(tibble)
library(OpenRepGrid)

n <- 1000000

set.seed(1234)
some_levels1 <- sapply(1:10, function(x) paste(LETTERS[sample(1:26, size = sample(3:8, 1), replace = TRUE)], collapse = ""))
some_levels2 <- sapply(1:65, function(x) paste(LETTERS[sample(1:26, size = sample(5:16, 1), replace = TRUE)], collapse = ""))


test_data <- mtcars %>%
  rownames_to_column() %>%
  sample_n(n, replace = TRUE) %>%
  mutate_all(~ sample(., length(.))) %>%
  mutate(factor1 = sample(some_levels1, n, replace = TRUE),
         factor2 = sample(some_levels2, n, replace = TRUE),
         text = randomSentences(n, sample(3:8, n, replace = TRUE))
         )

Read and Write

Writing the data is easy.

library(arrow)

write_parquet(test_data , "test_data.parquet")

# you can also mess with the compression
write_parquet(test_data, "test_data2.parquet", compress = "gzip", compression_level = 9)

Reading the data is also easy.

read_parquet("test_data.parquet")

# this option will result in lightning fast reads, but in a different format.
read_parquet("test_data2.parquet", as_data_frame = FALSE)

I tested reading this data against a few of the competing options, and did get slightly different results than with the article above, which is expected.

benchmarking

This file is nowhere near as large as the benchmark article, so maybe that is the difference.

Tests

  • rds: test_data.rds (20.3 MB)
  • parquet2_native: (14.9 MB with higher compression and as_data_frame = FALSE)
  • parquet2: test_data2.parquet (14.9 MB with higher compression)
  • parquet: test_data.parquet (40.7 MB)
  • fst2: test_data2.fst (27.9 MB with higher compression)
  • fst: test_data.fst (76.8 MB)
  • fread2: test_data.csv.gz (23.6MB)
  • fread: test_data.csv (98.7MB)
  • feather_arrow: test_data.feather (157.2 MB read with arrow)
  • feather: test_data.feather (157.2 MB read with feather)

Observations

For this particular file, fread is actually very fast. I like the small file size from the highly compressed parquet2 test. I may invest the time to work with the native data format rather than a data.frame if I really need the speed up.

Here fst is also a great choice. I would either use the highly compressed fst format or the highly compressed parquet depending on if I needed the speed or file size trade off.

Saving timestamp in mysql table using php

$created_date = date("Y-m-d H:i:s");
$sql = "INSERT INTO $tbl_name(created_date)VALUES('$created_date')";
$result = mysql_query($sql);

How to add additional libraries to Visual Studio project?

For Visual Studio you'll want to right click on your project in the solution explorer and then click on Properties.

Next open Configuration Properties and then Linker.

Now you want to add the folder you have the Allegro libraries in to Additional Library Directories,

Linker -> Input you'll add the actual library files under Additional Dependencies.

For the Header Files you'll also want to include their directories under C/C++ -> Additional Include Directories.

If there is a dll have a copy of it in your main project folder, and done.

I would recommend putting the Allegro files in the your project folder and then using local references in for the library and header directories.

Doing this will allow you to run the application on other computers without having to install Allergo on the other computer.

This was written for Visual Studio 2008. For 2010 it should be roughly the same.

Java ArrayList Index

The big difference between primitive arrays & object-based collections (e.g., ArrayList) is that the latter can grow (or shrink) dynamically. Primitive arrays are fixed in size: Once you create them, their size doesn't change (though the contents can).

How to extract numbers from string in c?

Or you can make a simple function like this:

// Provided 'c' is only a numeric character
int parseInt (char c) {
    return c - '0';
}

How do I center content in a div using CSS?

with all the adjusting css. if possible, wrap it with a table with height and width as 100% and td set it to vertical align to middle, text-align to center

Convert string to integer type in Go?

Converting Simple strings

The easiest way is to use the strconv.Atoi() function.

Note that there are many other ways. For example fmt.Sscan() and strconv.ParseInt() which give greater flexibility as you can specify the base and bitsize for example. Also as noted in the documentation of strconv.Atoi():

Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.

Here's an example using the mentioned functions (try it on the Go Playground):

flag.Parse()
s := flag.Arg(0)

if i, err := strconv.Atoi(s); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

if i, err := strconv.ParseInt(s, 10, 64); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

var i int
if _, err := fmt.Sscan(s, &i); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

Output (if called with argument "123"):

i=123, type: int
i=123, type: int64
i=123, type: int

Parsing Custom strings

There is also a handy fmt.Sscanf() which gives even greater flexibility as with the format string you can specify the number format (like width, base etc.) along with additional extra characters in the input string.

This is great for parsing custom strings holding a number. For example if your input is provided in a form of "id:00123" where you have a prefix "id:" and the number is fixed 5 digits, padded with zeros if shorter, this is very easily parsable like this:

s := "id:00123"

var i int
if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
    fmt.Println(i) // Outputs 123
}

How to create multidimensional array

I know this is ancient but what about...

4x4 example (actually 4x<anything>):

var matrix = [ [],[],[],[] ]

which can filled by:

for (var i=0; i<4; i++) {
   for (var j=0; j<4; j++) {
      matrix[i][j] = i*j;
   }
}

How to convert a list of numbers to jsonarray in Python

Use the json module to produce JSON output:

import json

with open(outputfilename, 'wb') as outfile:
    json.dump(row, outfile)

This writes the JSON result directly to the file (replacing any previous content if the file already existed).

If you need the JSON result string in Python itself, use json.dumps() (added s, for 'string'):

json_string = json.dumps(row)

The L is just Python syntax for a long integer value; the json library knows how to handle those values, no L will be written.

Demo string output:

>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'

Div 100% height works on Firefox but not in IE

I don't think IE supports the use of auto for setting height / width, so you could try giving this a numeric value (like Jarett suggests).

Also, it doesn't look like you are clearing your floats properly. Try adding this to your CSS for #container:

#container {
    height:100%;
    width:100%;
    overflow:hidden;
    /* for IE */
    zoom:1;
}

iOS 7 - Status bar overlaps the view

If you want "Use Autolayout" to be enabled at any cost place the following code in viewdidload.

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) 
{
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
}

Convert string to JSON array

If having following JSON from web service, Json Array as a response :

       [3]
 0:  {
 id: 2
 name: "a561137"
 password: "test"
 firstName: "abhishek"
 lastName: "ringsia"
 organization: "bbb"
    }-
1:  {
 id: 3
 name: "a561023"
 password: "hello"
 firstName: "hello"
  lastName: "hello"
  organization: "hello"
 }-
 2:  {
  id: 4
  name: "a541234"
  password: "hello"
  firstName: "hello"
  lastName: "hello"
  organization: "hello"
    }

have To Accept it first as a Json Array ,then while reading its Object have to use Object Mapper.readValue ,because Json Object Still in String .

      List<User> list = new ArrayList<User>();
      JSONArray jsonArr = new JSONArray(response);


      for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject jsonObj = jsonArr.getJSONObject(i);
         ObjectMapper mapper = new ObjectMapper();
        User usr = mapper.readValue(jsonObj.toString(), User.class);      
        list.add(usr);

    }

mapper.read is correct function ,if u use mapper.convert(param,param) . It will give u error .

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

You can do it with SQL Management Studio -

Server Properties - Security - [Server Authentication section] you check Sql Server and Windows authentication mode

Here is the msdn source - http://msdn.microsoft.com/en-us/library/ms188670.aspx

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

jquery count li elements inside ul -> length?

You have to count the li elements not the ul elements:

if ( $('#menu ul li').length > 1 ) {

If you need every UL element containing at least two LI elements, use the filter function:

$('#menu ul').filter(function(){ return $(this).children("li").length > 1 })

You can also use that in your condition:

if ( $('#menu ul').filter(function(){ return $(this).children("li").length > 1 }).length) {

How do I install jmeter on a Mac?

The easiest way to install it is using Homebrew:

brew install jmeter

Or if you need plugins also:

brew install jmeter --with-plugins

And to open it, use the following command (since it doesn't appear in your Applications):

open /usr/local/bin/jmeter

Where is Ubuntu storing installed programs?

to find the program you want you can run this command at terminal:

find / usr-name "your_program"

LDAP filter for blank (empty) attribute

I needed to do a query to get me all groups with a managedBy value set (not empty) and this gave some nice results:

(!(!managedBy=*))

Bootstrap dropdown sub menu missing

Until today (9 jan 2014) the Bootstrap 3 still not support sub menu dropdown.

I searched Google about responsive navigation menu and found this is the best i though.

It is Smart menus http://www.smartmenus.org/

I hope this is the way out for anyone who want navigation menu with multilevel sub menu.

update 2015-02-17 Smart menus are now fully support Bootstrap element style for submenu. For more information please look at Smart menus website.

How to edit data in result grid in SQL Server Management Studio

The given answers are still valid. No change in SSMS (SQL Server 2016) has been made on that regard.

You can also use the criteria pane, after doing the "Edit Top 200 Rows".

Edit Top 200 context menu

  1. Show criteria pane
  2. Enter some criterion
  3. Edit data directly in the results grid

Open criteria pane

Additionally, the number of rows for those commands can be customized in your SSMS options.

enter image description here

Can't create handler inside thread which has not called Looper.prepare()

The error is self-explanatory... doInBackground() runs on a background thread which, since it is not intended to loop, is not connected to a Looper.

You most likely don't want to directly instantiate a Handler at all... whatever data your doInBackground() implementation returns will be passed to onPostExecute() which runs on the UI thread.

   mActivity = ThisActivity.this; 

    mActivity.runOnUiThread(new Runnable() {
     public void run() {
     new asyncCreateText().execute();
     }
   });

ADDED FOLLOWING THE STACKTRACE APPEARING IN QUESTION:

Looks like you're trying to start an AsyncTask from a GL rendering thread... don't do that cos they won't ever Looper.loop() either. AsyncTasks are really designed to be run from the UI thread only.

The least disruptive fix would probably be to call Activity.runOnUiThread() with a Runnable that kicks off your AsyncTask.

Show hide fragment in android

This worked for me

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if(tag.equalsIgnoreCase("dashboard")){

            DashboardFragment dashboardFragment = (DashboardFragment)
                    fragmentManager.findFragmentByTag("dashboard");
            if(dashboardFragment!=null) ft.show(dashboardFragment);

            ShowcaseFragment showcaseFragment = (ShowcaseFragment)
                    fragmentManager.findFragmentByTag("showcase");
            if(showcaseFragment!=null) ft.hide(showcaseFragment);

        } else if(tag.equalsIgnoreCase("showcase")){
            DashboardFragment dashboardFragment = (DashboardFragment)
                    fragmentManager.findFragmentByTag("dashboard");
            if(dashboardFragment!=null) ft.hide(dashboardFragment);

            ShowcaseFragment showcaseFragment = (ShowcaseFragment)
                    fragmentManager.findFragmentByTag("showcase");
            if(showcaseFragment!=null) ft.show(showcaseFragment);
        }

        ft.commit();

When to use Spring Security`s antMatcher()?

Basically http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

How do I remove a key from a JavaScript object?

The delete operator allows you to remove a property from an object.

The following examples all do the same thing.

// Example 1
var key = "Cow";
delete thisIsObject[key]; 

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

If you're interested, read Understanding Delete for an in-depth explanation.

Deleting folders in python recursively

Here's another pure-pathlib solution, but without recursion:

from pathlib import Path
from typing import Union

def del_empty_dirs(base: Union[Path, str]):
    base = Path(base)
    for p in sorted(base.glob('**/*'), reverse=True):
        if p.is_dir():
            p.chmod(0o666)
            p.rmdir()
        else:
            raise RuntimeError(f'{p.parent} is not empty!')
    base.rmdir()

Refresh Excel VBA Function Results

The Application.Volatile doesn't work for recalculating a formula with my own function inside. I use the following function: Application.CalculateFull

What is the worst real-world macros/pre-processor abuse you've ever come across?

By a classmate who failed to understand the rules about magic numbers:
#define TWO_HUNDRED_AND_EIGHTY_THREE_POINT_ONE 283.1

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;
}

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

Best ways to teach a beginner to program?

I would recommend in first teaching the very basics that are used in almost every language, but doing so without a language. Outline all the basic concepts If-Else If-Else, Loops, Classes, Variable Types, Structures, etc. Everything that is the foundation of most languages. Then move onto really understanding Boolean, comparisons and complex AND OR statements, to get the feeling on what the outcomes are for more complex statements.

By doing it this way he will understand the concepts of programming and have a much easier time stepping into languages, from there its just learning the intricate details of the languages, its functions, and syntax.

jQuery Combobox/select autocomplete?

jQuery 1.8.1 has an example of this under autocomplete. It's very easy to implement.

if A vs if A is not None:

Most guides I've seen suggest that you should use

if A:

unless you have a reason to be more specific.

There are some slight differences. There are values other than None that return False, for example empty lists, or 0, so have a think about what it is you're really testing for.

Java NIO FileChannel versus FileOutputstream performance / usefulness

My experience with larger files sizes has been that java.nio is faster than java.io. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating:

The buffer size. The algorithm you basically have is

  • copy from disk to buffer
  • copy from buffer to disk

My own experience has been that this buffer size is ripe for tuning. I've settled on 4KB for one part of my application, 256KB for another. I suspect your code is suffering with such a large buffer. Run some benchmarks with buffers of 1KB, 2KB, 4KB, 8KB, 16KB, 32KB and 64KB to prove it to yourself.

Don't perform java benchmarks that read and write to the same disk.

If you do, then you are really benchmarking the disk, and not Java. I would also suggest that if your CPU is not busy, then you are probably experiencing some other bottleneck.

Don't use a buffer if you don't need to.

Why copy to memory if your target is another disk or a NIC? With larger files, the latency incured is non-trivial.

Like other have said, use FileChannel.transferTo() or FileChannel.transferFrom(). The key advantage here is that the JVM uses the OS's access to DMA (Direct Memory Access), if present. (This is implementation dependent, but modern Sun and IBM versions on general purpose CPUs are good to go.) What happens is the data goes straight to/from disc, to the bus, and then to the destination... bypassing any circuit through RAM or the CPU.

The web app I spent my days and night working on is very IO heavy. I've done micro benchmarks and real-world benchmarks too. And the results are up on my blog, have a look-see:

Use production data and environments

Micro-benchmarks are prone to distortion. If you can, make the effort to gather data from exactly what you plan to do, with the load you expect, on the hardware you expect.

My benchmarks are solid and reliable because they took place on a production system, a beefy system, a system under load, gathered in logs. Not my notebook's 7200 RPM 2.5" SATA drive while I watched intensely as the JVM work my hard disc.

What are you running on? It matters.

Using Razor within JavaScript

A simple and a good straight-forward example:

<script>
    // This gets the username from the Razor engine and puts it
    // in JavaScript to create a variable I can access from the
    // client side.
    //
    // It's an odd workaraound, but it works.
    @{
        var outScript = "var razorUserName = " + "\"" + @User.Identity.Name + "\"";
    }
    @MvcHtmlString.Create(outScript);
</script>

This creates a script in your page at the location you place the code above which looks like the following:

<script>
    // This gets the username from the Razor engine and puts it
    // in JavaScript to create a variable I can access from
    // client side.
    //
    // It's an odd workaraound, but it works.

    var razorUserName = "daylight";
</script>

Now you have a global JavaScript variable named razorUserName which you can access and use on the client. The Razor engine has obviously extracted the value from @User.Identity.Name (server-side variable) and put it in the code it writes to your script tag.

Creating Accordion Table with Bootstrap

For anyone who came here looking for how to get the true accordion effect and only allow one row to be expanded at a time, you can add an event handler for show.bs.collapse like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified this example to do so here: http://jsfiddle.net/QLfMU/116/

Difference between window.location.href and top.location.href

top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

Two other interesting objects are self and parent.

Adding a line break in MySQL INSERT INTO text

You can simply replace all \n with <br/> tag so that when page is displayed then it breaks line.

UPDATE table SET field = REPLACE(field, '\n', '<br/>')

Why does DEBUG=False setting make my django Static Files Access fail?

Support for string view arguments to url() is deprecated and will be removed in Django 1.10

My solution is just small correction to Conrado solution above.

from django.conf import settings
import os
from django.views.static import serve as staticserve

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', staticserve,
            {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
        )

Are string.Equals() and == operator really same?

The Header property of the TreeViewItem is statically typed to be of type object.

Therefore the == yields false. You can reproduce this with the following simple snippet:

object s1 = "Hallo";

// don't use a string literal to avoid interning
string s2 = new string(new char[] { 'H', 'a', 'l', 'l', 'o' });

bool equals = s1 == s2;         // equals is false
equals = string.Equals(s1, s2); // equals is true

Get last field using awk substr

Another option is to use bash parameter substitution.

$ foo="/home/parent/child/filename"
$ echo ${foo##*/}
filename
$ foo="/home/parent/child/child2/filename"
$ echo ${foo##*/}
filename

php get values from json encode

json_decode() will return an object or array if second value it's true:

$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];

What are best practices for multi-language database design?

I'm using next approach:

Product

ProductID OrderID,...

ProductInfo

ProductID Title Name LanguageID

Language

LanguageID Name Culture,....

Plot multiple lines in one graph

Instead of using the outrageously convoluted data structures required by ggplot2, you can use the native R functions:

tab<-read.delim(text="
Company 2011 2013
Company1 300 350
Company2 320 430
Company3 310 420
",as.is=TRUE,sep=" ",row.names=1)

tab<-t(tab)

plot(tab[,1],type="b",ylim=c(min(tab),max(tab)),col="red",lty=1,ylab="Value",lwd=2,xlab="Year",xaxt="n")
lines(tab[,2],type="b",col="black",lty=2,lwd=2)
lines(tab[,3],type="b",col="blue",lty=3,lwd=2)
grid()
legend("topleft",legend=colnames(tab),lty=c(1,2,3),col=c("red","black","blue"),bg="white",lwd=2)
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))

R multiple lines plot

ASP.NET Web API application gives 404 when deployed at IIS 7

For me I received a 404 error on my websites NOT using IIS Express (using Local IIS) while running an application that WAS using IIS Express. If I would close the browser that was used to run IIS Express, then the 404 would go away. For me I had my IIS Express project calling into Local IIS services, so I converted the IIS Express project to use Local IIS and then everything worked. It seems that you can't run both a non-IIS Express and Local IIS website at the same time for some reason.

Why cannot cast Integer to String in java?

You can't cast explicitly anything to a String that isn't a String. You should use either:

"" + myInt;

or:

Integer.toString(myInt);

or:

String.valueOf(myInt);

I prefer the second form, but I think it's personal choice.

Edit OK, here's why I prefer the second form. The first form, when compiled, could instantiate a StringBuffer (in Java 1.4) or a StringBuilder in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could tell. The second form also has an analogue, Integer.toString(myInt, radix) that lets you specify whether you want hex, octal, etc. If you want to be consistent in your code (purely aesthetically, I guess) the second form can be used in more places.

Edit 2 I assumed you meant that your integer was an int and not an Integer. If it's already an Integer, just use toString() on it and be done.

Angular2 multiple router-outlet in the same template

Aux routes syntax has changed with the new RC.3 router.

There are some known issues with aux routes but basic support is available.

You can define routes to show components in a named <router-outlet>

Route config

{path: 'chat', component: ChatCmp, outlet: 'aux'}

Named router outlet

<router-outlet name="aux">

Navigate aux routes

this._router.navigateByUrl("/crisis-center(aux:chat;open=true)");

It seems navigating aux routes from routerLink is not yet supported

<a [routerLink]="'/team/3(aux:/chat;open=true)'">Test</a>

<a [routerLink]="['/team/3', {outlets: {aux: 'chat'}}]">c</a>

Not tried myself yet

See also Angular2 router in one component

RC.5 routerLink DSL (same as createUrlTree parameter) https://angular.io/docs/ts/latest/api/router/index/Router-class.html#!#createUrlTree-anchor

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

Determine the number of lines within a text file

You could quickly read it in, and increment a counter, just use a loop to increment, doing nothing with the text.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

This is a well-known issue and based on this answer you could add setLenient:

Gson gson = new GsonBuilder()
        .setLenient()
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

Now, if you add this to your retrofit, it gives you another error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

This is another well-known error you can find answer here (this error means that your server response is not well-formatted); So change server response to return something:

{
    android:[
        { ver:"1.5", name:"Cupcace", api:"Api Level 3" }
        ...
    ]
}

For better comprehension, compare your response with Github api.

Suggestion: to find out what's going on to your request/response add HttpLoggingInterceptor in your retrofit.

Based on this answer your ServiceHelper would be:

private ServiceHelper() {
        httpClient = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.interceptors().add(interceptor);
        Retrofit retrofit = createAdapter().build();
        service = retrofit.create(IService.class);
    }

Also don't forget to add:

compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

JSONResult to String

json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";            
return new MemoryStream(Encoding.UTF8.GetBytes(json));

What are the differences between Deferred, Promise and Future in JavaScript?

What really made it all click for me was this presentation by Domenic Denicola.

In a github gist, he gave the description I like most, it's very concise:

The point of promises is to give us back functional composition and error bubbling in the async world.

In other word, promises are a way that lets us write asynchronous code that is almost as easy to write as if it was synchronous.

Consider this example, with promises:

getTweetsFor("domenic") // promise-returning async function
    .then(function (tweets) {
        var shortUrls = parseTweetsForUrls(tweets);
        var mostRecentShortUrl = shortUrls[0];
        return expandUrlUsingTwitterApi(mostRecentShortUrl); // promise-returning async function
    })
    .then(doHttpRequest) // promise-returning async function
    .then(
        function (responseBody) {
            console.log("Most recent link text:", responseBody);
        },
        function (error) {
            console.error("Error with the twitterverse:", error);
        }
    );

It works as if you were writing this synchronous code:

try {
    var tweets = getTweetsFor("domenic"); // blocking
    var shortUrls = parseTweetsForUrls(tweets);
    var mostRecentShortUrl = shortUrls[0];
    var responseBody = doHttpRequest(expandUrlUsingTwitterApi(mostRecentShortUrl)); // blocking x 2
    console.log("Most recent link text:", responseBody);
} catch (error) {
    console.error("Error with the twitterverse: ", error);
}

(If this still sounds complicated, watch that presentation!)

Regarding Deferred, it's a way to .resolve() or .reject() promises. In the Promises/B spec, it is called .defer(). In jQuery, it's $.Deferred().

Please note that, as far as I know, the Promise implementation in jQuery is broken (see that gist), at least as of jQuery 1.8.2.
It supposedly implements Promises/A thenables, but you don't get the correct error handling you should, in the sense that the whole "async try/catch" functionality won't work. Which is a pity, because having a "try/catch" with async code is utterly cool.

If you are going to use Promises (you should try them out with your own code!), use Kris Kowal's Q. The jQuery version is just some callback aggregator for writing cleaner jQuery code, but misses the point.

Regarding Future, I have no idea, I haven't seen that in any API.

Edit: Domenic Denicola's youtube talk on Promises from @Farm's comment below.

A quote from Michael Jackson (yes, Michael Jackson) from the video:

I want you to burn this phrase in your mind: A promise is an asynchronous value.

This is an excellent description: a promise is like a variable from the future - a first-class reference to something that, at some point, will exist (or happen).

How can I present a file for download from an MVC controller?

Although standard action results FileContentResult or FileStreamResult may be used for downloading files, for reusability, creating a custom action result might be the best solution.

As an example let's create a custom action result for exporting data to Excel files on the fly for download.

ExcelResult class inherits abstract ActionResult class and overrides the ExecuteResult method.

We are using FastMember package for creating DataTable from IEnumerable object and ClosedXML package for creating Excel file from the DataTable.

public class ExcelResult<T> : ActionResult
{
    private DataTable dataTable;
    private string fileName;

    public ExcelResult(IEnumerable<T> data, string filename, string[] columns)
    {
        this.dataTable = new DataTable();
        using (var reader = ObjectReader.Create(data, columns))
        {
            dataTable.Load(reader);
        }
        this.fileName = filename;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context != null)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            response.AddHeader("content-disposition", string.Format(@"attachment;filename=""{0}""", fileName));
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dataTable, "Sheet1");
                using (MemoryStream stream = new MemoryStream())
                {
                    wb.SaveAs(stream);
                    response.BinaryWrite(stream.ToArray());
                }
            }
        }
    }
}

In the Controller use the custom ExcelResult action result as follows

[HttpGet]
public async Task<ExcelResult<MyViewModel>> ExportToExcel()
{
    var model = new Models.MyDataModel();
    var items = await model.GetItems();
    string[] columns = new string[] { "Column1", "Column2", "Column3" };
    string filename = "mydata.xlsx";
    return new ExcelResult<MyViewModel>(items, filename, columns);
}

Since we are downloading the file using HttpGet, create an empty View without model and empty layout.

Blog post about custom action result for downloading files that are created on the fly:

https://acanozturk.blogspot.com/2019/03/custom-actionresult-for-files-in-aspnet.html

How to do Select All(*) in linq to sql

Why don't you use

DbTestDataContext obj = new DbTestDataContext();
var q =from a in obj.GetTable<TableName>() select a;

This is simple.

GROUP BY with MAX(DATE)

You cannot include non-aggregated columns in your result set which are not grouped. If a train has only one destination, then just add the destination column to your group by clause, otherwise you need to rethink your query.

Try:

SELECT t.Train, t.Dest, r.MaxTime
FROM (
      SELECT Train, MAX(Time) as MaxTime
      FROM TrainTable
      GROUP BY Train
) r
INNER JOIN TrainTable t
ON t.Train = r.Train AND t.Time = r.MaxTime

How to check encoding of a CSV file

In Python, You can Try...

from encodings.aliases import aliases
alias_values = set(aliases.values())

for encoding in set(aliases.values()):
    try:
        df=pd.read_csv("test.csv", encoding=encoding)
        print('successful', encoding)
    except:
        pass

How do I open a new window using jQuery?

Those are by no means the same. The first will simply send you to whatever URL you have assigned to window.location.href (in the same window you're currently in). The second makes a GET AJAX request.

Try this page: http://www.codebelt.com/jquery/open-new-browser-window-with-jquery-custom-size/

It gives a great example on how to open a new window*.

If you wish to use raw javascript then this is what you're looking for:

window.open(URL,name,specs,replace)

As seen in http://www.w3schools.com/jsref/met_win_open.asp

Connection failed: SQLState: '01000' SQL Server Error: 10061

I had the same error which was coming and dont need to worry about this error, just restart the server and restart the SQL services. This issue comes when there is low disk space issue and system will go into hung state and then the sql services will stop automatically.

SQL Server: How to check if CLR is enabled?

SELECT * FROM sys.configurations
WHERE name = 'clr enabled'

Is it possible to disable the network in iOS Simulator?

Use a simple Faraday cage to block or limit the external RF signal level.

You can make your own with aluminum foil. The openings should be smaller than the wavelength of your data service if that's what you want to block.

800 Mhz has a 37 cm (14") wavelength, 1900 Mhz has a 16 cm (6") wavelength.

This works better with an actual device than with the simulator since the Mac is hard to work on when inside the Faraday cage ;-)

enter image description here

Python executable not finding libpython shared library

I had the same problem and I solved it this way:

If you know where libpython resides at, I supposed it would be /usr/local/lib/libpython2.7.so.1.0 in your case, you can just create a symbolic link to it:

sudo ln -s /usr/local/lib/libpython2.7.so.1.0 /usr/lib/libpython2.7.so.1.0

Then try running ldd again and see if it worked.

How to enable cURL in PHP / XAMPP

For Ubuntu (and probably all Debian-Based) Linux Distributions:

sudo apt-get install php5-curl
sudo /etc/init.d/apache2 restart 

You might have seen PHP Fatal error: Call to undefined function curl_init() before.

How to update record using Entity Framework Core?

To update an entity with Entity Framework Core, this is the logical process:

  1. Create instance for DbContext class
  2. Retrieve entity by key
  3. Make changes on entity's properties
  4. Save changes

Update() method in DbContext:

Begins tracking the given entity in the Modified state such that it will be updated in the database when SaveChanges() is called.

Update method doesn't save changes in database; instead, it sets states for entries in DbContext instance.

So, We can invoke Update() method before to save changes in database.

I'll assume some object definitions to answer your question:

  1. Database name is Store

  2. Table name is Product

Product class definition:

public class Product
{
    public int? ProductID { get; set; }
    
    public string ProductName { get; set; }
    
    public string Description { get; set; }
    
    public decimal? UnitPrice { get; set; }
}

DbContext class definition:

public class StoreDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Your Connection String");

        base.OnConfiguring(optionsBuilder);
    }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>(entity =>
        {
            // Set key for entity
            entity.HasKey(p => p.ProductID);
        });
        
        base.OnModelCreating(modelBuilder);
    }
}

Logic to update entity:

using (var context = new StoreDbContext())
{
        // Retrieve entity by id
        // Answer for question #1
        var entity = context.Products.FirstOrDefault(item => item.ProductID == id);
        
        // Validate entity is not null
        if (entity != null)
        {
            // Answer for question #2

            // Make changes on entity
            entity.UnitPrice = 49.99m;
            entity.Description = "Collector's edition";
            
            /* If the entry is being tracked, then invoking update API is not needed. 
              The API only needs to be invoked if the entry was not tracked. 
              https://www.learnentityframeworkcore.com/dbcontext/modifying-data */
            // context.Products.Update(entity);
            
            // Save changes in database
            context.SaveChanges();
        }
}

What does the DOCKER_HOST variable do?

Ok, I think I got it.

The client is the docker command installed into OS X.

The host is the Boot2Docker VM.

The daemon is a background service running inside Boot2Docker.

This variable tells the client how to connect to the daemon.

When starting Boot2Docker, the terminal window that pops up already has DOCKER_HOST set, so that's why docker commands work. However, to run Docker commands in other terminal windows, you need to set this variable in those windows.

Failing to set it gives a message like this:

$ docker run hello-world
2014/08/11 11:41:42 Post http:///var/run/docker.sock/v1.13/containers/create: 
dial unix /var/run/docker.sock: no such file or directory

One way to fix that would be to simply do this:

$ export DOCKER_HOST=tcp://192.168.59.103:2375

But, as pointed out by others, it's better to do this:

$ $(boot2docker shellinit)
$ docker run hello-world
Hello from Docker. [...]

To spell out this possibly non-intuitive Bash command, running boot2docker shellinit returns a set of Bash commands that set environment variables:

export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1

Hence running $(boot2docker shellinit) generates those commands, and then runs them.

Changing the resolution of a VNC session in linux

Perhaps the most ignorant answer I've posted but here goes: Use TigerVNC client/viewer and check 'Resize remote session to local window' under Screen tab of options.

I don't know what the $%#@ TigerVNC client tells remote vncserver or xrandr or Xvnc or gnome or ... but it resizes when I change the TigerVNC Client window.

My setup:

  • Tiger VNC Server running on CentOS 6. Hosting GNOME desktop. (Works with RHEL 6.6 too)
  • Windows some version with Tiger VNC Client.

With this the resolution changes to fit the size of the client window no matter what it is, and it's not zooming, it's actual resolution change (I can see the new resolution in xrandr output).

I tried all I could to add a new resolution to the xrandr, but to no avail, always end up with 'xrandr: Failed to get size of gamma for output default' error.

Versions with which it works for me right now (although I've not had issues with ANY versions in the past, I just install the latest using yum install gnome-* tigervnc-server and works fine):

OS: RHEL 6.6 (Santiago)
VNC Server:
Name        : tigervnc-server
Arch        : x86_64
Version     : 1.1.0
Release     : 16.el6

# May be this is relevant..
$ xrandr --version
xrandr program version       1.4.0
Server reports RandR version 1.4
$ 

# I start the server using vncserver -geometry 800x600
# Xvnc is started by vncserver with following args:
/usr/bin/Xvnc :1 -desktop plabb13.sgdcelab.sabre.com:1 (sg219898) -auth /login/sg219898/.Xauthority 
-geometry 800x600 -rfbwait 30000 -rfbauth /login/sg219898/.vnc/passwd -rfbport 5901 -fp catalogue:/e
tc/X11/fontpath.d -pn


# I'm running GNOME (installed using sudo yum install gnome-*)
Name        : gnome-desktop
Arch        : x86_64
Version     : 2.28.2
Release     : 11.el6

Name        : gnome-session
Arch        : x86_64
Version     : 2.28.0
Release     : 22.el6

Connect using Tiger 32-bit VNC Client v1.3.1 on Windows 7.

How can I clone a private GitLab repository?

Before doing

git clone https://example.com/root/test.git

make sure that you have added ssh key in your system. Follow this : https://gitlab.com/profile/keys .

Once added run the above command. It will prompt for your gitlab username and password and on authentication, it will be cloned.

Setting HttpContext.Current.Session in a unit test

Try this:

        // MockHttpSession Setup
        var session = new MockHttpSession();

        // MockHttpRequest Setup - mock AJAX request
        var httpRequest = new Mock<HttpRequestBase>();

        // Setup this part of the HTTP request for AJAX calls
        httpRequest.Setup(req => req["X-Requested-With"]).Returns("XMLHttpRequest");

        // MockHttpContextBase Setup - mock request, cache, and session
        var httpContext = new Mock<HttpContextBase>();
        httpContext.Setup(ctx => ctx.Request).Returns(httpRequest.Object);
        httpContext.Setup(ctx => ctx.Cache).Returns(HttpRuntime.Cache);
        httpContext.Setup(ctx => ctx.Session).Returns(session);

        // MockHttpContext for cache
        var contextRequest = new HttpRequest("", "http://localhost/", "");
        var contextResponse = new HttpResponse(new StringWriter());
        HttpContext.Current = new HttpContext(contextRequest, contextResponse);

        // MockControllerContext Setup
        var context = new Mock<ControllerContext>();
        context.Setup(ctx => ctx.HttpContext).Returns(httpContext.Object);

        //TODO: Create new controller here
        //      Set controller's ControllerContext to context.Object

And Add the class:

public class MockHttpSession : HttpSessionStateBase
{
    Dictionary<string, object> _sessionDictionary = new Dictionary<string, object>();
    public override object this[string name]
    {
        get
        {
            return _sessionDictionary.ContainsKey(name) ? _sessionDictionary[name] : null;
        }
        set
        {
            _sessionDictionary[name] = value;
        }
    }

    public override void Abandon()
    {
        var keys = new List<string>();

        foreach (var kvp in _sessionDictionary)
        {
            keys.Add(kvp.Key);
        }

        foreach (var key in keys)
        {
            _sessionDictionary.Remove(key);
        }
    }

    public override void Clear()
    {
        var keys = new List<string>();

        foreach (var kvp in _sessionDictionary)
        {
            keys.Add(kvp.Key);
        }

        foreach(var key in keys)
        {
            _sessionDictionary.Remove(key);
        }
    }
}

This will allow you to test with both session and cache.

How to output to the console in C++/Windows

The AllocConsole Windows API function will create a console window for your application.

How to make a HTML Page in A4 paper size page(s)?

Technically, you could, but it would take a lot of work to get all browsers to print out the page exactly as it is displayed on screen. Also, most browsers force the URL, print date and page numbering on the print-out, which is not always desired. This cannot be altered or disabled.

Instead, I would advise to create a PDF based on the contents on screen and serve the PDF for downloading and/or printing. Although most available PDF libraries are paid, there are a few free alternatives available for creating basic PDFs.

TCPDF output without saving file

If You want to open dialogue window in browser to save, not open with PDF browser viewer (I was looking for this solution for a while), You should use 'D':

$pdf->Output('name.pdf', 'D');

Python: "Indentation Error: unindent does not match any outer indentation level"

Don't forget the use of """ comments. These need precise indentation too (a 1/2 hr job for me resolving this damn error too!)

How to extract an assembly from the GAC?

Copying from a command line is unnecessary. I typed in the name of the DLL from the Start Window search. I chose See More Results. The one in the GAC was returned in the search window. I right clicked on it and said open file location. It opened in normal Windows Explorer. I copied the file. I closed the window. Done.

How to display with n decimal places in Matlab

i use like tim say sprintf('%0.6f', x), it's a string then i change it to number by using command str2double(x).

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

With pure html (no JS), you can't really substitute a radio-button for an image (at least, I don't think you can). You could, though use the following to make the same connection to the user:

<form action="" method="post">
    <fieldset>
       <input type="radio" name="feeling" id="feelingSad" value="sad" /><label for="feelingSad"><img src="path/to/sad.png" /></label>
       <label for="feelingHappy"><input type="radio" name="feeling" id="feelingHappy" value="happy" /><img src="path/to/happy.png" /></label>
    </fieldset>
</form>

Change WPF controls from a non-main thread using Dispatcher.Invoke

When a thread is executing and you want to execute the main UI thread which is blocked by current thread, then use the below:

current thread:

Dispatcher.CurrentDispatcher.Invoke(MethodName,
    new object[] { parameter1, parameter2 }); // if passing 2 parameters to method.

Main UI thread:

Application.Current.Dispatcher.BeginInvoke(
    DispatcherPriority.Background, new Action(() => MethodName(parameter)));

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

How to start automatic download of a file in Internet Explorer?

I hate when sites complicate download so much and use hacks instead of a good old link.

Dead simple version:

<a href="file.zip">Start automatic download!</a>

It works! In every browser!


If you want to download a file that is usually displayed inline (such as an image) then HTML5 has a download attribute that forces download of the file. It also allows you to override filename (although there is a better way to do it):

<a href="report-generator.php" download="result.xls">Download</a>

Version with a "thanks" page:

If you want to display "thanks" after download, then use:

<a href="file.zip" 
   onclick="if (event.button==0) 
     setTimeout(function(){document.body.innerHTML='thanks!'},500)">
 Start automatic download!
</a>

Function in that setTimeout might be more advanced and e.g. download full page via AJAX (but don't navigate away from the page — don't touch window.location or activate other links).

The point is that link to download is real, can be copied, dragged, intercepted by download accelerators, gets :visited color, doesn't re-download if page is left open after browser restart, etc.

That's what I use for ImageOptim

REST API - file (ie images) processing - best practices

Your second solution is probably the most correct. You should use the HTTP spec and mimetypes the way they were intended and upload the file via multipart/form-data. As far as handling the relationships, I'd use this process (keeping in mind I know zero about your assumptions or system design):

  1. POST to /users to create the user entity.
  2. POST the image to /images, making sure to return a Location header to where the image can be retrieved per the HTTP spec.
  3. PATCH to /users/carPhoto and assign it the ID of the photo given in the Location header of step 2.

jquery animate background position

try backgroundPosition:"(-20px 0)"

Just to double check are you referencing this the background position plugin?

Example of it on jsfiddle with the background position plugin.

How to build a Horizontal ListView with RecyclerView?

Is there a better way to implement this now with Recyclerview now?

Yes.

When you use a RecyclerView, you need to specify a LayoutManager that is responsible for laying out each item in the view. The LinearLayoutManager allows you to specify an orientation, just like a normal LinearLayout would.

To create a horizontal list with RecyclerView, you might do something like this:

LinearLayoutManager layoutManager
    = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

RecyclerView myList = (RecyclerView) findViewById(R.id.my_recycler_view);
myList.setLayoutManager(layoutManager);

How to get all selected values from <select multiple=multiple>?

if you want as you expressed with breaks after each value;

$('#select-meal-type').change(function(){
    var meals = $(this).val();
    var selectedmeals = meals.join(", "); // there is a break after comma

    alert (selectedmeals); // just for testing what will be printed
})

Convert Xml to DataTable

You can use this code(Recommended)

 MemoryStream objMS = new MemoryStream();
 DataTable oDT = new DataTable();//Your DataTable which you want to convert
 oDT.WriteXml(objMS);
 objMS.Position = 0;
 XPathDocument result = new XPathDocument(objMS);

This is another way but first ex. is recommended

StringWriter objSW = new StringWriter();
DataTable oDt = new DataTable();//Your DataTable which you want to convert
oDt.WriteXml(objSW);
string result = objSW.ToString();

How can I color a UIImage in Swift?

Swift 3 version with scale and Orientation from @kuzdu answer

extension UIImage {

    func mask(_ color: UIColor) -> UIImage? {
        let maskImage = cgImage!

        let width = (cgImage?.width)!
        let height = (cgImage?.height)!
        let bounds = CGRect(x: 0, y: 0, width: width, height: height)

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!

        context.clip(to: bounds, mask: maskImage)
        context.setFillColor(color.cgColor)
        context.fill(bounds)

        if let cgImage = context.makeImage() {
            let coloredImage = UIImage.init(cgImage: cgImage, scale: scale, orientation: imageOrientation)
            return coloredImage
        } else {
            return nil
        }
    }
}

Latest jQuery version on Google's CDN

I don't know if/where it's published, but you can get the latest release by omitting the minor and build numbers.

Latest 1.8.x:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

Latest 1.x:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

However, do keep in mind that these links have a much shorter cache timeout than with the full version number, so your users may be downloading them more than you'd like. See The crucial .0 in Google CDN references to jQuery 1.x.0 for more information.

What equivalents are there to TortoiseSVN, on Mac OSX?

My previous version of this answer had links, that kept becoming dead.
So, I've pointed it to the internet archive to preserve the original answer.

Subversion client releases for Windows and Macintosh

Wiki - Subversion clients comparison table

Extract elements of list at odd positions

I like List comprehensions because of their Math (Set) syntax. So how about this:

L = [1, 2, 3, 4, 5, 6, 7]
odd_numbers = [y for x,y in enumerate(L) if x%2 != 0]
even_numbers = [y for x,y in enumerate(L) if x%2 == 0]

Basically, if you enumerate over a list, you'll get the index x and the value y. What I'm doing here is putting the value y into the output list (even or odd) and using the index x to find out if that point is odd (x%2 != 0).

Can two applications listen to the same port?

Short answer:

Going by the answer given here. You can have two applications listening on the same IP address, and port number, so long one of the port is a UDP port, while other is a TCP port.

Explanation:

The concept of port is relevant on the transport layer of the TCP/IP stack, thus as long as you are using different transport layer protocols of the stack, you can have multiple processes listening on the same <ip-address>:<port> combination.

One doubt that people have is if two applications are running on the same <ip-address>:<port> combination, how will a client running on a remote machine distinguish between the two? If you look at the IP layer packet header (https://en.wikipedia.org/wiki/IPv4#Header), you will see that bits 72 to 79 are used for defining protocol, this is how the distinction can be made.

If however you want to have two applications on same TCP <ip-address>:<port> combination, then the answer is no (An interesting exercise will be launch two VMs, give them same IP address, but different MAC addresses, and see what happens - you will notice that some times VM1 will get packets, and other times VM2 will get packets - depending on ARP cache refresh).

I feel that by making two applications run on the same <op-address>:<port> you want to achieve some kind of load balancing. For this you can run the applications on different ports, and write IP table rules to bifurcate the traffic between them.

Also see @user6169806's answer.

Check if a String contains a special character

What do you exactly call "special character" ? If you mean something like "anything that is not alphanumeric" you can use org.apache.commons.lang.StringUtils class (methods IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable).

If it is not so trivial, you can use a regex that defines the exact character list you accept and match the string against it.

How to disable button in React.js

In HTML,

<button disabled/>
<buttton disabled="true">
<buttton disabled="false">
<buttton disabled="21">

All of them boils down to disabled="true" that is because it returns true for a non-empty string. Hence, in order to return false, pass a empty string in a conditional statement like this.input.value?"true":"".

render() {
    return (
        <div className="add-item">
            <input type="text" className="add-item__input" ref={(input) => this.input = input} placeholder={this.props.placeholder} />
            <button disabled={this.input.value?"true":""} className="add-item__button" onClick={this.add.bind(this)}>Add</button>
        </div>
    );
}

Embedding SVG into ReactJS

If you want to load it from a file, you may try to use React-inlinesvg - that's pretty simple and straight-forward.

import SVG from 'react-inlinesvg';

<SVG
  src="/path/to/myfile.svg"
  preloader={<Loader />}
  onLoad={(src) => {
    myOnLoadHandler(src);
  }}
>
  Here's some optional content for browsers that don't support XHR or inline
  SVGs. You can use other React components here too. Here, I'll show you.
  <img src="/path/to/myfile.png" />
</SVG>

Java: convert seconds to minutes, hours and days

It should be like:

    public static void calculateTime(long seconds) {
            int day = (int)TimeUnit.SECONDS.toDays(seconds);        
            long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
            long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
            long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);

            System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);

        }

Explanation:

TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours with out consideration for days. Minus the hours for days you already got i.e, day*24. You now got remaining hours. Same for minute and second. You need to minus the already got hour and minutes respectively.

SQL Query - how do filter by null or not null

Just like you said

select * from tbl where statusid is null

or

select * from tbl where statusid is not null

If your statusid is not null, then it will be selected just fine when you have an actual value, no need for any "if" logic if that is what you were thinking

select * from tbl where statusid = 123 -- the record(s) returned will not have null statusid

if you want to select where it is null or a value, try

select * from tbl where statusid = 123 or statusid is null

how to split the ng-repeat data with three columns using bootstrap

<div class="row">
  <div class="col-md-4" ng-repeat="remainder in [0,1,2]">
    <ul>
      <li ng-repeat="item in items" ng-if="$index % 3 == remainder">{{item}}</li>
    </ul>
  </div>
</div>

Using Google maps API v3 how do I get LatLng with a given address?

There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

To shorten it up a little:

geocoder = new google.maps.Geocoder();

function codeAddress() {

    //In this case it gets the address from an element on the page, but obviously you  could just pass it to the method instead
    var address = document.getElementById( 'address' ).value;

    geocoder.geocode( { 'address' : address }, function( results, status ) {
        if( status == google.maps.GeocoderStatus.OK ) {

            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter( results[0].geometry.location );
            var marker = new google.maps.Marker( {
                map     : map,
                position: results[0].geometry.location
            } );
        } else {
            alert( 'Geocode was not successful for the following reason: ' + status );
        }
    } );
}

foreach with index

I like being able to use foreach, so I made an extension method and a structure:

public struct EnumeratedInstance<T>
{
    public long cnt;
    public T item;
}

public static IEnumerable<EnumeratedInstance<T>> Enumerate<T>(this IEnumerable<T> collection)
{
    long counter = 0;
    foreach (var item in collection)
    {
        yield return new EnumeratedInstance<T>
        {
            cnt = counter,
            item = item
        };
        counter++;
    }
}

and an example use:

foreach (var ii in new string[] { "a", "b", "c" }.Enumerate())
{
    Console.WriteLine(ii.item + ii.cnt);
}

One nice thing is that if you are used to the Python syntax, you can still use it:

foreach (var ii in Enumerate(new string[] { "a", "b", "c" }))

Freeing up a TCP/IP port?

sudo killall -9 "process name"

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

Displaying a message in iOS which has the same functionality as Toast in Android

For me this solution works fine: https://github.com/cruffenach/CRToast

enter image description here

Example how use it:

    NSDictionary *options = @{
                          kCRToastTextKey : @"Hello World!",
                          kCRToastTextAlignmentKey : @(NSTextAlignmentCenter),
                          kCRToastBackgroundColorKey : [UIColor redColor],
                          kCRToastAnimationInTypeKey : @(CRToastAnimationTypeGravity),
                          kCRToastAnimationOutTypeKey : @(CRToastAnimationTypeGravity),
                          kCRToastAnimationInDirectionKey : @(CRToastAnimationDirectionLeft),
                          kCRToastAnimationOutDirectionKey : @(CRToastAnimationDirectionRight)
                          };
[CRToastManager showNotificationWithOptions:options
                            completionBlock:^{
                                NSLog(@"Completed");
                            }];

How to check if a key exists in Json Object and get its value

JSONObject root= new JSONObject();
JSONObject container= root.getJSONObject("LabelData");

try{
//if key will not be available put it in the try catch block your program 
 will work without error 
String Video=container.getString("video");
}
catch(JsonException e){

 if key will not be there then this block will execute

 } 
 if(video!=null || !video.isEmpty){
  //get Value of video
}else{
  //other vise leave it
 }

i think this might help you

Can I have multiple primary keys in a single table?

Some people use the term "primary key" to mean exactly an integer column that gets its values generated by some automatic mechanism. For example AUTO_INCREMENT in MySQL or IDENTITY in Microsoft SQL Server. Are you using primary key in this sense?

If so, the answer depends on the brand of database you're using. In MySQL, you can't do this, you get an error:

mysql> create table foo (
  id int primary key auto_increment, 
  id2 int auto_increment
);
ERROR 1075 (42000): Incorrect table definition; 
there can be only one auto column and it must be defined as a key

In some other brands of database, you are able to define more than one auto-generating column in a table.

How to implement a SQL like 'LIKE' operator in java?

You could turn '%string%' to contains(), 'string%' to startsWith() and '%string"' to endsWith().

You should also run toLowerCase() on both the string and pattern as LIKE is case-insenstive.

Not sure how you'd handle '%string%other%' except with a Regular Expression though.

If you're using Regular Expressions:

How do I link a JavaScript file to a HTML file?

This is how you link a JS file in HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script> - tag is used to define a client-side script, such as a JavaScript.

type - specify the type of the script

src - script file name and path

How to check if the user can go back in browser history or not

A solution that actually works

window.history.length == 1

This works on Chrome, Firefox, and Edge. You can use the following piece of JQuery code that worked for me on the latest versions of all of the above 3 browsers if you want to hide or remove a back button on your developed web page when there is no window history.

$(window).load(function() {
        if (window.history.length == 1) {
            $("#back-button").remove();
        }
    })

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

SQL sum with condition

Try this instead:

SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)

Explanation

Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:

The CASE expression has two formats:

  • The simple CASE expression compares an expression to a set of simple expressions to determine the result.
  • The searched CASE expression evaluates a set of Boolean expressions to determine the result.

You want the searched CASE expression syntax:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.

Android AudioRecord example

Here I am posting you the some code example which record good quality of sound using AudioRecord API.

Note: If you use in emulator the sound quality will not much good because we are using sample rate 8k which only supports in emulator. In device use sample rate to 44.1k for better quality.

public class Audio_Record extends Activity {
    private static final int RECORDER_SAMPLERATE = 8000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private AudioRecord recorder = null;
    private Thread recordingThread = null;
    private boolean isRecording = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setButtonHandlers();
        enableButtons(false);

        int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
                RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING); 
    }

    private void setButtonHandlers() {
        ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
        ((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
    }

    private void enableButton(int id, boolean isEnable) {
        ((Button) findViewById(id)).setEnabled(isEnable);
    }

    private void enableButtons(boolean isRecording) {
        enableButton(R.id.btnStart, !isRecording);
        enableButton(R.id.btnStop, isRecording);
    }

    int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
    int BytesPerElement = 2; // 2 bytes in 16bit format

    private void startRecording() {

        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

        recorder.startRecording();
        isRecording = true;
        recordingThread = new Thread(new Runnable() {
            public void run() {
                writeAudioDataToFile();
            }
        }, "AudioRecorder Thread");
        recordingThread.start();
    }

        //convert short to byte
    private byte[] short2byte(short[] sData) {
        int shortArrsize = sData.length;
        byte[] bytes = new byte[shortArrsize * 2];
        for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
        }
        return bytes;

    }

    private void writeAudioDataToFile() {
        // Write the output audio in byte

        String filePath = "/sdcard/voice8K16bitmono.pcm";
        short sData[] = new short[BufferElements2Rec];

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        while (isRecording) {
            // gets the voice output from microphone to byte format

            recorder.read(sData, 0, BufferElements2Rec);
            System.out.println("Short writing to file" + sData.toString());
            try {
                // // writes the data to file from buffer
                // // stores the voice buffer
                byte bData[] = short2byte(sData);
                os.write(bData, 0, BufferElements2Rec * BytesPerElement);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRecording() {
        // stops the recording activity
        if (null != recorder) {
            isRecording = false;
            recorder.stop();
            recorder.release();
            recorder = null;
            recordingThread = null;
        }
    }

    private View.OnClickListener btnClick = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btnStart: {
                enableButtons(true);
                startRecording();
                break;
            }
            case R.id.btnStop: {
                enableButtons(false);
                stopRecording();
                break;
            }
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}

For more detail try this AUDIORECORD BLOG.

Happy Coding !!

Setting onSubmit in React.js

I'd also suggest moving the event handler outside render.

var OnSubmitTest = React.createClass({

  submit: function(e){
    e.preventDefault();
    alert('it works!');
  }

  render: function() {
    return (
      <form onSubmit={this.submit}>
        <button>Click me</button>
      </form>
    );
  }
});

What are callee and caller saved registers?

The caller-saved / callee-saved terminology is based on a pretty braindead inefficient model of programming where callers actually do save/restore all the call-clobbered registers (instead of keeping long-term-useful values elsewhere), and callees actually do save/restore all the call-preserved registers (instead of just not using some or any of them).

Or you have to understand that "caller-saved" means "saved somehow if you want the value later".

In reality, efficient code lets values get destroyed when they're no longer needed. Compilers typically make functions that save a few call-preserved registers at the start of a function (and restore them at the end). Inside the function, they use those regs for values that need to survive across function calls.

I prefer "call-preserved" vs. "call-clobbered", which are unambiguous and self-describing once you've heard of the basic concept, and don't require any serious mental gymnastics to think about from the caller's perspective or the callee's perspective. (Both terms are from the same perspective).

Plus, these terms differ by more than one letter.

The terms volatile / non-volatile are pretty good, by analogy with storage which loses its value on power-loss or not, (like DRAM vs. Flash). But the C volatile keyword has a totally different technical meaning, so that's a downside to "(non)-volatile" when describing C calling conventions.


  • Call-clobbered, aka caller-saved or volatile registers are good for scratch / temporary values that aren't needed after the next function call.

From the callee's perspective, your function can freely overwrite (aka clobber) these registers without saving/restoring.

From a caller's perspective, call foo destroys (aka clobbers) all the call-clobbered registers, or at least you have to assume it does.

You can write private helper functions that have a custom calling convention, e.g. you know they don't modify a certain register. But if all you know (or want to assume or depend on) is that the target function follows the normal calling convention, then you have to treat a function call as if it does destroy all the call-clobbered registers. That's literally what the name come from: a call clobbers those registers.

Some compilers that do inter-procedural optimization can also create internal-use-only definitions of functions that don't follow the ABI, using a custom calling convention.

  • Call-preserved, aka callee-saved or non-volatile registers keep their values across function calls. This is useful for loop variables in a loop that makes function calls, or basically anything in a non-leaf function in general.

From a callee's perspective, these registers can't be modified unless you save the original value somewhere so you can restore it before returning. Or for registers like the stack pointer (which is almost always call-preserved), you can subtract a known offset and add it back again before returning, instead of actually saving the old value anywhere. i.e. you can restore it by dead reckoning, unless you allocate a runtime-variable amount of stack space. Then typically you restore the stack pointer from another register.

A function that can benefit from using a lot of registers can save/restore some call-preserved registers just so it can use them as more temporaries, even if it doesn't make any function calls. Normally you'd only do this after running out of call-clobbered registers to use, because save/restore typically costs a push/pop at the start/end of the function. (Or if your function has multiple exit paths, a pop in each of them.)


The name "caller-saved" is misleading: you don't have to specially save/restore them. Normally you arrange your code to have values that need to survive a function call in call-preserved registers, or somewhere on the stack, or somewhere else that you can reload from. It's normal to let a call destroy temporary values.


An ABI or calling convention defines which are which

See for example What registers are preserved through a linux x86-64 function call for the x86-64 System V ABI.

Also, arg-passing registers are always call-clobbered in all function-calling conventions I'm aware of. See Are rdi and rsi caller saved or callee saved registers?

But system-call calling conventions typically make all the registers except the return value call-preserved. (Usually including even condition-codes / flags.) See What are the calling conventions for UNIX & Linux system calls on i386 and x86-64

How to add include and lib paths to configure/make cycle?

Set LDFLAGS and CFLAGS when you run make:

$ LDFLAGS="-L/home/me/local/lib" CFLAGS="-I/home/me/local/include" make

If you don't want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/local/lib

converting drawable resource image into bitmap

First Create Bitmap Image

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);

now set bitmap in Notification Builder Icon....

Notification.Builder.setLargeIcon(bmp);

How do I check if a Sql server string is null or empty

[Column_name] IS NULL OR LEN(RTRIM(LTRIM([Column_name]))) = 0

Google Maps v2 - set both my location and zoom in

You cannot animate two things (like zoom in and go to my location) in one google map?

From a coding standpoint, you would do them sequentially:

    CameraUpdate center=
        CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
                                                 -73.98180484771729));
    CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);

    map.moveCamera(center);
    map.animateCamera(zoom);

Here, I move the camera first, then animate the camera, though both could be animateCamera() calls. Whether GoogleMap consolidates these into a single event, I can't say, as it goes by too fast. :-)

Here is the sample project from which I pulled the above code.


Sorry, this answer is flawed. See Rob's answer for a way to truly do this in one shot, by creating a CameraPosition and then creating a CameraUpdate from that CameraPosition.

width:auto for <input> fields

As stated in the other answer, width: auto doesn't work due to the width being generated by the input's size attribute, which cannot be set to "auto" or anything similar.

There are a few workarounds you can use to cause it to play nicely with the box model, but nothing fantastic as far as I know.

First you can set the padding in the field using percentages, making sure that the width adds up to 100%, e.g.:

input {
  width: 98%;
  padding: 1%;
}

Another thing you might try is using absolute positioning, with left and right set to 0. Using this markup:

<fieldset>
    <input type="text" />
</fieldset>

And this CSS:

fieldset {
  position: relative;
}

input {
    position: absolute;
    left: 0;
    right: 0;
}

This absolute positioning will cause the input to fill the parent fieldset horizontally, regardless of the input's padding or margin. However a huge downside of this is that you now have to deal with the height of the fieldset, which will be 0 unless you set it. If your inputs are all the same height this will work for you, simply set the fieldset's height to whatever the input's height should be.

Other than this there are some JS solutions, but I don't like applying basic styling with JS.

How to set cellpadding and cellspacing in table with CSS?

Use padding on the cells and border-spacing on the table. The former will give you cellpadding while the latter will give you cellspacing.

table { border-spacing: 5px; } /* cellspacing */

th, td { padding: 5px; } /* cellpadding */

jsFiddle Demo

How to Disable GUI Button in Java

You create the frame with button enable, do some test to see if btn1Cliked is true, and that's all.

Then you have the actionPerformed method that does nothing with your button. So, if you don't have any action related, your button status will never be evaluated again.

Exec : display stdout "live"

After reviewing all the other answers, I ended up with this:

function oldSchoolMakeBuild(cb) {
    var makeProcess = exec('make -C ./oldSchoolMakeBuild',
         function (error, stdout, stderr) {
             stderr && console.error(stderr);
             cb(error);
        });
    makeProcess.stdout.on('data', function(data) {
        process.stdout.write('oldSchoolMakeBuild: '+ data);
    });
}

Sometimes data will be multiple lines, so the oldSchoolMakeBuild header will appear once for multiple lines. But this didn't bother me enough to change it.

Converting int to bytes in Python 3

The behaviour comes from the fact that in Python prior to version 3 bytes was just an alias for str. In Python3.x bytes is an immutable version of bytearray - completely new type, not backwards compatible.

Jquery date picker z-index issue

I had this issue as well, since the datepicker uses the input's z-index, I added the following css

#dialogID input,.modal-dialog input, .modal-dialog .input-group .form-control{
  z-index:inherit;
}

Just take the rule that applies to yours, either by parent id, class, or in my case a bootstrap dialog, using their input-group and form-control.

Negate if condition in bash script

If you're feeling lazy, here's a terse method of handling conditions using || (or) and && (and) after the operation:

wget -q --tries=10 --timeout=20 --spider http://google.com || \
{ echo "Sorry you are Offline" && exit 1; }

How to import popper.js?

You can download and import all of Bootstrap, and Popper, with a single command using Fetch Injection:

fetchInject([
  'https://npmcdn.com/[email protected]/dist/js/bootstrap.min.js',
  'https://cdn.jsdelivr.net/popper.js/1.0.0-beta.3/popper.min.js'
], fetchInject([
  'https://cdn.jsdelivr.net/jquery/3.1.1/jquery.slim.min.js',
  'https://npmcdn.com/[email protected]/dist/js/tether.min.js'
]));

Add CSS files if you need those too. Adjust versions and external sources to meet your needs and consider using sub-resource integrity checking if you're not hosting the files on your own domain or don't trust the source.

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

The following code did the trick for me.

html:

<div class="back" onclick="goBackOrGoHome()">
  Back
</div>

js:

home_url = [YOUR BASE URL];

pathArray = document.referrer.split( '/' );
protocol = pathArray[0];
host = pathArray[2];

url_before = protocol + '//' + host;

url_now = window.location.protocol + "//" + window.location.host;


function goBackOrGoHome(){
  if ( url_before == url_now) {
    window.history.back();    
  }else{
    window.location = home_url;
  };
}

So, you use document.referrer to set the domain of the page you come from. Then you compare that with your current url using window.location.

If they are from the same domain, it means you are coming from your own site and you send them window.history.back(). If they are not the same, you are coming from somewhere else and you should redirect home or do whatever you like.

OS X Framework Library not loaded: 'Image not found'

If you accidentally reset your keychain, this can occur due to missing Apple certificates in the keychain. I followed this to solve my problem.

I had the same issue and was able to fix by re-downloading the WWDR (Apple Worldwide Developer Relations Certification Authority). Download from here: http://developer.apple.com/certificationauthority/AppleWWDRCA.cer

Conversion failed when converting the varchar value 'simple, ' to data type int

In order to avoid such error you could use CASE + ISNUMERIC to handle scenarios when you cannot convert to int.
Change

CONVERT(INT, CONVERT(VARCHAR(12), a.value))

To

CONVERT(INT,
        CASE
        WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value)
        ELSE 0 END) 

Basically this is saying if you cannot convert me to int assign value of 0 (in my example)

Alternatively you can look at this article about creating a custom function that will check if a.value is number: http://www.tek-tips.com/faqs.cfm?fid=6423

find first sequence item that matches a criterion

a=[100,200,300,400,500]
def search(b):
 try:
  k=a.index(b)
  return a[k] 
 except ValueError:
    return 'not found'
print(search(500))

it'll return the object if found else it'll return "not found"

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

i initially came here with the same problem. I had jus installed Oracle 12c on Windows 8 (64-bit),but i have since resolved it by 'TNSPING xe' on the command line... If the connection isn't established or name not found,try the database name,in my case it was 'orcl'... 'TNSPING orcl' again and if it pings successfully then u need to change the SID to 'orcl' in this case (or whatever database name u used)...

How to inject a Map using the @Value Spring Annotation?

To get this working with YAML, do this:

property-name: '{
  key1: "value1",
  key2: "value2"
}'