Programs & Examples On #Enforcement

The maximum message size quota for incoming messages (65536) has been exceeded

Updating the config didn't work for me, but I was able to edit the binding programmatically:

private YourAPIClient GetClient()
{
    Uri baseAddress = new Uri(APIURL);

    var binding = new BasicHttpBinding();
    binding.MaxReceivedMessageSize = 20000000;
    binding.MaxBufferSize = 20000000;
    binding.MaxBufferPoolSize = 20000000;
    binding.AllowCookies = true;

    var readerQuotas = new XmlDictionaryReaderQuotas();
    readerQuotas.MaxArrayLength = 20000000;
    readerQuotas.MaxStringContentLength = 20000000;
    readerQuotas.MaxDepth = 32;
    binding.ReaderQuotas = readerQuotas;

    if (baseAddress.Scheme.ToLower() == "https")
        binding.Security.Mode = BasicHttpSecurityMode.Transport;

    var client = new YourAPIClient(binding, new EndpointAddress(baseAddress));
    return client;
}

WCF Service , how to increase the timeout?

The timeout configuration needs to be set at the client level, so the configuration I was setting in the web.config had no effect, the WCF test tool has its own configuration and there is where you need to set the timeout.

How to prevent rm from reporting that a file was not found?

-f is the correct flag, but for the test operator, not rm

[ -f "$THEFILE" ] && rm "$THEFILE"

this ensures that the file exists and is a regular file (not a directory, device node etc...)

How do I dynamically assign properties to an object in TypeScript?

Store any new property on any kind of object by typecasting it to 'any':

var extend = <any>myObject;
extend.NewProperty = anotherObject;

Later on you can retrieve it by casting your extended object back to 'any':

var extendedObject = <any>myObject;
var anotherObject = <AnotherObjectType>extendedObject.NewProperty;

How to change the display name for LabelFor in razor in mvc3?

Decorate the model property with the DisplayName attribute.

correct way to use super (argument passing)

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

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

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

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

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

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

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

What is the simplest way to convert array to vector?

Personally, I quite like the C++2011 approach because it neither requires you to use sizeof() nor to remember adjusting the array bounds if you ever change the array bounds (and you can define the relevant function in C++2003 if you want, too):

#include <iterator>
#include <vector>
int x[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(std::begin(x), std::end(x));

Obviously, with C++2011 you might want to use initializer lists anyway:

std::vector<int> v({ 1, 2, 3, 4, 5 });

Check if an element is present in a Bash array

You could do:

if [[ " ${arr[*]} " == *" d "* ]]; then
    echo "arr contains d"
fi

This will give false positives for example if you look for "a b" -- that substring is in the joined string but not as an array element. This dilemma will occur for whatever delimiter you choose.

The safest way is to loop over the array until you find the element:

array_contains () {
    local seeking=$1; shift
    local in=1
    for element; do
        if [[ $element == "$seeking" ]]; then
            in=0
            break
        fi
    done
    return $in
}

arr=(a b c "d e" f g)
array_contains "a b" "${arr[@]}" && echo yes || echo no    # no
array_contains "d e" "${arr[@]}" && echo yes || echo no    # yes

Here's a "cleaner" version where you just pass the array name, not all its elements

array_contains2 () { 
    local array="$1[@]"
    local seeking=$2
    local in=1
    for element in "${!array}"; do
        if [[ $element == "$seeking" ]]; then
            in=0
            break
        fi
    done
    return $in
}

array_contains2 arr "a b"  && echo yes || echo no    # no
array_contains2 arr "d e"  && echo yes || echo no    # yes

For associative arrays, there's a very tidy way to test if the array contains a given key: The -v operator

$ declare -A arr=( [foo]=bar [baz]=qux )
$ [[ -v arr[foo] ]] && echo yes || echo no
yes
$ [[ -v arr[bar] ]] && echo yes || echo no
no

See 6.4 Bash Conditional Expressions in the manual.

How to pip or easy_install tkinter on Windows

Had the same problem in Linux. This solved it. (I'm on Debian 9 derived Bunsen Helium)

$ sudo apt-get install python3-tk

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

How to set background color of a View

This works for me

v.getBackground().setTint(Color.parseColor("#212121"));

That way only changes the color of the background without change the background itself. This is usefull for example if you have a background with rounded corners.

Script Tag - async & defer

It seems the behavior of defer and async is browser dependent, at least on the execution phase. NOTE, defer only applies to external scripts. I'm assuming async follows same pattern.

In IE 11 and below, the order seems to be like this:

  • async (could partially execute while page loading)
  • none (could execute while page loading)
  • defer (executes after page loaded, all defer in order of placement in file)

In Edge, Webkit, etc, the async attribute seems to be either ignored or placed at the end:

  • data-pagespeed-no-defer (executes before any other scripts, while page is loading)
  • none (could execute while page is loading)
  • defer (waits until DOM loaded, all defer in order of placement in file)
  • async (seems to wait until DOM loaded)

In newer browsers, the data-pagespeed-no-defer attribute runs before any other external scripts. This is for scripts that don't depend on the DOM.

NOTE: Use defer when you need an explicit order of execution of your external scripts. This tells the browser to execute all deferred scripts in order of placement in the file.

ASIDE: The size of the external javascripts did matter when loading...but had no effect on the order of execution.

If you're worried about the performance of your scripts, you may want to consider minification or simply loading them dynamically with an XMLHttpRequest.

Changing the URL in react-router v4 without using Redirect or Link

Try this,

this.props.router.push('/foo')

warning works for versions prior to v4

and

this.props.history.push('/foo')

for v4 and above

Speed tradeoff of Java's -Xms and -Xmx options

It is difficult to say how the memory allocation will affect your speed. It depends on the garbage collection algorithm the JVM is using. For example if your garbage collector needs to pause to do a full collection, then if you have 10 more memory than you really need then the collector will have 10 more garbage to clean up.

If you are using java 6 you can use the jconsole (in the bin directory of the jdk) to attach to your process and watch how the collector is behaving. In general the collectors are very smart and you won't need to do any tuning, but if you have a need there are numerous options you have use to further tune the collection process.

How to represent the double quotes character (") in regex?

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex.

However, because java uses double quotes to delimit String constants, if you want to create a string in java with a double quote in it, you must escape them.

This code will test if your String matches:

if (str.matches("\".*\"")) {
    // this string starts and end with a double quote
}

Note that you don't need to add start and end of input markers (^ and $) in the regex, because matches() requires that the whole input be matched to return true - ^ and $ are implied.

How to get the current directory of the cmdlet being executed

You can also use:

(Resolve-Path .\).Path

The part in brackets returns a PathInfo object.

(Available since PowerShell 2.0.)

How to convert an NSTimeInterval (seconds) into minutes

Brief Description

  1. The answer from Brian Ramsay is more convenient if you only want to convert to minutes.
  2. If you want Cocoa API do it for you and convert your NSTimeInterval not only to minutes but also to days, months, week, etc,... I think this is a more generic approach
  3. Use NSCalendar method:

    • (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts

    • "Returns, as an NSDateComponents object using specified components, the difference between two supplied dates". From the API documentation.

  4. Create 2 NSDate whose difference is the NSTimeInterval you want to convert. (If your NSTimeInterval comes from comparing 2 NSDate you don't need to do this step, and you don't even need the NSTimeInterval).

  5. Get your quotes from NSDateComponents

Sample Code

// The time interval 
NSTimeInterval theTimeInterval = 326.4;

// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];

// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1]; 

// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;

NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];

NSLog(@"Conversion: %dmin %dhours %ddays %dmoths",[conversionInfo minute], [conversionInfo hour], [conversionInfo day], [conversionInfo month]);

[date1 release];
[date2 release];

Known issues

  • Too much for just a conversion, you are right, but that's how the API works.
  • My suggestion: if you get used to manage your time data using NSDate and NSCalendar, the API will do the hard work for you.

How to use Selenium with Python?

There are a lot of sources for selenium - here is good one for simple use Selenium, and here is a example snippet too Selenium Examples

You can find a lot of good sources to use selenium, it's not too hard to get it set up and start using it.

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

An efficient compression algorithm for short text strings

You might want to take a look at Standard Compression Scheme for Unicode.

SQL Server 2008 R2 use it internally and can achieve up to 50% compression.

How to select all and copy in vim?

There are a few important informations missing from your question:

  • output of $ vim --version?
  • OS?
  • CLI or GUI?
  • local or remote?
  • do you use tmux? screen?

If your Vim was built with clipboard support, you are supposed to use the clipboard register like this, in normal mode:

gg"+yG

If your Vim doesn't have clipboard support, you can manage to copy text from Vim to your OS clipboard via other programs. This pretty much depends on your OS but you didn't say what it is so we can't really help.

However, if your Vim is crippled, the best thing to do is to install a proper build with clipboard support but I can't tell you how either because I don't know what OS you use.

edit

On debian based systems, the following command will install a proper Vim with clipboard, ruby, python… support.

$ sudo apt-get install vim-gnome

Export to CSV via PHP

I recommend parsecsv-for-php to get around a number any issues with nested newlines and quotes.

Can I edit an iPad's host file?

The previous answer is correct, but if the effect you are looking for is to redirect HTTP traffic for a domain to another IP there is a way.

Since it technically is not answering your question, I have asked and answered the question here:

How can I redirect HTTP requests made from an iPad?

How to create a file on Android Internal Storage?

I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/ or /mnt/sdcard/. Let me explain.

If you execute the following statement:

File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();

It will resolve the path to the root /data/ somewhere higher up in Android.

I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/ without me translating anything on my own.

File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();

A quick fix would be to change your following code:

File f = new File(getLocalPath().replace("/data/data/", "/"));

Hope this helps

Application Installation Failed in Android Studio

Faced same issues on MIUI phone resolved by making MIUI account and enable install by USB.

Add MIME mapping in web.config for IIS Express

If anybody encounters this with errors like Error: cannot add duplicate collection entry of type ‘mimeMap’ with unique key attribute and/or other scripts stop working when doing this fix, it might help to remove it first like this:

<staticContent>
  <remove fileExtension=".woff" />
  <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
</staticContent>

At least that solved my problem

check if "it's a number" function in Oracle

Assuming that the ID column in myTable is not declared as a NUMBER (which seems like an odd choice and likely to be problematic), you can write a function that tries to convert the (presumably VARCHAR2) ID to a number, catches the exception, and returns a 'Y' or an 'N'. Something like

CREATE OR REPLACE FUNCTION is_number( p_str IN VARCHAR2 )
  RETURN VARCHAR2 DETERMINISTIC PARALLEL_ENABLE
IS
  l_num NUMBER;
BEGIN
  l_num := to_number( p_str );
  RETURN 'Y';
EXCEPTION
  WHEN value_error THEN
    RETURN 'N';
END is_number;

You can then embed that call in a query, i.e.

SELECT (CASE WHEN is_number( myTable.id ) = 'Y' AND myTable.id > 0 
               THEN 'Number > 0'
             ELSE 'Something else'
         END) some_alias
  FROM myTable

Note that although PL/SQL has a boolean data type, SQL does not. So while you can declare a function that returns a boolean, you cannot use such a function in a SQL query.

Is it possible to run a .NET 4.5 app on XP?

Last version to support windows XP (SP3) is mono-4.3.2.467-gtksharp-2.12.30.1-win32-0.msi and that doesnot replace .NET 4.5 but could be of interest for some applications.

see there: https://download.mono-project.com/archive/4.3.2/windows-installer/

Firefox Add-on RESTclient - How to input POST parameters?

Here is a step by step guide (I think this should come pre-loaded with the add-on):

  1. In the top menu of RESTClient -> Headers -> Custom Header
  2. In the pop-up box, enter Name: Content-Type and Value: application/x-www-form-urlencoded
  3. Check the "Save to favorite" box and click Okay.
    Now you will see a "Headers" section with your newly added data.
  4. Then in the Body section, you can enter your data to post like:

    username=test&name=Firstname+Lastname
    
  5. Whenever you want to make a post request, from the Headers main menu, select the Content-Type:application/x-www-form-urlencoded item that you added and it should work.

How to read multiple text files into a single RDD?

In PySpark, I have found an additional useful way to parse files. Perhaps there is an equivalent in Scala, but I am not comfortable enough coming up with a working translation. It is, in effect, a textFile call with the addition of labels (in the below example the key = filename, value = 1 line from file).

"Labeled" textFile

input:

import glob
from pyspark import SparkContext
SparkContext.stop(sc)
sc = SparkContext("local","example") # if running locally
sqlContext = SQLContext(sc)

for filename in glob.glob(Data_File + "/*"):
    Spark_Full += sc.textFile(filename).keyBy(lambda x: filename)

output: array with each entry containing a tuple using filename-as-key and with value = each line of file. (Technically, using this method you can also use a different key besides the actual filepath name- perhaps a hashing representation to save on memory). ie.

[('/home/folder_with_text_files/file1.txt', 'file1_contents_line1'),
 ('/home/folder_with_text_files/file1.txt', 'file1_contents_line2'),
 ('/home/folder_with_text_files/file1.txt', 'file1_contents_line3'),
 ('/home/folder_with_text_files/file2.txt', 'file2_contents_line1'),
  ...]

You can also recombine either as a list of lines:

Spark_Full.groupByKey().map(lambda x: (x[0], list(x[1]))).collect()

[('/home/folder_with_text_files/file1.txt', ['file1_contents_line1', 'file1_contents_line2','file1_contents_line3']),
 ('/home/folder_with_text_files/file2.txt', ['file2_contents_line1'])]

Or recombine entire files back to single strings (in this example the result is the same as what you get from wholeTextFiles, but with the string "file:" stripped from the filepathing.):

Spark_Full.groupByKey().map(lambda x: (x[0], ' '.join(list(x[1])))).collect()

How can I add "href" attribute to a link dynamically using JavaScript?

I assume you know how to get the DOM object for the <a> element (use document.getElementById or some other method).

To add any attribute, just use the setAttribute method on the DOM object:

a = document.getElementById(...);
a.setAttribute("href", "somelink url");

What is the difference between mocking and spying when using Mockito?

[Test double types]

Mock vs Spy

Mock is a bare double object. This object has the same methods signatures but realisation is empty and return default value - 0 and null

Spy is a cloned double object. New object is cloned based on a real object but you have a possibility to mock it

class A {
    String foo1() {
        foo2();
        return "RealString_1";
    }

    String foo2() {
        return "RealString_2";
    }

    void foo3() { foo4(); }

    void foo4() { }
}
@Test
public void testMockA() {
    //given
    A mockA = Mockito.mock(A.class);
    Mockito.when(mockA.foo1()).thenReturn("MockedString");

    //when
    String result1 = mockA.foo1();
    String result2 = mockA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals(null, result2);

    //Case 2
    //when
    mockA.foo3();

    //then
    verify(mockA).foo3();
    verify(mockA, never()).foo4();
}

@Test
public void testSpyA() {
    //given
    A spyA = Mockito.spy(new A());

    Mockito.when(spyA.foo1()).thenReturn("MockedString");

    //when
    String result1 = spyA.foo1();
    String result2 = spyA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals("RealString_2", result2);

    //Case 2
    //when
    spyA.foo3();

    //then
    verify(spyA).foo3();
    verify(spyA).foo4();
}

PHP ternary operator vs null coalescing operator

The other answers goes deep and give great explanations. For those who look for quick answer,

$a ?: 'fallback' is $a ? $a : 'fallback'

while

$a ?? 'fallback' is $a = isset($a) ? $a : 'fallback'


The main difference would be when the left operator is either:

  • A falsy value that is NOT null (0, '', false, [], ...)
  • An undefined variable

How can I execute a python script from an html button?

Using a UI Framework would be a lot cleaner (and involve fewer components). Here is an example using wxPython:

import wx
import os
class MyForm(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Launch Scripts")
        panel = wx.Panel(self, wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)
        buttonA = wx.Button(panel, id=wx.ID_ANY, label="App A", name="MYSCRIPT")
        buttonB = wx.Button(panel, id=wx.ID_ANY, label="App B", name="MYOtherSCRIPT")
        buttonC = wx.Button(panel, id=wx.ID_ANY, label="App C", name="SomeDifferentScript")
        buttons = [buttonA, buttonB, buttonC]

        for button in buttons:
            self.buildButtons(button, sizer)

        panel.SetSizer(sizer)

    def buildButtons(self, btn, sizer):
        btn.Bind(wx.EVT_BUTTON, self.onButton)
        sizer.Add(btn, 0, wx.ALL, 5)

    def onButton(self, event):
        """
        This method is fired when its corresponding button is pressed, taking the script from it's name
        """
        button = event.GetEventObject()

        os.system('python {}.py'.format(button.GetName()))

        button_id = event.GetId()
        button_by_id = self.FindWindowById(button_id)
        print "The button you pressed was labeled: " + button_by_id.GetLabel()
        print "The button's name is " + button_by_id.GetName()

# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

I haven't tested this yet, and I'm sure there are cleaner ways of launching a python script form a python script, but the idea I think will still hold. Good luck!

Fitting a Normal distribution to 1D data

Here you are not fitting a normal distribution. Replacing sns.distplot(data) by sns.distplot(data, fit=norm, kde=False) should do the trick.

Resize a large bitmap file to scaled output file on Android

This worked for me. The function gets a path to a file on the sd card and returns a Bitmap in the maximum displayable size. The code is from Ofir with some changes like image file on sd instead a Ressource and the witdth and heigth are get from the Display Object.

private Bitmap makeBitmap(String path) {

    try {
        final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
        //resource = getResources();

        // Decode image size
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        int scale = 1;
        while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) >
                IMAGE_MAX_SIZE) {
            scale++;
        }
        Log.d("TAG", "scale = " + scale + ", orig-width: " + options.outWidth + ", orig-height: " + options.outHeight);

        Bitmap pic = null;
        if (scale > 1) {
            scale--;
            // scale to max possible inSampleSize that still yields an image
            // larger than target
            options = new BitmapFactory.Options();
            options.inSampleSize = scale;
            pic = BitmapFactory.decodeFile(path, options);

            // resize to desired dimensions

            Display display = getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            int width = size.y;
            int height = size.x;

            //int height = imageView.getHeight();
            //int width = imageView.getWidth();
            Log.d("TAG", "1th scale operation dimenions - width: " + width + ", height: " + height);

            double y = Math.sqrt(IMAGE_MAX_SIZE
                    / (((double) width) / height));
            double x = (y / height) * width;

            Bitmap scaledBitmap = Bitmap.createScaledBitmap(pic, (int) x, (int) y, true);
            pic.recycle();
            pic = scaledBitmap;

            System.gc();
        } else {
            pic = BitmapFactory.decodeFile(path);
        }

        Log.d("TAG", "bitmap size - width: " +pic.getWidth() + ", height: " + pic.getHeight());
        return pic;

    } catch (Exception e) {
        Log.e("TAG", e.getMessage(),e);
        return null;
    }

}

Determining the current foreground application from a background task or service

For cases when we need to check from our own service/background-thread whether our app is in foreground or not. This is how I implemented it, and it works fine for me:

public class TestApplication extends Application implements Application.ActivityLifecycleCallbacks {

    public static WeakReference<Activity> foregroundActivityRef = null;

    @Override
    public void onActivityStarted(Activity activity) {
        foregroundActivityRef = new WeakReference<>(activity);
    }

    @Override
    public void onActivityStopped(Activity activity) {
        if (foregroundActivityRef != null && foregroundActivityRef.get() == activity) {
            foregroundActivityRef = null;
        }
    }

    // IMPLEMENT OTHER CALLBACK METHODS
}

Now to check from other classes, whether app is in foreground or not, simply call:

if(TestApplication.foregroundActivityRef!=null){
    // APP IS IN FOREGROUND!
    // We can also get the activity that is currently visible!
}

Update (as pointed out by SHS):

Do not forget to register for the callbacks in your Application class's onCreate method.

@Override
public void onCreate() {
    ...
    registerActivityLifecycleCallbacks(this);
}

How to detect the swipe left or Right in Android?

this should help you maybe...

private final GestureDetector.SimpleOnGestureListener onGestureListener = new GestureDetector.SimpleOnGestureListener() {
    @Override
    public boolean onDoubleTap(MotionEvent e) {
        Log.i("gestureDebug333", "doubleTapped:" + e);
        return super.onDoubleTap(e);
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        Log.i("gestureDebug333", "doubleTappedEvent:" + e);

        return super.onDoubleTapEvent(e);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        Log.i("gestureDebug333", "onDown:" + e);


        return super.onDown(e);

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {


        Log.i("gestureDebug333", "flinged:" + e1 + "---" + e2);
        Log.i("gestureDebug333", "fling velocity:" + velocityX + "---" + velocityY);
        if (e1.getAction() == MotionEvent.ACTION_DOWN && e1.getX() > (e2.getX() + 300)){
           // Toast.makeText(context, "flinged right to left", Toast.LENGTH_SHORT).show();
            goForward();
        }
        if (e1.getAction() == MotionEvent.ACTION_DOWN && e2.getX() > (e1.getX() + 300)){
            //Toast.makeText(context, "flinged left to right", Toast.LENGTH_SHORT).show();
            goBack();
        }
        return super.onFling(e1, e2, velocityX, velocityY);
    }

    @Override
    public void onLongPress(MotionEvent e) {
        super.onLongPress(e);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    @Override
    public void onShowPress(MotionEvent e) {
        super.onShowPress(e);
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        return super.onSingleTapConfirmed(e);
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return super.onSingleTapUp(e);
    }
};

How to print a string at a fixed width?

format is definitely the most elegant way, but afaik you can't use that with python's logging module, so here's how you can do it using the % formatting:

formatter = logging.Formatter(
    fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)

Here, the - indicates left-alignment, and the number before s indicates the fixed width.

Some sample output:

2017-03-14 14:43:42,581 | this-app             | INFO       | running main
2017-03-14 14:43:42,581 | this-app.aux         | DEBUG      | 5 is an int!
2017-03-14 14:43:42,581 | this-app.aux         | INFO       | hello
2017-03-14 14:43:42,581 | this-app             | ERROR      | failed running main

More info at the docs here: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

Usage of MySQL's "IF EXISTS"

SELECT IF((
     SELECT count(*) FROM gdata_calendars 
     WHERE `group` =  ? AND id = ?)
,1,0);

For Detail explanation you can visit here

What is the best/safest way to reinstall Homebrew?

The way to reinstall Homebrew is completely remove it and start over. The Homebrew FAQ has a link to a shell script to uninstall homebrew.

If the only thing you've installed in /usr/local is homebrew itself, you can just rm -rf /usr/local/* /usr/local/.git to clear it out. But /usr/local/ is the standard Unix directory for all extra binaries, not just Homebrew, so you may have other things installed there. In that case uninstall_homebrew.sh is a better bet. It is careful to only remove homebrew's files and leave the rest alone.

How to fix Subversion lock error

We had the same repeating problem. It's a disaster. What can you do if cleanup and unlock does not help because there is no existing lock?

  1. Search the hidden .svn folder in your directory structure. It contains a wc.db file which is an sql lite file.
  2. Open it with an sql client, e.g. DBeaver. Add an sql lite connection to the dbeaver by selecting the wc.db file.
  3. Open the WC_LOCK table. You can see one or more rows that contains the URL which was mentioned in the phantom lock error window.
  4. Delete these rows from the table.
  5. Try to update your project from the repo.
  6. If you use more than 1 repo in 1 project (externals) another phantom lock may appear during the update. In this case repeat the process with that folder.

Node.js: Python not found exception due to node-sass and node-gyp

I had to:

Delete node_modules
Uninstall/reinstall node
npm install [email protected]

worked fine after forcing it to the right sass version, according to the version said to be working with the right node.

NodeJS  Minimum node-sass version   Node Module
Node 12 4.12+   72
Node 11 4.10+   67
Node 10 4.9+    64
Node 8  4.5.3+  57

There was lots of other errors that seemed to be caused by the wrong sass version defined.

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

To force the download of a PDF file, instead of being handled by the browser's PDF plugin:

public ActionResult DownloadPDF()
{
    return File("~/Content/MyFile.pdf", "application/pdf", "MyRenamedFile.pdf");
}

If you want to let the browser handle by its default behavior (plugin or download), just send two parameters.

public ActionResult DownloadPDF()
{
    return File("~/Content/MyFile.pdf", "application/pdf");
}

You'll need to use the third parameter to specify a name for the file on the browser dialog.

UPDATE: Charlino is right, when passing the third parameter (download filename) Content-Disposition: attachment; gets added to the Http Response Header. My solution was to send application\force-download as the mime-type, but this generates a problem with the filename of the download so the third parameter is required to send a good filename, therefore eliminating the need to force a download.

live output from subprocess command

It looks like line-buffered output will work for you, in which case something like the following might suit. (Caveat: it's untested.) This will only give the subprocess's stdout in real time. If you want to have both stderr and stdout in real time, you'll have to do something more complex with select.

proc = subprocess.Popen(run_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
while proc.poll() is None:
    line = proc.stdout.readline()
    print line
    log_file.write(line + '\n')
# Might still be data on stdout at this point.  Grab any
# remainder.
for line in proc.stdout.read().split('\n'):
    print line
    log_file.write(line + '\n')
# Do whatever you want with proc.stderr here...

Split string in Lua?

I used the above examples to craft my own function. But the missing piece for me was automatically escaping magic characters.

Here is my contribution:

function split(text, delim)
    -- returns an array of fields based on text and delimiter (one character only)
    local result = {}
    local magic = "().%+-*?[]^$"

    if delim == nil then
        delim = "%s"
    elseif string.find(delim, magic, 1, true) then
        -- escape magic
        delim = "%"..delim
    end

    local pattern = "[^"..delim.."]+"
    for w in string.gmatch(text, pattern) do
        table.insert(result, w)
    end
    return result
end

How to zoom div content using jquery?

 $('image').animate({ 'zoom': 1}, 400);

Installing RubyGems in Windows

Another way is to let chocolatey manage your ruby package (and any other package), that way you won't have to put ruby in your path manually:

Install chocolatey first by opening your favourite command prompt and executing:

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin

then all you need to do is type

cinst ruby

In your command prompt and the package installs.

Using a package manager provides overall more control, I'd recommend this for every package that can be installed via chocolatey.

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

How to write a basic swap function in Java

You can easily write one yourself.

given:

int array[]={1,2};

you do:

int temp=array[0];
array[0]=array[1];
array[1]=temp;

And you're done. 3 lines of code.

How can I make PHP display the error instead of giving me 500 Internal Server Error

Check the error_reporting, display_errors and display_startup_errors settings in your php.ini file. They should be set to E_ALL and "On" respectively (though you should not use display_errors on a production server, so disable this and use log_errors instead if/when you deploy it). You can also change these settings (except display_startup_errors) at the very beginning of your script to set them at runtime (though you may not catch all errors this way):

error_reporting(E_ALL);
ini_set('display_errors', 'On');

After that, restart server.

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

In later versions of CMake, one way to do it on each target is:

set_target_properties(MyTarget PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")

I don't know of a way to do it globally.

Add Bootstrap Glyphicon to Input Box

Without Bootstrap:

We'll get to Bootstrap in a second, but here's the fundamental CSS concepts in play in order to do this yourself. As beard of prey points out, you can do this with CSS by absolutely positioning the icon inside of the input element. Then add padding to either side so the text doesn't overlap with the icon.

So for the following HTML:

<div class="inner-addon left-addon">
    <i class="glyphicon glyphicon-user"></i>
    <input type="text" class="form-control" />
</div>

You can use the following CSS to left and right align glyphs:

/* enable absolute positioning */
.inner-addon { 
    position: relative; 
}

/* style icon */
.inner-addon .glyphicon {
  position: absolute;
  padding: 10px;
  pointer-events: none;
}

/* align icon */
.left-addon .glyphicon  { left:  0px;}
.right-addon .glyphicon { right: 0px;}

/* add padding  */
.left-addon input  { padding-left:  30px; }
.right-addon input { padding-right: 30px; }

Demo in Plunker

css screenshot

Note: This presumes you're using glyphicons, but works equally well with font-awesome.
For FA, just replace .glyphicon with .fa


With Bootstrap:

As buffer points out, this can be accomplished natively within Bootstrap by using Validation States with Optional Icons. This is done by giving the .form-group element the class of .has-feedback and the icon the class of .form-control-feedback.

The simplest example would be something like this:

<div class="form-group has-feedback">
    <label class="control-label">Username</label>
    <input type="text" class="form-control" placeholder="Username" />
    <i class="glyphicon glyphicon-user form-control-feedback"></i>
</div>

Pros:

  • Includes support for different form types (Basic, Horizontal, Inline)
  • Includes support for different control sizes (Default, Small, Large)

Cons:

  • Doesn't include support for left aligning icons

To overcome the cons, I put together this pull-request with changes to support left aligned icons. As it is a relatively large change, it has been put off until a future release, but if you need these features today, here's a simple implementation guide:

Just include the these form changes in css (also inlined via hidden stack snippet at the bottom)
*LESS: alternatively, if you are building via less, here's the form changes in less

Then, all you have to do is include the class .has-feedback-left on any group that has the class .has-feedback in order to left align the icon.

Since there are a lot of possible html configurations over different form types, different control sizes, different icon sets, and different label visibilities, I created a test page that shows the correct set of HTML for each permutation along with a live demo.

Here's a demo in Plunker

feedback screenshot

P.S. frizi's suggestion of adding pointer-events: none; has been added to bootstrap

Didn't find what you were looking for? Try these similar questions:

Addition CSS for Left Aligned feedback icons

_x000D_
_x000D_
.has-feedback .form-control {_x000D_
  padding-right: 34px;_x000D_
}_x000D_
.has-feedback .form-control.input-sm,_x000D_
.has-feedback.form-group-sm .form-control {_x000D_
  padding-right: 30px;_x000D_
}_x000D_
.has-feedback .form-control.input-lg,_x000D_
.has-feedback.form-group-lg .form-control {_x000D_
  padding-right: 46px;_x000D_
}_x000D_
.has-feedback-left .form-control {_x000D_
  padding-right: 12px;_x000D_
  padding-left: 34px;_x000D_
}_x000D_
.has-feedback-left .form-control.input-sm,_x000D_
.has-feedback-left.form-group-sm .form-control {_x000D_
  padding-left: 30px;_x000D_
}_x000D_
.has-feedback-left .form-control.input-lg,_x000D_
.has-feedback-left.form-group-lg .form-control {_x000D_
  padding-left: 46px;_x000D_
}_x000D_
.has-feedback-left .form-control-feedback {_x000D_
  left: 0;_x000D_
}_x000D_
.form-control-feedback {_x000D_
  line-height: 34px !important;_x000D_
}_x000D_
.input-sm + .form-control-feedback,_x000D_
.form-horizontal .form-group-sm .form-control-feedback {_x000D_
  width: 30px;_x000D_
  height: 30px;_x000D_
  line-height: 30px !important;_x000D_
}_x000D_
.input-lg + .form-control-feedback,_x000D_
.form-horizontal .form-group-lg .form-control-feedback {_x000D_
  width: 46px;_x000D_
  height: 46px;_x000D_
  line-height: 46px !important;_x000D_
}_x000D_
.has-feedback label.sr-only ~ .form-control-feedback,_x000D_
.has-feedback label.sr-only ~ div .form-control-feedback {_x000D_
  top: 0;_x000D_
}_x000D_
@media (min-width: 768px) {_x000D_
  .form-inline .inline-feedback {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
  }_x000D_
  .form-inline .has-feedback .form-control-feedback {_x000D_
    top: 0;_x000D_
  }_x000D_
}_x000D_
.form-horizontal .has-feedback-left .form-control-feedback {_x000D_
  left: 15px;_x000D_
}
_x000D_
_x000D_
_x000D_

How do I prevent a Gateway Timeout with FastCGI on Nginx

Proxy timeouts are well, for proxies, not for FastCGI...

The directives that affect FastCGI timeouts are client_header_timeout, client_body_timeout and send_timeout.

Edit: Considering what's found on nginx wiki, the send_timeout directive is responsible for setting general timeout of response (which was bit misleading). For FastCGI there's fastcgi_read_timeout which is affecting the fastcgi process response timeout.

HTH.

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

How do I get HTTP Request body content in Laravel?

I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.

Looking at the class in edit #2, I would make it look like this:

class XmlController extends Controller
{
    public function index()
    {
        $content = Request::all();
        return Response::json($content);
    }
}

Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.

More information on Laravel responses here:

http://laravel.com/docs/5.0/responses

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I ran into this same issue on a new install of mysql 5.5 on a mac. I tried to drop the test schema and got an errno 17 message. errno 17 is the error returned by some posix os functions indicating that a file exists where it should not. In the data directory, I found a strange file ".empty":

sh-3.2# ls -la data/test
total 0
drwxr-xr-x   3 _mysql  wheel  102 Apr 15 12:36 .
drwxr-xr-x  11 _mysql  wheel  374 Apr 15 12:28 ..
-rw-r--r--   1 _mysql  wheel    0 Mar 31 10:19 .empty

Once I rm'd the .empty file, the drop database command succeeded.

I don't know where the .empty file came from; as noted, this was a new mysql install. Perhaps something went wrong in the install process.

Creating virtual directories in IIS express

I had to make the entry in the [project].vs\config\applicationhost.config file.

Prior to this, it worked from deployment but not from code.

How to lay out Views in RelativeLayout programmatically?

call

tv1.setId(1) 

after

tv1.setText("A");

creating an array of structs in c++

You can't use an initialization-list for a struct after it's been initialized. You've already default-initialized the two Customer structs when you declared the array customerRecords. Therefore you're going to have either use member-access syntax to set the value of the non-static data members, initialize the structs using a list of initialization lists when you declare the array itself, or you can create a constructor for your struct and use the default operator= member function to initialize the array members.

So either of the following could work:

Customer customerRecords[2];
customerRecords[0].uid = 25;
customerRecords[0].name = "Bob Jones";
customerRecords[1].uid = 25;
customerRecords[1].namem = "Jim Smith";

Or if you defined a constructor for your struct like:

Customer::Customer(int id, string input_name): uid(id), name(input_name) {}

You could then do:

Customer customerRecords[2];
customerRecords[0] = Customer(25, "Bob Jones");
customerRecords[1] = Customer(26, "Jim Smith");

Or you could do the sequence of initialization lists that Tuomas used in his answer. The reason his initialization-list syntax works is because you're actually initializing the Customer structs at the time of the declaration of the array, rather than allowing the structs to be default-initialized which takes place whenever you declare an aggregate data-structure like an array.

How can I loop over entries in JSON?

To decode json, you have to pass the json string. Currently you're trying to pass an object:

>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>

You can fetch the data with response.read().

REST API error code 500 handling

Generally speaking, 5xx response codes indicate non-programmatic failures, such as a database connection failure, or some other system/library dependency failure. In many cases, it is expected that the client can re-submit the same request in the future and expect it to be successful.

Yes, some web-frameworks will respond with 5xx codes, but those are typically the result of defects in the code and the framework is too abstract to know what happened, so it defaults to this type of response; that example, however, doesn't mean that we should be in the habit of returning 5xx codes as the result of programmatic behavior that is unrelated to out of process systems. There are many, well defined response codes that are more suitable than the 5xx codes. Being unable to parse/validate a given input is not a 5xx response because the code can accommodate a more suitable response that won't leave the client thinking that they can resubmit the same request, when in fact, they can not.

To be clear, if the error encountered by the server was due to CLIENT input, then this is clearly a CLIENT error and should be handled with a 4xx response code. The expectation is that the client will correct the error in their request and resubmit.

It is completely acceptable, however, to catch any out of process errors and interpret them as a 5xx response, but be aware that you should also include further information in the response to indicate exactly what failed; and even better if you can include SLA times to address.

I don't think it's a good practice to interpret, "an unexpected error" as a 5xx error because bugs happen.

It is a common alert monitor to begin alerting on 5xx types of errors because these typically indicate failed systems, rather than failed code. So, code accordingly!

What is the most efficient way to get first and last line of a text file?

Here is an extension of @Trasp's answer that has additional logic for handling the corner case of a file that has only one line. It may be useful to handle this case if you repeatedly want to read the last line of a file that is continuously being updated. Without this, if you try to grab the last line of a file that has just been created and has only one line, IOError: [Errno 22] Invalid argument will be raised.

def tail(filepath):
    with open(filepath, "rb") as f:
        first = f.readline()      # Read the first line.
        f.seek(-2, 2)             # Jump to the second last byte.
        while f.read(1) != b"\n": # Until EOL is found...
            try:
                f.seek(-2, 1)     # ...jump back the read byte plus one more.
            except IOError:
                f.seek(-1, 1)
                if f.tell() == 0:
                    break
        last = f.readline()       # Read last line.
    return last

how to cancel/abort ajax request in axios

Axios does not support canceling requests at the moment. Please see this issue for details.

UPDATE: Cancellation support was added in axios v0.15.

EDIT: The axios cancel token API is based on the withdrawn cancelable promises proposal.

Example:

const cancelTokenSource = axios.CancelToken.source();

axios.get('/user/12345', {
  cancelToken: cancelTokenSource.token
});

// Cancel request
cancelTokenSource.cancel();

How to load/edit/run/save text files (.py) into an IPython notebook cell?

To write/save

%%writefile myfile.py

  • write/save cell contents into myfile.py (use -a to append). Another alias: %%file myfile.py

To run

%run myfile.py

  • run myfile.py and output results in the current cell

To load/import

%load myfile.py

  • load "import" myfile.py into the current cell

For more magic and help

%lsmagic

  • list all the other cool cell magic commands.

%COMMAND-NAME?

  • for help on how to use a certain command. i.e. %run?

Note

Beside the cell magic commands, IPython notebook (now Jupyter notebook) is so cool that it allows you to use any unix command right from the cell (this is also equivalent to using the %%bash cell magic command).

To run a unix command from the cell, just precede your command with ! mark. for example:

  • !python --version see your python version
  • !python myfile.py run myfile.py and output results in the current cell, just like %run (see the difference between !python and %run in the comments below).

Also, see this nbviewer for further explanation with examples. Hope this helps.

Find and replace with sed in directory and sub directories

This worked for me:

find ./ -type f -exec sed -i '' 's#NEEDLE#REPLACEMENT#' *.php {} \;

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

I searched for the error in the web and came to this page. I am using Visual Studio 2015 and this is my first MVC project.

If you miss the @ symbol before the render section you will get the same error. I would like to share this for future beginners.

 @RenderSection("headscripts", required: false)

Add a dependency in Maven

Actually, on investigating this, I think all these answers are incorrect. Your question is misleading because of our level of understanding of maven. And I say our because I'm just getting introduced to maven.

In Eclipse, when you want to add a jar file to your project, normally you download the jar manually and then drop it into the lib directory. With maven, you don't do it this way. Here's what you do:

  • Go to mvnrepository
  • Search for the library you want to add
  • Copy the dependency statement into your pom.xml
  • rebuild via mvn

Now, maven will connect and download the jar along with the list of dependencies, and automatically resolve any additional dependencies that jar may have had. So if the jar also needed commons-logging, that will be downloaded as well.

Laravel Eloquent - distinct() and count() not working properly together

Based on Laravel docs for raw queries I was able to get count for a select field to work with this code in the product model.

public function scopeShowProductCount($query)
{
    $query->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))
          ->groupBy('pid')
          ->orderBy('count_pid', 'desc');
}

This facade worked to get the same result in the controller:

$products = DB::table('products')->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))->groupBy('pid')->orderBy('count_pid', 'desc')->get();

The resulting dump for both queries was as follows:

#attributes: array:2 [
  "pid" => "1271"
  "count_pid" => 19
],
#attributes: array:2 [
  "pid" => "1273"
  "count_pid" => 12
],
#attributes: array:2 [
  "pid" => "1275"
  "count_pid" => 7
]

What is DOM element?

As per W3C: DOM permits programs and scripts to dynamically access and update the content, structure and style of XML or HTML documents.

DOM is composed of:

  • set of objects/elements
  • a structure of how these objects/elements can be combined
  • and an interface to access and modify them

cheers

Is there a 'box-shadow-color' property?

Actually… there is! Sort of. box-shadow defaults to color, just like border does.

According to http://dev.w3.org/.../#the-box-shadow

The color is the color of the shadow. If the color is absent, the used color is taken from the ‘color’ property.

In practice, you have to change the color property and leave box-shadow without a color:

box-shadow: 1px 2px 3px;
color: #a00;

Support

  • Safari 6+
  • Chrome 20+ (at least)
  • Firefox 13+ (at least)
  • IE9+ (IE8 doesn't support box-shadow at all)

Demo

_x000D_
_x000D_
div {_x000D_
    box-shadow: 0 0 50px;_x000D_
    transition: 0.3s color;_x000D_
}_x000D_
.green {_x000D_
    color: green;_x000D_
}_x000D_
.red {_x000D_
    color: red;_x000D_
}_x000D_
div:hover {_x000D_
    color: yellow;_x000D_
}_x000D_
_x000D_
/*demo style*/_x000D_
body {_x000D_
    text-align: center;_x000D_
}_x000D_
div {_x000D_
    display: inline-block;_x000D_
    background: white;_x000D_
    height: 100px;_x000D_
    width: 100px;_x000D_
    margin: 30px;_x000D_
    border-radius: 50%;_x000D_
}
_x000D_
<div class="green"></div>_x000D_
<div class="red"></div>
_x000D_
_x000D_
_x000D_

The bug mentioned in the comment below has since been fixed :)

How to Get enum item name from its value

I have had excellent success with a technique which resembles the X macros pointed to by @RolandXu. We made heavy use of the stringize operator, too. The technique mitigates the maintenance nightmare when you have an application domain where items appear both as strings and as numerical tokens.

It comes in particularily handy when machine readable documentation is available so that the macro X(...) lines can be auto-generated. A new documentation would immediately result in a consistent program update covering the strings, enums and the dictionaries translating between them in both directions. (We were dealing with PCL6 tokens).

And while the preprocessor code looks pretty ugly, all those technicalities can be hidden in the header files which never have to be touched again, and neither do the source files. Everything is type safe. The only thing that changes is a text file containing all the X(...) lines, and that is possibly auto generated.

How to convert UTC timestamp to device local time in android

I did it using Extension Functions in kotlin

fun String.toDate(dateFormat: String = "yyyy-MM-dd HH:mm:ss", timeZone: TimeZone = TimeZone.getTimeZone("UTC")): Date {
    val parser = SimpleDateFormat(dateFormat, Locale.getDefault())
    parser.timeZone = timeZone
    return parser.parse(this)
}

fun Date.formatTo(dateFormat: String, timeZone: TimeZone = TimeZone.getDefault()): String {
    val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
    formatter.timeZone = timeZone
    return formatter.format(this)
}

Usage:

"2018-09-10 22:01:00".toDate().formatTo("dd MMM yyyy")

Output: "11 Sep 2018"

Note:

Ensure the proper validation.

What is the SSIS package and what does it do?

Microsoft SQL Server Integration Services (SSIS) is a platform for building high-performance data integration solutions, including extraction, transformation, and load (ETL) packages for data warehousing. SSIS includes graphical tools and wizards for building and debugging packages; tasks for performing workflow functions such as FTP operations, executing SQL statements, and sending e-mail messages; data sources and destinations for extracting and loading data; transformations for cleaning, aggregating, merging, and copying data; a management database, SSISDB, for administering package execution and storage; and application programming interfaces (APIs) for programming the Integration Services object model.

As per Microsoft, the main uses of SSIS Package are:

• Merging Data from Heterogeneous Data Stores Populating Data

• Warehouses and Data Marts Cleaning and Standardizing Data Building

• Business Intelligence into a Data Transformation Process Automating

• Administrative Functions and Data Loading

For developers:

SSIS Package can be integrated with VS development environment for building Business Intelligence solutions. Business Intelligence Development Studio is the Visual Studio environment with enhancements that are specific to business intelligence solutions. It work with 32-bit development environment only.

Download SSDT tools for Visual Studio:

http://www.microsoft.com/en-us/download/details.aspx?id=36843

Creating SSIS ETL Package - Basics :

https://docs.microsoft.com/en-us/sql/integration-services/ssis-how-to-create-an-etl-package?view=sql-server-2017

Sample project of SSIS features in 6 lessons:

https://docs.microsoft.com/en-us/sql/integration-services/ssis-how-to-create-an-etl-package?view=sql-server-2017

Listing information about all database files in SQL Server

You can also try this.

 select db_name(dbid) dbname, filename from sys.sysaltfiles

What is the difference between a "function" and a "procedure"?

This is a well-known old question, but I'd like to share some more insights about modern programming language research and design.

Basic answer

Traditionally (in the sense of structured programming) and informally, a procedure is a reusable structural construct to have "input" and to do something programmable. When something is needed to be done within a procedure, you can provide (actual) arguments to the procedure in a procedure call coded in the source code (usually in a kind of an expression), and the actions coded in the procedures body (provided in the definition of the procedure) will be executed with the substitution of the arguments into the (formal) parameters used in the body.

A function is more than a procedure because return values can also be specified as the "output" in the body. Function calls are more or less same to procedure calls, except that you can also use the result of the function call, syntactically (usually as a subexpression of some other expression).

Traditionally, procedure calls (rather than function calls) are used to indicate that no output must be interested, and there must be side effects to avoid the call being no-ops, hence emphasizing the imperative programming paradigm. Many traditional programming languages like Pascal provide both "procedures" and "functions" to distinguish this intentional difference of styles.

(To be clear, the "input" and "output" mentioned above are simplified notions based on the syntactic properties of functions. Many languages additionally support passing arguments to parameters by reference/sharing, to allow users transporting information encoded in arguments during the calls. Such parameter may even be just called as "in/out parameter". This feature is based on the nature of the objects being passed in the calls, which is orthogonal to the properties of the feature of procedure/function.)

However, if the result of a function call is not needed, it can be just (at least logically) ignored, and function definitions/function calls should be consistent to procedure definitions/procedure calls in this way. ALGOL-like languages like C, C++ and Java, all provide the feature of "function" in this fashion: by encoding the result type void as a special case of functions looking like traditional procedures, there is no need to provide the feature of "procedures" separately. This prevents some bloat in the language design.

Since SICP is mentioned, it is also worth noting that in the Scheme language specified by RnRS, a procedure may or may not have to return the result of the computation. This is the union of the traditional "function" (returning the result) and "procedure" (returning nothing), essentially same to the "function" concept of many ALGOL-like languages (and actually sharing even more guarantees like applicative evaluations of the operands before the call). However, old-fashion differences still occur even in normative documents like SRFI-96.

I don't know much about the exact reasons behind the divergence, but as I have experienced, it seems that language designers will be happier without specification bloat nowadays. That is, "procedure" as a standalone feature is unnecessary. Techniques like void type is already sufficient to mark the use where side effects should be emphasized. This is also more natural to users having experiences on C-like languages, which are popular more than a few decades. Moreover, it avoids the embarrassment in cases like RnRS where "procedures" are actually "functions" in the broader sense.

In theory, a function can be specified with a specified unit type as the type of the function call result to indicate that result is special. This distinguishes the traditional procedures (where the result of a call is uninterested) from others. There are different styles in the design of a language:

  • As in RnRS, just marking the uninterested results as "unspecified" value (of unspecified type, if the language has to mention it) and it is sufficient to be ignored.
  • Specifying the uninterested result as the value of a dedicated unit type (e.g. Kernel's #inert) also works.
  • When that type is a further a bottom type, it can be (hopefully) statically verified and prevented used as a type of expression. The void type in ALGOL-like languages is exactly an example of this technique. ISO C11's _Noreturn is a similar but more subtle one in this kind.

Further reading

As the traditional concept derived from math, there are tons of black magic most people do not bother to know. Strictly speaking, you won't be likely get the whole things clear as per your math books. CS books might not provide much help, either.

With concerning of programming languages, there are several caveats:

  • Functions in different branches of math are not always defined having same meanings. Functions in different programming paradigms may also be quite different (even sometimes the syntaxes of function call look similar). Sometimes the reasons to cause the differences are same, but sometimes they are not.
    • It is idiomatic to model computation by mathematical functions and then implement the underlying computation in programming languages. Be careful to avoid mapping them one to one unless you know what are being talked about.
  • Do not confuse the model with the entity be modeled.
    • The latter is only one of the implementation to the former. There can be more than one choices, depending on the contexts (the branches of math interested, for example).
    • In particular, it is more or less similarly absurd to treat "functions" as "mappings" or subsets of Cartesian products like to treat natural numbers as Von-Neumann encoding of ordinals (looking like a bunch of {{{}}, {}}...) besides some limited contexts.
  • Mathematically, functions can be partial or total. Different programming languages have different treatment here.
    • Some functional languages may honor totality of functions to guarantee the computation within the function calls always terminate in finite steps. However, this is essentially not Turing-complete, hence weaker computational expressiveness, and not much seen in general-purpose languages besides semantics of typechecking (which is expected to be total).
    • If the difference between the procedures and functions is significant, should there be "total procedures"? Hmm...
  • Constructs similar to functions in calculi used to model the general computation and the semantics of the programming languages (e.g. lambda abstractions in lambda calculi) can have different evaluation strategies on operands.
    • In traditional the reductions in pure calculi as well in as evaluations of expressions in pure functional languages, there are no side effects altering the results of the computations. As a result, operands are not required to be evaluated before the body of the functions-like constructs (because the invariant to define "same results" is kept by properties like ß-equivalence guaranteed by Church-Rosser property).
    • However, many programming languages may have side effects during the evaluations of expressions. That means, strict evaluation strategies like applicative evaluation are not the same to non-strict evaluation ones like call-by-need. This is significant, because without the distinction, there is no need to distinguish function-like (i.e. used with arguments) macros from (traditional) functions. But depending on the flavor of theories, this still can be an artifact. That said, in a broader sense, functional-like macros (esp. hygienic ones) are mathematical functions with some unnecessary limitations (syntactic phases). Without the limitations, it might be sane to treat (first-class) function-like macros as procedures...
    • For readers interested in this topic, consider some modern abstractions.
  • Procedures are usually considered out of the scope of traditional math. However, in calculi modeling the computation and programming language semantics, as well as contemporary programming language designs, there can be quite a big family of related concepts sharing the "callable" nature. Some of them are used to implement/extend/replace procedures/functions. There are even more subtle distinctions.

How can I disable a specific LI element inside a UL?

Using JQuery : http://api.jquery.com/hide/

$('li.two').hide()

In :

<ul class="lul">
    <li class="one">a</li>
    <li class="two">b</li>
    <li class="three">c</li>
</ul>

On document ready.

http://jsfiddle.net/2dDSG/

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

Difference between variable declaration syntaxes in Javascript (including global variables)?

Keeping it simple :

a = 0

The code above gives a global scope variable

var a = 0;

This code will give a variable to be used in the current scope, and under it

window.a = 0;

This generally is same as the global variable.

Combining multiple condition in single case statement in Sql Server

You can put the condition after the WHEN clause, like so:

SELECT
  CASE
    WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
    WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
    WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
    WHEN DS.DES = 'N' THEN 'Early Term'
    WHEN DS.DES = 'Y' THEN 'Complete'
  END
FROM
  ....

Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...

How to write MySQL query where A contains ( "a" or "b" )

Two options:

  1. Use the LIKE keyword, along with percent signs in the string

    select * from table where field like '%a%' or field like '%b%'.
    

    (note: If your search string contains percent signs, you'll need to escape them)

  2. If you're looking for more a complex combination of strings than you've specified in your example, you could regular expressions (regex):

    See the MySQL manual for more on how to use them: http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Of these, using LIKE is the most usual solution -- it's standard SQL, and in common use. Regex is less commonly used but much more powerful.

Note that whichever option you go with, you need to be aware of possible performance implications. Searching for sub-strings like this will mean that the query will have to scan the entire table. If you have a large table, this could make for a very slow query, and no amount of indexing is going to help.

If this is an issue for you, and you'r going to need to search for the same things over and over, you may prefer to do something like adding a flag field to the table which specifies that the string field contains the relevant sub-strings. If you keep this flag field up-to-date when you insert of update a record, you could simply query the flag when you want to search. This can be indexed, and would make your query much much quicker. Whether it's worth the effort to do that is up to you, it'll depend on how bad the performance is using LIKE.

psql - save results of command to a file

This approach will work with any psql command from the simplest to the most complex without requiring any changes or adjustments to the original command.

NOTE: For Linux servers.


  • Save the contents of your command to a file

MODEL

read -r -d '' FILE_CONTENT << 'HEREDOC'
[COMMAND_CONTENT]

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd

EXAMPLE

read -r -d '' FILE_CONTENT << 'HEREDOC'
DO $f$
declare
    curid INT := 0;
    vdata BYTEA;
    badid VARCHAR;
    loc VARCHAR;
begin
FOR badid IN SELECT some_field FROM public.some_base LOOP
    begin
    select 'ctid - '||ctid||'pagenumber - '||(ctid::text::point) [0]::bigint
        into loc
        from public.some_base where some_field = badid;
        SELECT file||' '
        INTO vdata
        FROM public.some_base where some_field = badid;
    exception
        when others then
        raise notice 'Block/PageNumber - % ',loc;
            raise notice 'Corrupted id - % ', badid;
            --return;
    end;
end loop;
end;
$f$;

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd
  • Run the command

MODEL

sudo -u postgres psql [some_db] -c "$(cat sqlcmd)" >>sqlop 2>&1

EXAMPLE

sudo -u postgres psql some_db -c "$(cat sqlcmd)" >>sqlop 2>&1

  • View/track your command output

cat sqlop

Done! Thanks! =D

Simple argparse example wanted: 1 argument, 3 results

I went through all the examples and answers and in a way or another they didn't address my need. So I will list her a scenario that I need more help and I hope this can explain the idea more.

Initial Problem

I need to develop a tool which is getting a file to process it and it needs some optional configuration file to be used to configure the tool.

so what I need is something like the following

mytool.py file.text -config config-file.json

The solution

Here is the solution code

import argparse

def main():
    parser = argparse.ArgumentParser(description='This example for a tool to process a file and configure the tool using a config file.')
    parser.add_argument('filename', help="Input file either text, image or video")
    # parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
    # parser.add_argument('-c', '--config_file', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
    parser.add_argument('-c', '--config', default='configFile.json', dest='config_file', help="a JSON file to load the initial configuration " )
    parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )

    args = parser.parse_args()
    
    filename = args.filename
    configfile = args.config_file

    print("The file to be processed is", filename)
    print("The config file is", configfile)

    if args.debug:
        print("Debug mode enabled")
    else:
        print("Debug mode disabled")

    print("and all arguments are: ", args)

if __name__ == '__main__':
    main()

I will show the solution in multiple enhancements to show the idea

First Round: List the arguments

List all input as mandatory inputs so second argument will be

parser.add_argument('config_file', help="a JSON file to load the initial configuration ")

When we get the help command for this tool we find the following outcome

(base) > python .\argparser_example.py -h
usage: argparser_example.py [-h] filename config_file

This example for a tool to process a file and configure the tool using a config file.

positional arguments:
  filename     Input file either text, image or video
  config_file  a JSON file to load the initial configuration

optional arguments:
  -h, --help   show this help message and exit

and when I execute it as the following

(base) > python .\argparser_example.py filename.txt configfile.json

the outcome will be

The file to be processed is filename.txt
The config file is configfile.json
and all arguments are:  Namespace(config_file='configfile.json', filename='filename.txt')

But the config file should be optional, I removed it from the arguments

(base) > python .\argparser_example.py filename.txt

The outcome will be is:

usage: argparser_example.py [-h] filename config_file
argparser_example.py: error: the following arguments are required: c

Which means we have a problem in the tool

Second Round : Make it optimal

So to make it optional I modified the program as follows

    parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)

The help outcome should be

usage: argparser_example.py [-h] [-c CONFIG] filename

This example for a tool to process a file and configure the tool using a config file.

positional arguments:
  filename              Input file either text, image or video

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        a JSON file to load the initial configuration

so when I execute the program

(base) > python .\argparser_example.py filename.txt

the outcome will be

The file to be processed is filename.txt
The config file is configFile.json
and all arguments are:  Namespace(config_file='configFile.json', filename='filename.txt')

with arguments like

(base) > python .\argparser_example.py filename.txt --config_file anotherConfig.json

The outcome will be

The file to be processed is filename.txt
The config file is anotherConfig.json
and all arguments are:  Namespace(config_file='anotherConfig.json', filename='filename.txt')

Round 3: Enhancements

to change the flag name from --config_file to --config while we keep the variable name as is we modify the code to include dest='config_file' as the following:

parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', dest='config_file')

and the command will be

(base) > python .\argparser_example.py filename.txt --config anotherConfig.json

To add the support for having a debug mode flag, we need to add a flag in the arguments to support a boolean debug flag. To implement it i added the following:

    parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )

the tool command will be:

(carnd-term1-38) > python .\argparser_example.py image.jpg -c imageConfig,json --debug

the outcome will be

The file to be processed is image.jpg
The config file is imageConfig,json
Debug mode enabled
and all arguments are:  Namespace(config_file='imageConfig,json', debug=True, filename='image.jpg')

CreateProcess error=206, The filename or extension is too long when running main() method

Try updating your Eclipse version, the issue was closed recently (2013-03-12). Check the bug report https://bugs.eclipse.org/bugs/show_bug.cgi?id=327193

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

Java reflection: how to get field value from an object, not knowing its class

public abstract class Refl {
    /** Use: Refl.<TargetClass>get(myObject,"x.y[0].z"); */
    public static<T> T get(Object obj, String fieldPath) {
        return (T) getValue(obj, fieldPath);
    }
    public static Object getValue(Object obj, String fieldPath) {
        String[] fieldNames = fieldPath.split("[\\.\\[\\]]");
        String success = "";
        Object res = obj;
        for (String fieldName : fieldNames) {
            if (fieldName.isEmpty()) continue;
            int index = toIndex(fieldName);
            if (index >= 0) {
                try {
                    res = ((Object[])res)[index];
                } catch (ClassCastException cce) {
                    throw new RuntimeException("cannot cast "+res.getClass()+" object "+res+" to array, path:"+success, cce);
                } catch (IndexOutOfBoundsException iobe) {
                    throw new RuntimeException("bad index "+index+", array size "+((Object[])res).length +" object "+res +", path:"+success, iobe);
                }
            } else {
                Field field = getField(res.getClass(), fieldName);
                field.setAccessible(true);
                try {
                    res = field.get(res);
                } catch (Exception ee) {
                    throw new RuntimeException("cannot get value of ["+fieldName+"] from "+res.getClass()+" object "+res +", path:"+success, ee);
                }
            }
            success += fieldName + ".";
        }
        return res;
    }

    public static Field getField(Class<?> clazz, String fieldName) {
        Class<?> tmpClass = clazz;
        do {
            try {
                Field f = tmpClass.getDeclaredField(fieldName);
                return f;
            } catch (NoSuchFieldException e) {
                tmpClass = tmpClass.getSuperclass();
            }
        } while (tmpClass != null);

        throw new RuntimeException("Field '" + fieldName + "' not found in class " + clazz);
    }

    private static int toIndex(String s) {
        int res = -1;
        if (s != null && s.length() > 0 && Character.isDigit(s.charAt(0))) {
            try {
                res = Integer.parseInt(s);
                if (res < 0) {
                    res = -1;
                }
            } catch (Throwable t) {
                res = -1;
            }
        }
        return res;
    }
}

It supports fetching fields and array items, e.g.:

System.out.println(""+Refl.getValue(b,"x.q[0].z.y"));

there is no difference between dots and braces, they are just delimiters, and empty field names are ignored:

System.out.println(""+Refl.getValue(b,"x.q[0].z.y[value]"));
System.out.println(""+Refl.getValue(b,"x.q.1.y.z.value"));
System.out.println(""+Refl.getValue(b,"x[q.1]y]z[value"));

The remote certificate is invalid according to the validation procedure

.NET is seeing an invalid SSL certificate on the other end of the connection. There is a workaround for it, but obviously not recommended for production code:

// Put this somewhere that is only once - like an initialization method
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate);
...

static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
   return true;
}

add an element to int [] array in java

class AddElement {
     public static void main(String s[]) {
        int arr[] ={2,3};
        int add[] = new int[arr.length+1];
        for(int i=0;i<add.length;i++){
        if(i==add.length-1){
            add[i]=4;
        }else{
            add[i]=arr[i];
        }
        System.out.println(add[i]);
        }
    } 
}

OkHttp Post Body as JSON

Another approach is by using FormBody.Builder().
Here's an example of callback:

Callback loginCallback = new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        try {
            Log.i(TAG, "login failed: " + call.execute().code());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // String loginResponseString = response.body().string();
        try {
            JSONObject responseObj = new JSONObject(response.body().string());
            Log.i(TAG, "responseObj: " + responseObj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Log.i(TAG, "loginResponseString: " + loginResponseString);
    }
};

Then, we create our own body:

RequestBody formBody = new FormBody.Builder()
        .add("username", userName)
        .add("password", password)
        .add("customCredential", "")
        .add("isPersistent", "true")
        .add("setCookie", "true")
        .build();

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(this)
        .build();
Request request = new Request.Builder()
        .url(loginUrl)
        .post(formBody)
        .build();

Finally, we call the server:

client.newCall(request).enqueue(loginCallback);

What is an HttpHandler in ASP.NET

Any Class that implements System.Web.IHttpHandler Interface becomes HttpHandler. And this class run as processes in response to a request made to the ASP.NET Site.

The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler(The Class that implements System.Web.IHttpHandler Interface).

You can create your own custom HTTP handlers that render custom output to the browser.

Some ASP.NET default handlers are:

  1. Page Handler (.aspx) – Handles Web pages
  2. User Control Handler (.ascx) – Handles Web user control pages
  3. Web Service Handler (.asmx) – Handles Web service pages
  4. Trace Handler (trace.axd) – Handles trace functionality

How to write and save html file in python?

print('<tr><td>%04d</td>' % (i+1), file=Html_file)

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

From inside of a Docker container, how do I connect to the localhost of the machine?

For Linux, where you cannot change the interface the localhost service binds to

There are two problems we need to solve

  1. Getting the IP of the host
  2. Making our localhost service available to Docker

The first problem can be solved using qoomon's docker-host image, as given by other answers.

You will need to add this container to the same bridge network as your other container so that you can access it. Open a terminal inside your container and ensure that you can ping dockerhost.

bash-5.0# ping dockerhost
PING dockerhost (172.20.0.2): 56 data bytes
64 bytes from 172.20.0.2: seq=0 ttl=64 time=0.523 ms

Now, the harder problem, making the service accessible to docker.

We can use telnet to check if we can access a port on the host (you may need to install this).

The problem is that our container will only be able to access services that bind to all interfaces, such as SSH:

bash-5.0# telnet dockerhost 22
SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3

But services bound only to localhost will be inaccessible:

bash-5.0# telnet dockerhost 1025
telnet: can't connect to remote host (172.20.0.2): Connection refused

The proper solution here would be to bind the service to dockers bridge network. However, this answer assumes that it is not possible for you to change this. So we will instead use iptables.

First, we need to find the name of the bridge network that docker is using with ifconfig. If you are using an unnamed bridge, this will just be docker0. However, if you are using a named network you will have a bridge starting with br- that docker will be using instead. Mine is br-5cd80298d6f4.

Once we have the name of this bridge, we need to allow routing from this bridge to localhost. This is disabled by default for security reasons:

sysctl -w net.ipv4.conf.<bridge_name>.route_localnet=1

Now to set up our iptables rule. Since our container can only access ports on the docker bridge network, we are going to pretend that our service is actually bound to a port on this network.

To do this, we will forward all requests to <docker_bridge>:port to localhost:port

iptables -t nat -A PREROUTING -p tcp -i <docker_bridge_name> --dport <service_port> -j DNAT --to-destination 127.0.0.1:<service_port>

For example, for my service on port 1025

iptables -t nat -A PREROUTING -p tcp -i br-5cd80298d6f4 --dport 1025 -j DNAT --to-destination 127.0.0.1:1025

You should now be able to access your service from the container:

bash-5.0# telnet dockerhost 1025
220 127.0.0.1 ESMTP Service Ready

How to handle authentication popup with Selenium WebDriver using Java

Popular solution is to append username and password in URL, like, http://username:[email protected]. However, if your username or password contains special character, then it may fail. So when you create the URL, make sure you encode those special characters.

String username = URLEncoder.encode(user, StandardCharsets.UTF_8.toString());
String password = URLEncoder.encode(pass, StandardCharsets.UTF_8.toString());
String url = “http://“ + username + “:” + password + “@website.com”;
driver.get(url);

Representing null in JSON

Let's evaluate the parsing of each:

http://jsfiddle.net/brandonscript/Y2dGv/

var json1 = '{}';
var json2 = '{"myCount": null}';
var json3 = '{"myCount": 0}';
var json4 = '{"myString": ""}';
var json5 = '{"myString": "null"}';
var json6 = '{"myArray": []}';

console.log(JSON.parse(json1)); // {}
console.log(JSON.parse(json2)); // {myCount: null}
console.log(JSON.parse(json3)); // {myCount: 0}
console.log(JSON.parse(json4)); // {myString: ""}
console.log(JSON.parse(json5)); // {myString: "null"}
console.log(JSON.parse(json6)); // {myArray: []}

The tl;dr here:

The fragment in the json2 variable is the way the JSON spec indicates null should be represented. But as always, it depends on what you're doing -- sometimes the "right" way to do it doesn't always work for your situation. Use your judgement and make an informed decision.


JSON1 {}

This returns an empty object. There is no data there, and it's only going to tell you that whatever key you're looking for (be it myCount or something else) is of type undefined.


JSON2 {"myCount": null}

In this case, myCount is actually defined, albeit its value is null. This is not the same as both "not undefined and not null", and if you were testing for one condition or the other, this might succeed whereas JSON1 would fail.

This is the definitive way to represent null per the JSON spec.


JSON3 {"myCount": 0}

In this case, myCount is 0. That's not the same as null, and it's not the same as false. If your conditional statement evaluates myCount > 0, then this might be worthwhile to have. Moreover, if you're running calculations based on the value here, 0 could be useful. If you're trying to test for null however, this is actually not going to work at all.


JSON4 {"myString": ""}

In this case, you're getting an empty string. Again, as with JSON2, it's defined, but it's empty. You could test for if (obj.myString == "") but you could not test for null or undefined.


JSON5 {"myString": "null"}

This is probably going to get you in trouble, because you're setting the string value to null; in this case, obj.myString == "null" however it is not == null.


JSON6 {"myArray": []}

This will tell you that your array myArray exists, but it's empty. This is useful if you're trying to perform a count or evaluation on myArray. For instance, say you wanted to evaluate the number of photos a user posted - you could do myArray.length and it would return 0: defined, but no photos posted.

How to increase timeout for a single test case in mocha

This worked for me! Couldn't find anything to make it work with before()

describe("When in a long running test", () => {
  it("Should not time out with 2000ms", async () => {
    let service = new SomeService();
    let result = await service.callToLongRunningProcess();
    expect(result).to.be.true;
  }).timeout(10000); // Custom Timeout 
});

Remove leading or trailing spaces in an entire column of data

If you would like to use a formula, the TRIM function will do exactly what you're looking for:

+----+------------+---------------------+
|    |     A      |           B         |
+----+------------+---------------------+
| 1  | =TRIM(B1)  |  value to trim here |
+----+------------+---------------------+

So to do the whole column...
1) Insert a column
2) Insert TRIM function pointed at cell you are trying to correct.
3) Copy formula down the page
4) Copy inserted column
5) Paste as "Values"

Should be good to go from there...

Closing Twitter Bootstrap Modal From Angular Controller

I have remixed the answer by @isubuz and this answer by @Umur Kontaci on attribute directives into a version where your controller doesn't call a DOM-like operation like "dismiss", but instead tries to be more MVVM style, setting a boolean property isInEditMode. The view in turn links this bit of info to the attribute directive that opens/closes the bootstrap modal.

_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
_x000D_
app.directive('myModal', function() {_x000D_
   return {_x000D_
     restrict: 'A',_x000D_
     scope: { myModalIsOpen: '=' },_x000D_
     link: function(scope, element, attr) {_x000D_
       scope.$watch(_x000D_
         function() { return scope.myModalIsOpen; },_x000D_
         function() { element.modal(scope.myModalIsOpen ? 'show' : 'hide'); }_x000D_
       );_x000D_
     }_x000D_
   } _x000D_
});_x000D_
_x000D_
app.controller('MyCtrl', function($scope) {_x000D_
  $scope.isInEditMode = false;_x000D_
  $scope.toggleEditMode = function() { _x000D_
    $scope.isInEditMode = !$scope.isInEditMode;_x000D_
  };_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="MyCtrl as vm">_x000D_
_x000D_
<div class="modal fade" my-modal my-modal-is-open="isInEditMode">_x000D_
  <div class="modal-dialog">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-body">_x000D_
        Modal body! IsInEditMode == {{isInEditMode}}_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button class="btn" ng-click="toggleEditMode()">Close</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<p><button class="btn" ng-click="toggleEditMode()">Toggle Edit Mode</button></p> _x000D_
<pre>isInEditMode == {{isInEditMode}}</pre>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the best way to conditionally apply a class?

Here is another option that works well when ng-class can't be used (for example when styling SVG):

ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"

(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)

How to stop docker under Linux

The output of ps aux looks like you did not start docker through systemd/systemctl.

It looks like you started it with:

sudo dockerd -H gridsim1103:2376

When you try to stop it with systemctl, nothing should happen as the resulting dockerd process is not controlled by systemd. So the behavior you see is expected.

The correct way to start docker is to use systemd/systemctl:

systemctl enable docker
systemctl start docker

After this, docker should start on system start.

EDIT: As you already have the docker process running, simply kill it by pressing CTRL+C on the terminal you started it. Or send a kill signal to the process.

Can I use complex HTML with Twitter Bootstrap's Tooltip?

The html data attribute does exactly what it says it does in the docs. Try this little example, no JavaScript necessary (broken into lines for clarification):

<span rel="tooltip" 
     data-toggle="tooltip" 
     data-html="true" 
     data-title="<table><tr><td style='color:red;'>complex</td><td>HTML</td></tr></table>"
>
hover over me to see HTML
</span>


JSFiddle demos:

How can I "disable" zoom on a mobile web page?

The solution using a meta-tag did not work for me (tested on Chrome win10 and safari IOS 14.3), and I also believe that the concerns regarding accessibility, as mentioned by Jack and others, should be honored.

My solution is to disable zooming only on elements that are damaged by the default zoom.

I did this by registering event listeners for zoom-gestures and using event.preventDefault() to suppress the browsers default zoom-behavior.

This needs to be done with several events (touch gestures, mouse wheel and keys). The following snippet is an example for the mouse wheel and pinch gestures on touchpads:

noteSheetCanvas.addEventListener("wheel", e => {
        // suppress browsers default zoom-behavior:
        e.preventDefault();

        // execution my own custom zooming-behavior:
        if (e.deltaY > 0) {
            this._zoom(1);
        } else {
            this._zoom(-1);
        }
    });

How to detect touch gestures is described here: https://stackoverflow.com/a/11183333/1134856

I used this to keep the standard zooming behavior for most parts of my application and to define custom zooming-behavior on a canvas-element.

How to export the Html Tables data into PDF using Jspdf

There is a tablePlugin for jspdf it expects array of objects and displays that data as a table. You can style the text and headers with little changes in the code. It is open source and also has examples for you to get started with.

Pycharm: run only part of my Python file

  1. Go to File >> Settings >> Plugins and install the plugin PyCharm cell mode
  2. Go to File >> Settings >> Appearance & Behavior >> Keymap and assign your keyboard shortcuts for Run Cell and Run Cell and go to next

A cell is delimited by ##

Ref https://plugins.jetbrains.com/plugin/7858-pycharm-cell-mode

Generate JSON string from NSDictionary in iOS

Now no need third party classes ios 5 introduced Nsjsonserialization

NSString *urlString=@"Your url";
NSString *urlUTF8 = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[[NSURL alloc]initWithString:urlUTF8];
NSURLRequest *request=[NSURLRequest requestWithURL:url];

NSURLResponse *response;

NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

NSError *myError = nil;

NSDictionary *res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:&myError];

Nslog(@"%@",res);

this code can useful for getting jsondata.

Getting an option text/value with JavaScript

You can use:

var option_user_selection = element.options[ element.selectedIndex ].text

Can CSS force a line break after each word in an element?

In my case,

    word-break: break-all;

worked perfecly, hope it helps any other newcomer like me.

Run MySQLDump without Locking Tables

Does the --lock-tables=false option work?

According to the man page, if you are dumping InnoDB tables you can use the --single-transaction option:

--lock-tables, -l

Lock all tables before dumping them. The tables are locked with READ
LOCAL to allow concurrent inserts in the case of MyISAM tables. For
transactional tables such as InnoDB and BDB, --single-transaction is
a much better option, because it does not need to lock the tables at
all.

For innodb DB:

mysqldump --single-transaction=TRUE -u username -p DB

Open link in new tab or window

set the target attribute of your <a> element to "_tab"

EDIT: It works, however W3Schools says there is no such target attribute: http://www.w3schools.com/tags/att_a_target.asp

EDIT2: From what I've figured out from the comments. setting target to _blank will take you to a new tab or window (depending on your browser settings). Typing anything except one of the ones below will create a new tab group (I'm not sure how these work):

_blank  Opens the linked document in a new window or tab
_self   Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frame
_top    Opens the linked document in the full body of the window
framename   Opens the linked document in a named frame

ERROR: Google Maps API error: MissingKeyMapError

Yes. Now Google wants an API key to authenticate users to access their APIs`.

You can get the API key from the following link. Go through the link and you need to enter a project and so on. But it is easy. Hassle free.

https://developers.google.com/maps/documentation/javascript/get-api-key

Once you get the API key change the previous

<script src="https://maps.googleapis.com/maps/api/js"></script>

to

<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=your_api_key_here"></script>

Now your google map is in action. In case if you are wondering to get the longitude and latitude to input to Maps. Just pin the location you want and check the URL of the browser. You can see longitude and latitude values there. Just copy those values and paste it as follows.

new google.maps.LatLng(longitude ,latitude )

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

Python+OpenCV: cv2.imwrite

enter image description here enter image description here enter image description here

Alternatively, with MTCNN and OpenCV(other dependencies including TensorFlow also required), you can:

1 Perform face detection(Input an image, output all boxes of detected faces):

from mtcnn.mtcnn import MTCNN
import cv2

face_detector = MTCNN()

img = cv2.imread("Anthony_Hopkins_0001.jpg")
detect_boxes = face_detector.detect_faces(img)
print(detect_boxes)

[{'box': [73, 69, 98, 123], 'confidence': 0.9996458292007446, 'keypoints': {'left_eye': (102, 116), 'right_eye': (150, 114), 'nose': (129, 142), 'mouth_left': (112, 168), 'mouth_right': (146, 167)}}]

2 save all detected faces to separate files:

for i in range(len(detect_boxes)):
    box = detect_boxes[i]["box"]
    face_img = img[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

3 or Draw rectangles of all detected faces:

for box in detect_boxes:
    box = box["box"]
    pt1 = (box[0], box[1]) # top left
    pt2 = (box[0] + box[2], box[1] + box[3]) # bottom right
    cv2.rectangle(img, pt1, pt2, (0,255,0), 2)
cv2.imwrite("detected-boxes.jpg", img)

How to set layout_gravity programmatically?

 int width=getResources().getDisplayMetrics().widthPixels; 
 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                    (width, width);

            params.gravity = Gravity.CENTER;

           iv_main_text = new HTextView(getContext());
            iv_main_text.setLayoutParams(params);
            iv_main_text.setBackgroundColor(Color.BLUE);
            iv_main_text.setTextSize(60);
            iv_main_text.setGravity(Gravity.CENTER);
            iv_main_text.setTextColor(Color.BLACK);

How to echo out the values of this array?

you need the set key and value in foreach loop for that:

foreach($item AS $key -> $value) {
echo $value;
}

this should do the trick :)

'npm' is not recognized as internal or external command, operable program or batch file

If the package is successfully installed and still shows the message "'npm' is not recognized as an internal or external command, operable program or batch file."

  1. Click windows start button.
  2. Look for "ALL APPS", you will see Node.js and Node.js Command prompt there.
  3. You can run the Node.js Command prompt as administrator and soon as its run it will show the message "Your environment has been set up for using Node.js 6.3.0 (x64) and npm."

and then it works from there...

Twitter Bootstrap button click to toggle expand/collapse text section above button

Based on the doc

<div class="row">
    <div class="span4 collapse-group">
        <h2>Heading</h2>
        <p class="collapse">Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
        <p><a class="btn" href="#">View details &raquo;</a></p>
    </div>
</div>
$('.row .btn').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    var $collapse = $this.closest('.collapse-group').find('.collapse');
    $collapse.collapse('toggle');
});

Working demo.

Incrementing a variable inside a Bash loop

You're getting final 0 because your while loop is being executed in a sub (shell) process and any changes made there are not reflected in the current (parent) shell.

Correct script:

while read -r country _; do
  if [ "US" = "$country" ]; then
        ((USCOUNTER++))
        echo "US counter $USCOUNTER"
  fi
done < "$FILE"

PyTorch: How to get the shape of a Tensor as a list of int

Previous answers got you list of torch.Size Here is how to get list of ints

listofints = [int(x) for x in tensor.shape]

Xcode Error: "The app ID cannot be registered to your development team."

This happened to me, even though I had already registered the Bundle Id with my account. It turns out that the capitalisation differed, so I had to change the bundle id in Xcode to lowercase, and it all worked. Hope that helps someone else :)

Maintaining Session through Angular.js

You would use a service for that in Angular. A service is a function you register with Angular, and that functions job is to return an object which will live until the browser is closed/refreshed. So it's a good place to store state in, and to synchronize that state with the server asynchronously as that state changes.

Fast way to get the min/max values among properties of object

You could try:

const obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
const max = Math.max.apply(null, Object.values(obj));
console.log(max) // 5

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

Perform Button click event when user press Enter key in Textbox

Put your form inside an asp.net panel control and set its defaultButton attribute with your button Id. See the code below:

  <asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
         <ContentTemplate>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Send" />
             </ContentTemplate>
          </asp:UpdatePanel>
    </asp:Panel>

Hope this will help you...

Google Maps V3 - How to calculate the zoom level for a given bounds

Thanks, that helped me a lot in finding the most suitable zoom factor to correctly display a polyline. I find the maximum and minimum coordinates among the points I have to track and, in case the path is very "vertical", I just added few lines of code:

var GLOBE_WIDTH = 256; // a constant in Google's map projection
var west = <?php echo $minLng; ?>;
var east = <?php echo $maxLng; ?>;
*var north = <?php echo $maxLat; ?>;*
*var south = <?php echo $minLat; ?>;*
var angle = east - west;
if (angle < 0) {
    angle += 360;
}
*var angle2 = north - south;*
*if (angle2 > angle) angle = angle2;*
var zoomfactor = Math.round(Math.log(960 * 360 / angle / GLOBE_WIDTH) / Math.LN2);

Actually, the ideal zoom factor is zoomfactor-1.

Cannot connect to the Docker daemon on macOS

Docker for Mac is deprecated. And you don't need Homebrew to run Docker on Mac. Instead you'll likely want to install Docker Desktop or, if already installed, make sure it's up-to-date and running, then attempt to connect to the socket again.

enter image description here

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

This is a problem of M2E for Eclipse M2E plugin execution not covered.

To solve this problem, all you got to do is to map the lifecycle it doesn't recognize and instruct M2E to execute it.

You should add this after your plugins, inside the build. This will remove the error and make M2E recognize the goal copy-depencies of maven-dependency-plugin and make the POM work as expected, copying dependencies to folder every time Eclipse build it. If you just want to ignore the error, then you change <execute /> for <ignore />. No need for enclosing your maven-dependency-plugin into pluginManagement, as suggested before.

<pluginManagement>
  <plugins>
    <plugin>
      <groupId>org.eclipse.m2e</groupId>
      <artifactId>lifecycle-mapping</artifactId>
      <version>1.0.0</version>
      <configuration>
        <lifecycleMappingMetadata>
          <pluginExecutions>
            <pluginExecution>
              <pluginExecutionFilter>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <versionRange>[2.0,)</versionRange>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
              </pluginExecutionFilter>
              <action>
                <execute />
              </action>
            </pluginExecution>
          </pluginExecutions>
        </lifecycleMappingMetadata>
      </configuration>
    </plugin>
  </plugins>
</pluginManagement>

1 = false and 0 = true?

It may very well be a mistake on the original author, however the notion that 1 is true and 0 is false is not a universal concept. In shell scripting 0 is returned for success, and any other number for failure. In other languages such as Ruby, only nil and false are considered false, and any other value is considered true, so in Ruby both 1 and 0 would be considered true.

How can I update a row in a DataTable in VB.NET?

Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue

Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.

SMTP connect() failed PHPmailer - PHP

If you're using VPS and with httpd service, please check if your httpd_can_sendmail is on.

getsebool -a | grep mail

to set on

setsebool -P httpd_can_sendmail on

Web Reference vs. Service Reference

Adding a service reference allows you to create a WCF client, which can be used to talk to a regular web service provided you use the appropriate binding. Adding a web reference will allow you to create only a web service (i.e., SOAP) reference.

If you are absolutely certain you are not ready for WCF (really don't know why) then you should create a regular web service reference.

Android: Getting a file URI from a content URI?

you can get filename by uri with simple way

Retrieving file information

fun get_filename_by_uri(uri : Uri) : String{
    contentResolver.query(uri, null, null, null, null).use { cursor ->
        cursor?.let {
            val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
            it.moveToFirst()
            return it.getString(nameIndex)
        }
    }
    return ""
}

and easy to read it by using

contentResolver.openInputStream(uri)

Running a cron job on Linux every six hours

Please keep attention at this syntax:

* */6 * * *

This means 60 times (every minute) every 6 hours,

not

one time every 6 hours.

What is the difference between a function expression vs declaration in JavaScript?

The first statement depends on the context in which it is declared.

If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.

If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"

EDIT:

I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.

END EDIT

Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore

var foo = function foo() { return 5; }

Is the same as

var foo = function fooYou() { return 5; }

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.

A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.

If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.

TIMESTAMP LIMITATION

The TIMESTAMP type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW().

how to update the multiple rows at a time using linq to sql?

Do not use the ToList() method as in the accepted answer !

Running SQL profiler, I verified and found that ToList() function gets all the records from the database. It is really bad performance !!

I would have run this query by pure sql command as follows:

string query = "Update YourTable Set ... Where ...";    
context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));

This would operate the update in one-shot without selecting even one row.

Determine the size of an InputStream

you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link

Get Bytes from Inputstream

Running a command as Administrator using PowerShell?

Here is an addition to Shay Levi's suggestion (just add these lines at the beginning of a script):

if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))  
{  
  $arguments = "& '" +$myinvocation.mycommand.definition + "'"
  Start-Process powershell -Verb runAs -ArgumentList $arguments
  Break
}

This results in the current script being passed to a new powershell process in Administrator mode (if current User has access to Administrator mode and the script is not launched as Administrator).

Date difference in minutes in Python

from datetime import datetime

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 17:31:22', fmt)

print (d2-d1).days * 24 * 60

PHP 7 simpleXML

Typically on Debian systems you have different PHP configuration for CLI and for PHP running as say an Apache module. Your phpinfo page may very well show simplexml as being enabled via web server, while it is not enabled via CLI.

Substitute a comma with a line break in a cell

You can also do this without VBA from the find/replace dialogue box. My answer was at https://stackoverflow.com/a/6116681/509840 .

Best way to convert an ArrayList to a string

Download the Apache Commons Lang and use the method

 StringUtils.join(list)

 StringUtils.join(list, ", ") // 2nd param is the separator.

You can implement it by yourself, of course, but their code is fully tested and is probably the best possible implementation.

I am a big fan of the Apache Commons library and I also think it's a great addition to the Java Standard Library.

Edit line thickness of CSS 'underline' attribute

_x000D_
_x000D_
a {_x000D_
  text-decoration: none;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
a.underline {_x000D_
  text-decoration: underline;_x000D_
}_x000D_
_x000D_
a.shadow {_x000D_
   box-shadow: inset 0 -4px 0 white, inset 0 -4.5px 0 blue;_x000D_
}
_x000D_
<h1><a href="#" class="underline">Default: some text alpha gamma<br>the quick brown fox</a></h1>_x000D_
<p>Working:</p>_x000D_
<h1><a href="#" class="shadow">Using Shadow: some text alpha gamma<br>the quick brown fox<br>even works with<br>multiple lines</a></h1>_x000D_
<br>
_x000D_
_x000D_
_x000D_

Final Solution: http://codepen.io/vikrant-icd/pen/gwNqoM

a.shadow {
   box-shadow: inset 0 -4px 0 white, inset 0 -4.5px 0 blue;
}

Is it possible to refresh a single UITableViewCell in a UITableView?

I need the upgrade cell but I want close the keyboard. If I use

let indexPath = NSIndexPath(forRow: path, inSection: 1)
tableView.beginUpdates()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) //try other animations
tableView.endUpdates()

the keyboard disappear

End-line characters from lines read from text file, using Python

Long time ago, there was Dear, clean, old, BASIC code that could run on 16 kb core machines: like that:

if (not open(1,"file.txt")) error "Could not open 'file.txt' for reading"
while(not eof(1)) 
  line input #1 a$
  print a$
wend
close

Now, to read a file line by line, with far better hardware and software (Python), we must reinvent the wheel:

def line_input (file):
    for line in file:
        if line[-1] == '\n':
            yield line[:-1]
        else:
            yield line

f = open("myFile.txt", "r")
for line_input(f):
    # do something with line

I am induced to think that something has gone the wrong way somewhere...

Java method to sum any number of ints

Use var args

public long sum(int... numbers){
      if(numbers == null){ return 0L;}
      long result = 0L;
      for(int number: numbers){
         result += number;
      }
      return result;   
}

How to configure encoding in Maven?

If you combine the answers above, finally a pom.xml that configured for UTF-8 should seem like that.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>YOUR_COMPANY</groupId>
    <artifactId>YOUR_APP</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <project.java.version>1.8</project.java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>
        <!-- Your dependencies -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>${project.java.version}</source>
                    <target>${project.java.version}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Uncompress tar.gz file

gunzip <filename>

then

tar -xvf <tar-file-name>

MySQL trigger if condition exists

Try to do...

 DELIMITER $$
        CREATE TRIGGER aumentarsalario 
        BEFORE INSERT 
        ON empregados
        FOR EACH ROW
        BEGIN
          if (NEW.SALARIO < 900) THEN 
             set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
          END IF;
        END $$
  DELIMITER ;

How to sort a list of strings?

It is simple: https://trinket.io/library/trinkets/5db81676e4

scores = '54 - Alice,35 - Bob,27 - Carol,27 - Chuck,05 - Craig,30 - Dan,27 - Erin,77 - Eve,14 - Fay,20 - Frank,48 - Grace,61 - Heidi,03 - Judy,28 - Mallory,05 - Olivia,44 - Oscar,34 - Peggy,30 - Sybil,82 - Trent,75 - Trudy,92 - Victor,37 - Walter'

scores = scores.split(',') for x in sorted(scores): print(x)

How to pick just one item from a generator?

You can pick specific items using destructuring, e.g.:

>>> [first, *middle, last] = range(10)
>>> first
0
>>> middle
[1, 2, 3, 4, 5, 6, 7, 8]
>>> last
9

Note that this is going to consume your generator, so while highly readable, it is less efficient than something like next(), and ruinous on infinite generators:

>>> [first, *rest] = itertools.count()

System not declared in scope?

Chances are that you've not included the header file that declares system().

In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include preprocessor directive. As the code does not #include the header file in which system() is declared, the compilation fails.

To fix this issue, find out which header file provides you with the declaration of system() and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>

Setting DIV width and height in JavaScript

If you remove the javascript: prefix and remove the parts for the unknown ids like 'black_fade' from your javascript code, this should work in firefox

Condensed example:

<html>
    <head>
        <script type="text/javascript">
            function show_update_profile() {
               document.getElementById('div_register').style.height= "500px";
               document.getElementById('div_register').style.width= "500px";
               document.getElementById('div_register').style.display='block';
               return true;
           }
        </script>
        <style>
           /* just to show dimensions of div */
           #div_register
           {
                background-color: #cfc;
           }
        </style>
    </head>
    <body>
        <div id="main">
            <input type="button" onclick="show_update_profile();" value="show"/>
        </div>
        <div id="div_register">
            <table>
                <tr>
                   <td>
                     welcome 
                   </td>
                </tr>
            </table>
        </div>
    </body>
</html>

fork and exec in bash

Use the ampersand just like you would from the shell.

#!/usr/bin/bash
function_to_fork() {
   ...
}

function_to_fork &
# ... execution continues in parent process ...

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

To people that can't get above fixes working.

Had to change file ssl.py to fix it. Look for function create_default_context and change line:

context = SSLContext(PROTOCOL_SSLv23)

to

context = SSLContext(PROTOCOL_TLSv1)

Maybe someone can create easier solution without editing ssl.py?

Can't Load URL: The domain of this URL isn't included in the app's domains

Adding my localhost on Valid OAuth redirect URIs at https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/ solved the problem!

And pay attention for one detail here:

In this case http://localhost:3000 is not the same of http://0.0.0.0:3000 or http://127.0.0.1:3000

Make sure you are using exactly the running url of you sandbox server. I spend some time to discover that...

enter image description here

Can someone explain how to append an element to an array in C programming?

int arr[10] = {0, 5, 3, 64};
arr[4] = 5;

EDIT: So I was asked to explain what's happening when you do:

int arr[10] = {0, 5, 3, 64};

you create an array with 10 elements and you allocate values for the first 4 elements of the array.

Also keep in mind that arr starts at index arr[0] and ends at index arr[9] - 10 elements

arr[0] has value 0;
arr[1] has value 5;
arr[2] has value 3;
arr[3] has value 64;

after that the array contains garbage values / zeroes because you didn't allocated any other values

But you could still allocate 6 more values so when you do

arr[4] = 5;

you allocate the value 5 to the fifth element of the array.

You could do this until you allocate values for the last index of the arr that is arr[9];

Sorry if my explanation is choppy, but I have never been good at explaining things.

Convert Java String to sql.Timestamp

Here's the intended way to convert a String to a Date:

String timestamp = "2011-10-02-18.48.05.123";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS");
Date parsedDate = df.parse(timestamp);

Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds.

Maven: best way of linking custom external JAR to my project?

The best solution here is to install a repository: Nexus or Artifactory. If gives you a place to put things like this, and further it speeds things up by caching your stuff from the outside.

If the thing you are dealing with is open source, you might also consider putting in into central.

See the guide.

How to install 2 Anacondas (Python 2 and 3) on Mac OS

There is no need to install Anaconda again. Conda, the package manager for Anaconda, fully supports separated environments. The easiest way to create an environment for Python 2.7 is to do

conda create -n python2 python=2.7 anaconda

This will create an environment named python2 that contains the Python 2.7 version of Anaconda. You can activate this environment with

source activate python2

This will put that environment (typically ~/anaconda/envs/python2) in front in your PATH, so that when you type python at the terminal it will load the Python from that environment.

If you don't want all of Anaconda, you can replace anaconda in the command above with whatever packages you want. You can use conda to install packages in that environment later, either by using the -n python2 flag to conda, or by activating the environment.

URL.Action() including route values

You also can use in this form:

<a href="@Url.Action("Information", "Admin", null)"> Admin</a>

npm notice created a lockfile as package-lock.json. You should commit this file

Yes. You should add this file to your version control system, i.e. You should commit it.

This file is intended to be committed into source repositories

You can read more about what it is/what it does here:

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

Adding event listeners to dynamically added elements using jQuery

$(document).on('click', 'selector', handler);

Where click is an event name, and handler is an event handler, like reference to a function or anonymous function function() {}

PS: if you know the particular node you're adding dynamic elements to - you could specify it instead of document.

Mail multipart/alternative vs multipart/mixed

Great Answer Lain!

There were a couple things I did to make this work in a broader set of devices. At the end I will list the clients I tested on.

  1. I added a new build constructor that did not contain the parameter attachments and did not use MimeMultipart("mixed"). There is no need for mixed if you are sending only inline images.

    public Multipart build(String messageText, String messageHtml, List<URL> messageHtmlInline) throws MessagingException {
    
        final Multipart mpAlternative = new MimeMultipart("alternative");
        {
            //  Note: MUST RENDER HTML LAST otherwise iPad mail client only renders 
            //  the last image and no email
                addTextVersion(mpAlternative,messageText);
                addHtmlVersion(mpAlternative,messageHtml, messageHtmlInline);
        }
    
        return mpAlternative;
    }
    
  2. In addTextVersion method I added charset when adding content this probably could/should be passed in, but I just added it statically.

    textPart.setContent(messageText, "text/plain");
    to
    textPart.setContent(messageText, "text/plain; charset=UTF-8");
    
  3. The last item was adding to the addImagesInline method. I added setting the image filename to the header by the following code. If you don't do this then at least on Android default mail client it will have inline images that have a name of Unknown and will not automatically download them and present in email.

    for (URL img : embeded) {
        final MimeBodyPart htmlPartImg = new MimeBodyPart();
        DataSource htmlPartImgDs = new URLDataSource(img);
        htmlPartImg.setDataHandler(new DataHandler(htmlPartImgDs));
        String fileName = img.getFile();
        fileName = getFileName(fileName);
        String newFileName = cids.get(fileName);
        boolean imageNotReferencedInHtml = newFileName == null;
        if (imageNotReferencedInHtml) continue;
        htmlPartImg.setHeader("Content-ID", "<"+newFileName+">");
        htmlPartImg.setDisposition(BodyPart.INLINE);
        **htmlPartImg.setFileName(newFileName);**
        parent.addBodyPart(htmlPartImg);
    }
    

So finally, this is the list of clients I tested on. Outlook 2010, Outlook Web App, Internet Explorer 11, Firefox, Chrome, Outlook using Apple’s native app, Email going through Gmail - Browser mail client, Internet Explorer 11, Firefox, Chrome, Android default mail client, osx IPhone default mail client, Gmail mail client on Android, Gmail mail client on IPhone, Email going through Yahoo - Browser mail client, Internet Explorer 11, Firefox, Chrome, Android default mail client, osx IPhone default mail client.

Hope that helps anyone else.

What's the difference between subprocess Popen and call (how can I use them)?

The other answer is very complete, but here is a rule of thumb:

  • call is blocking:

    call('notepad.exe')
    print('hello')  # only executed when notepad is closed
    
  • Popen is non-blocking:

    Popen('notepad.exe')
    print('hello')  # immediately executed
    

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

Changing the 'w' (write) in this line:

output = csv.DictWriter(open('file3.csv','w'), delimiter=',', fieldnames=headers)

To 'wb' (write binary) fixed this problem for me:

output = csv.DictWriter(open('file3.csv','wb'), delimiter=',', fieldnames=headers)

Python v2.75: Open()

Credit to @dandrejvv for the solution in the comment on the original post above.

How to write character & in android strings.xml

Mac and Android studio users:

Type your char such as & in the string.xml or layout and choose "Option" and "return" keys. Please refer the screen shot

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

Pure datetime solution, does not depend on language or DATEFORMAT, no strings

SELECT
    DATEADD(year, [year]-1900, DATEADD(month, [month]-1, DATEADD(day, [day]-1, 0)))
FROM
    dbo.Table

Cygwin Make bash command not found

follow some steps below:

  1. open cygwin setup again

  2. choose catagory on view tab

  3. fill "make" in search tab

  4. expand devel

  5. find "make: a GNU version of the 'make' ultility", click to install

  6. Done!

ValueError: math domain error

you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.

What are functional interfaces used for in Java 8?

The documentation makes indeed a difference between the purpose

An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.

and the use case

Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

whose wording does not preclude other use cases in general. Since the primary purpose is to indicate a functional interface, your actual question boils down to “Are there other use cases for functional interfaces other than lambda expressions and method/constructor references?”

Since functional interface is a Java language construct defined by the Java Language Specification, only that specification can answer that question:

JLS §9.8. Functional Interfaces:

In addition to the usual process of creating an interface instance by declaring and instantiating a class (§15.9), instances of functional interfaces can be created with method reference expressions and lambda expressions (§15.13, §15.27).

So the Java Language Specification doesn’t say otherwise, the only use case mentioned in that section is that of creating interface instances with method reference expressions and lambda expressions. (This includes constructor references as they are noted as one form of method reference expression in the specification).

So in one sentence, no, there is no other use case for it in Java 8.

Google API authentication: Not valid origin for the client

I received the same console error message when working with this example: https://developers.google.com/analytics/devguides/reporting/embed/v1/getting-started

The documentation says not to overlook two critical steps ("As you go through the instructions, it's important that you not overlook these two critical steps: Enable the Analytics API [&] Set the correct origins"), but does not clearly state WHERE to set the correct origins.

Since the client ID I had was not working, I created a new project and a new client ID. The new project may not have been necessary, but I'm retaining (and using) it.

Here's what worked:

During creation of the credentials, you will see a section called "Restrictions Enter JavaScript origins, redirect URIs, or both". This is where you can enter your origins.

Save and copy your client ID (and secret).

My script worked after I created the new OAUTH credential, assigned the origin, and used the newly generated client ID following this process.

How to read file contents into a variable in a batch file?

To get all the lines of the file loaded into the variable, Delayed Expansion is needed, so do the following:

SETLOCAL EnableDelayedExpansion

for /f "Tokens=* Delims=" %%x in (version.txt) do set Build=!Build!%%x

There is a problem with some special characters, though especially ;, % and !

How to git-svn clone the last n revisions from a Subversion repository?

... 7 years later, in the desert, a tumbleweed blows by ...

I wasn't satisfied with the accepted answer so I created some scripts to do this for you available on Github. These should help anyone who wants to use git svn clone but doesn't want to clone the entire repository and doesn't want to hunt for a specific revision to clone from in the middle of the history (maybe you're cloning a bunch of repos). Here we can just clone the last N revisions:

Use git svn clone to clone the last 50 revisions

# -u    The SVN URL to clone
# -l    The limit of revisions
# -o    The output directory

./git-svn-cloneback.sh -u https://server/project/trunk -l 50 -o myproj --authors-file=svn-authors.txt

Find the previous N revision from an SVN repo

# -u    The SVN URL to clone
# -l    The limit of revisions

./svn-lookback.sh -u https://server/project/trunk -l 5     

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Calling conventions defines how parameters are passed in the registers when calling or being called by other program. And the best source of these convention is in the form of ABI standards defined for each these hardware. For ease of compilation, the same ABI is also used by userspace and kernel program. Linux/Freebsd follow the same ABI for x86-64 and another set for 32-bit. But x86-64 ABI for Windows is different from Linux/FreeBSD. And generally ABI does not differentiate system call vs normal "functions calls". Ie, here is a particular example of x86_64 calling conventions and it is the same for both Linux userspace and kernel: http://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64/ (note the sequence a,b,c,d,e,f of parameters):

A good rendering of calling conventions vs registers usage

Performance is one of the reasons for these ABI (eg, passing parameters via registers instead of saving into memory stacks)

For ARM there is various ABI:

http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.subset.swdev.abi/index.html

https://developer.apple.com/library/ios/documentation/Xcode/Conceptual/iPhoneOSABIReference/iPhoneOSABIReference.pdf

ARM64 convention:

http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf

For Linux on PowerPC:

http://refspecs.freestandards.org/elf/elfspec_ppc.pdf

http://www.0x04.net/doc/elf/psABI-ppc64.pdf

And for embedded there is the PPC EABI:

http://www.freescale.com/files/32bit/doc/app_note/PPCEABI.pdf

This document is good overview of all the different conventions:

http://www.agner.org/optimize/calling_conventions.pdf

Writing File to Temp Folder

You can dynamically retrieve a temp path using as following and better to use it instead of using hard coded string value for temp location.It will return the temp folder or temp file as you want.

string filePath = Path.Combine(Path.GetTempPath(),"SaveFile.txt");

or

Path.GetTempFileName();

How to run Tensorflow on CPU

In some systems one have to specify:

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=""  # or even "-1"

BEFORE importing tensorflow.

Open Google Chrome from VBA/Excel

Worked here too:

Sub test544()

  Dim chromePath As String

  chromePath = """C:\Program Files\Google\Chrome\Application\chrome.exe"""

  Shell (chromePath & " -url http:google.ca")

End Sub

Cannot install packages using node package manager in Ubuntu

for me problem was solved by,

sudo apt-get remove node
sudo apt-get remove nodejs
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
alias node=nodejs
rm -r /usr/local/lib/python2.7/dist-packages/localstack/node_modules
npm install -g npm@latest || sudo npm install -g npm@latest

Difference between angle bracket < > and double quotes " " while including header files in C++?

When you use angle brackets, the compiler searches for the file in the include path list. When you use double quotes, it first searches the current directory (i.e. the directory where the module being compiled is) and only then it'll search the include path list.

So, by convention, you use the angle brackets for standard includes and the double quotes for everything else. This ensures that in the (not recommended) case in which you have a local header with the same name as a standard header, the right one will be chosen in each case.

Making TextView scrollable on Android

In my case.Constraint Layout.AS 2.3.

Code implementation:

YOUR_TEXTVIEW.setMovementMethod(new ScrollingMovementMethod());

XML:

android:scrollbars="vertical"
android:scrollIndicators="right|end"

How to get and set the current web page scroll position?

I went with the HTML5 local storage solution... All my links call a function which sets this before changing window.location:

localStorage.topper = document.body.scrollTop;

and each page has this in the body's onLoad:

  if(localStorage.topper > 0){ 
    window.scrollTo(0,localStorage.topper);
  }

Create a new txt file using VB.NET

You could just use this

FileOpen(1, "C:\my files\2010\SomeFileName.txt", OpenMode.Output)
FileClose(1)

This opens the file replaces whatever is in it and closes the file.

What is LD_LIBRARY_PATH and how to use it?

Well, the error message tells you what to do: add the path where Jacob.dll resides to java.library.path. You can do that on the command line like this:

java -Djava.library.path="dlls" ...

(assuming Jacob.dll is in the "dlls" folder)

Also see java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

Parsing HTTP Response in Python

I guess things have changed in python 3.4. This worked for me:

print("resp:" + json.dumps(resp.json()))

Simplest way to detect keypresses in javascript

KEYPRESS (enter key)
Click inside the snippet and press Enter key.

Vanilla

_x000D_
_x000D_
document.addEventListener("keypress", function(event) {
  if (event.keyCode == 13) {
    alert('hi.');
  }
});
_x000D_
_x000D_
_x000D_

Vanilla shorthand (ES6)

_x000D_
_x000D_
this.addEventListener('keypress', event => {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
$(this).on('keypress', function(event) {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery classic

_x000D_
_x000D_
$(this).keypress(function(event) {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery shorthand (ES6)

_x000D_
_x000D_
$(this).keypress((e) => {
  if (e.keyCode == 13)
    alert('hi.')
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Even shorter (ES6)

_x000D_
_x000D_
$(this).keypress(e=>
  e.which==13?
  alert`hi.`:null
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Due some requests, here an explanation:

I rewrote this answer as things have become deprecated over time so I updated it.

I used this to focus on the window scope inside the results when document is ready and for the sake of brevity but it's not necessary.

Deprecated:
The .which and .keyCode methods are actually considered deprecated so I would recommend .code but I personally still use keyCode as the performance is much faster and only that counts for me. The jQuery classic version .keypress() is not officially deprecated as some people say but they are no more preferred like .on('keypress') as it has a lot more functionality(live state, multiple handlers, etc.). The 'keypress' event in the Vanilla version is also deprecated. People should prefer beforeinput or keydown today. (Note: It has nothing to do with jQuery's events, they are called the same but execute differently.)

All examples above are no biggies regarding deprecated or not. Consoles or any browser should be able to notify you with that if this happens. And if this ever does in future, just fix it.

Readablity:
Despite the ease making it too short and snippy isn't always good either. If you work in a team, your code must be readable and detailed. I recommend the jQuery version .on('keypress'), this is the way to go and understandable by most people.

Performance:
I always follow my phrase Performance over Effectiveness as anything can be more effective if there is the option but it just should function and execute only what I want, the faster the better. This is why I prefer .keyCode even if it's considered deprecated(in most cases). It's all up to you though.

Performance Test

Stop a youtube video with jquery?

To start video

var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);

To stop video

var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);

You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters

works for both vimeo and youtube on FF & Chrome

Send data from javascript to a mysql database

JavaScript, as defined in your question, can't directly work with MySql. This is because it isn't running on the same computer.

JavaScript runs on the client side (in the browser), and databases usually exist on the server side. You'll probably need to use an intermediate server-side language (like PHP, Java, .Net, or a server-side JavaScript stack like Node.js) to do the query.

Here's a tutorial on how to write some code that would bind PHP, JavaScript, and MySql together, with code running both in the browser, and on a server:

http://www.w3schools.com/php/php_ajax_database.asp

And here's the code from that page. It doesn't exactly match your scenario (it does a query, and doesn't store data in the DB), but it might help you start to understand the types of interactions you'll need in order to make this work.

In particular, pay attention to these bits of code from that article.

Bits of Javascript:

xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();

Bits of PHP code:

mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
// ...
$row = mysql_fetch_array($result)
mysql_close($con);

Also, after you get a handle on how this sort of code works, I suggest you use the jQuery JavaScript library to do your AJAX calls. It is much cleaner and easier to deal with than the built-in AJAX support, and you won't have to write browser-specific code, as jQuery has cross-browser support built in. Here's the page for the jQuery AJAX API documentation.

The code from the article

HTML/Javascript code:

<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html>

PHP code:

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

Which version of Python do I have installed?

To check the Python version in a Jupyter notebook, you can use:

from platform import python_version
print(python_version())

to get version number, as:

3.7.3

or:

import sys
print(sys.version)

to get more information, as

3.7.3 (default, Apr 24 2019, 13:20:13) [MSC v.1915 32 bit (Intel)]

or:

sys.version_info

to get major, minor and micro versions, as

sys.version_info(major=3, minor=7, micro=3, releaselevel='final', serial=0)

Converting a char to uppercase

Have a look at the java.lang.Character class, it provides a lot of useful methods to convert or test chars.

Resolving require paths with webpack

For future reference, webpack 2 removed everything but modules as a way to resolve paths. This means root will not work.

https://gist.github.com/sokra/27b24881210b56bbaff7#resolving-options

The example configuration starts with:

{
  modules: [path.resolve(__dirname, "app"), "node_modules"]
  // (was split into `root`, `modulesDirectories` and `fallback` in the old options)

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

I had the same problem cause i had no public keys, so i did:

heroku keys:clear
heroku keys:add

That will generate a public key and then it works well

How to merge multiple lists into one list in python?

Just add them:

['it'] + ['was'] + ['annoying']

You should read the Python tutorial to learn basic info like this.

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here

How to remove pip package after deleting it manually

  1. Go to the site-packages directory where pip is installing your packages.
  2. You should see the egg file that corresponds to the package you want to uninstall. Delete the egg file (or, to be on the safe side, move it to a different directory).
  3. Do the same with the package files for the package you want to delete (in this case, the psycopg2 directory).
  4. pip install YOUR-PACKAGE

How to test an SQL Update statement before running it?

Autocommit OFF ...

MySQL

set autocommit=0;

It sets the autommit off for the current session.

You execute your statement, see what it has changed, and then rollback if it's wrong or commit if it's what you expected !

EDIT: The benefit of using transactions instead of running select query is that you can check the resulting set easierly.

java.math.BigInteger cannot be cast to java.lang.Long

Better option is use SQLQuery#addScalar than casting to Long or BigDecimal.

Here is modified query that returns count column as Long

Query query = session
             .createSQLQuery("SELECT COUNT(*) as count
                             FROM SpyPath 
                             WHERE DATE(time)>=DATE_SUB(CURDATE(),INTERVAL 6 DAY) 
                             GROUP BY DATE(time) 
                             ORDER BY time;")
             .addScalar("count", LongType.INSTANCE);

Then

List<Long> result = query.list(); //No ClassCastException here  

Related link

How do I use Apache tomcat 7 built in Host Manager gui?

Tomcat 8:

The following worked for me with tomcat 8.

Add these lines to apache-tomcat-8.0.9/conf/tomcat-users.xml

For Manager:

<role rolename="manager-gui"/>
<user username="admin" password="pass" roles="manager-gui"/>

For Host Manager:

<role rolename="admin-gui"/>
<user username="admin" password="pass" roles="admin-gui"/>