Programs & Examples On #Merge module

Find distance between two points on map using Google Map API V2

In android google maps application there is a very easy way to find distance between 2 locations, to do so follow the following easy steps:

  1. when you first open the app go to " your timeline " from the drop menue on the top left.

  2. once the new windwo opens, chose from the settings on your top right menue and choose "add place".

  3. add your places and name them lilke point 1 , point 2 , or any easy name to remember.
  4. once your places are added and flagged go back to the main Window in your google app.
  5. click on the blue circle with the arrow in your bottom right.
  6. a new windwo will open and you can see on the top there are two text fields in which you can add your "from location" and "distance location".
  7. click on any text field and type in your saved location in point 3.
  8. click on the other text field and add your next saved location.
  9. By doing so, google maps will calculate the distance between the two locations and show you the blue path on map ..

Good luck

Add a new column to existing table in a migration

You can add new columns within the initial Schema::create method like this:

Schema::create('users', function($table) {
    $table->integer("paied");
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

If you have already created a table you can add additional columns to that table by creating a new migration and using the Schema::table method:

Schema::table('users', function($table) {
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

The documentation is fairly thorough about this, and hasn't changed too much from version 3 to version 4.

Simple dynamic breadcrumb

Here is my solution based on Skeptic answer. It gets page title from WordPress DB, not from URL because there is a problem with latin characters (slug doesn't has a latin characters). You can also choose to display "home" item or not.

/**
 * Show Breadcrumbs
 * 
 * @param string|bool $home
 * @param string $class
 * @return string
 * 
 * Using: echo breadcrumbs();
 */
function breadcrumbs($home = 'Home', $class = 'items') {
    $breadcrumb  = '<ul class="'. $class .'">';
    $breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

    if ($home) {
        $breadcrumb .= '<li><a href="' . get_site_url() . '">' . $home . '</a></li>';
    }

    $path = '';
    foreach ($breadcrumbs as $crumb) {
        $path .=  $crumb . '/';
        $page = get_page_by_path($path);

        if ($home && ($page->ID == get_option('page_on_front'))) {
            continue;
        }

        $breadcrumb .= '<li><a href="'. get_permalink($page) .'">' . $page->post_title . '</a></li>';
    }

    $breadcrumb .= '</ul>';
    return $breadcrumb;
}

Using:

<div class="breadcrumb">
    <div class="container">
        <h3 class="breadcrumb__title">Jazda na maxa!</h3>
        <?php echo breadcrumbs('Start', 'breadcrumb__items'); ?>
    </div>
</div>

Position a div container on the right side

This works for me.

<div style="position: relative;width:100%;">
    <div style="position:absolute;left:0px;background-color:red;width:25%;height:100px;">
      This will be on the left
    </div>

    <div style="position:absolute;right:0px;background-color:blue;width:25%;height:100px;">
      This will be on the right
    </div>
</div>

Get the key corresponding to the minimum value within a dictionary

If you are not sure that you have not multiple minimum values, I would suggest:

d = {320:1, 321:0, 322:3, 323:0}
print ', '.join(str(key) for min_value in (min(d.values()),) for key in d if d[key]==min_value)

"""Output:
321, 323
"""

Pointer vs. Reference

A reference is an implicit pointer. Basically you can change the value the reference points to but you can't change the reference to point to something else. So my 2 cents is that if you only want to change the value of a parameter pass it as a reference but if you need to change the parameter to point to a different object pass it using a pointer.

Android Studio: Plugin with id 'android-library' not found

Just for the record (took me quite a while) before Grzegorzs answer worked for me I had to install "android support repository" through the SDK Manager!

Install it and add the following code above apply plugin: 'android-library' in the build.gradle of actionbarsherlock folder!

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.+'
    }
}

What's the difference between Visual Studio Community and other, paid versions?

All these answers are partially wrong.

Microsoft has clarified that Community is for ANY USE as long as your revenue is under $1 Million US dollars. That is literally the only difference between Pro and Community. Corporate or free or not, irrelevant.

Even the lack of TFS support is not true. I can verify it is present and works perfectly.

EDIT: Here is an MSDN post regarding the $1M limit: MSDN (hint: it's in the VS 2017 license)

EDIT: Even over the revenue limit, open source is still free.

Fitting a Normal distribution to 1D data

There is a much simpler way to do it using seaborn:

import seaborn as sns
from scipy.stats import norm

data = norm.rvs(5,0.4,size=1000) # you can use a pandas series or a list if you want

sns.distplot(data)
plt.show()

output:

enter image description here

for more information:seaborn.distplot

How to get the PID of a process by giving the process name in Mac OS X ?

The answer above was mostly correct, just needed some tweaking for the different parameters in Mac OSX.

ps -A | grep [f]irefox | awk '{print $1}'

100% height minus header?

As mentioned in the comments height:100% relies on the height of the parent container being explicitly defined. One way to achieve what you want is to use absolute/relative positioning, and specifying the left/right/top/bottom properties to "stretch" the content out to fill the available space. I have implemented what I gather you want to achieve in jsfiddle. Try resizing the Result window and you will see the content resizes automatically.

The limitation of this approach in your case is that you have to specify an explicit margin-top on the parent container to offset its contents down to make room for the header content. You can make it dynamic if you throw in javascript though.

How to do something to each file in a directory with a batch script

Use

for /r path %%var in (*.*) do some_command %%var

with:

  • path being the starting path.
  • %%var being some identifier.
  • *.* being a filemask OR the contents of a variable.
  • some_command being the command to execute with the path and var concatenated as parameters.

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

I got this error after upgrading from Visual Studio 2013 to 2015. After a bit of searching and trying various fixes I found the problem can be resolved by removing the following from web.config:

<staticContent>
    <mimeMap fileExtension=".less" mimeType="text/css" />
</staticContent >

Apparently staticContent is deprecated now?

Source

Edit 1

This sort of prevented IIS from serving .json files when the program was deployed. If you do this you're supposed to re-add .json (application/json) to the mime types of your site in IIS. Here is some more info: http://www.iis.net/configreference/system.webserver/staticcontent/mimemap

Edit 2

I noticed that in my situation the above edit 1 solution only works temporarily. Once I redeploy the entry gets removed. So, I moved the mimeMap XML into Web.Release.config. Works fine now.

android pick images from gallery

Absolutely. Try this:

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);

Don't forget also to create the constant PICK_IMAGE, so you can recognize when the user comes back from the image gallery Activity:

public static final int PICK_IMAGE = 1;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == PICK_IMAGE) {
        //TODO: action
    }
}

That's how I call the image gallery. Put it in and see if it works for you.

EDIT:

This brings up the Documents app. To allow the user to also use any gallery apps they might have installed:

    Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
    getIntent.setType("image/*");

    Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    pickIntent.setType("image/*");

    Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});

    startActivityForResult(chooserIntent, PICK_IMAGE);

Using IS NULL or IS NOT NULL on join conditions - Theory question

Your execution plan should make this clear; the JOIN takes precedence, after which the results are filtered.

What does %~dp0 mean, and how does it work?

The variable %0 in a batch script is set to the name of the executing batch file.

The ~dp special syntax between the % and the 0 basically says to expand the variable %0 to show the drive letter and path, which gives you the current directory containing the batch file!

Help = Link

How can I get list of values from dict?

Yes it's the exact same thing in Python 2:

d.values()

In Python 3 (where dict.values returns a view of the dictionary’s values instead):

list(d.values())

How do I use $scope.$watch and $scope.$apply in AngularJS?

Just finish reading ALL the above, boring and sleepy (sorry but is true). Very technical, in-depth, detailed, and dry. Why am I writing? Because AngularJS is massive, lots of inter-connected concepts can turn anyone going nuts. I often asked myself, am I not smart enough to understand them? No! It's because so few can explain the tech in a for-dummie language w/o all the terminologies! Okay, let me try:

1) They are all event-driven things. (I hear the laugh, but read on)

If you don't know what event-driven is Then think you place a button on the page, hook it up w/ a function using "on-click", waiting for users to click on it to trigger the actions you plant inside the function. Or think of "trigger" of SQL Server / Oracle.

2) $watch is "on-click".

What's special about is it takes 2 functions as parameters, first one gives the value from the event, second one takes the value into consideration...

3) $digest is the boss who checks around tirelessly, bla-bla-bla but a good boss.

4) $apply gives you the way when you want to do it manually, like a fail-proof (in case on-click doesn't kick in, you force it to run.)

Now, let's make it visual. Picture this to make it even more easy to grab the idea:

In a restaurant,

- WAITERS

are supposed to take orders from customers, this is

$watch(
  function(){return orders;},
  function(){Kitchen make it;}
);

- MANAGER running around to make sure all waiters are awake, responsive to any sign of changes from customers. This is $digest()

- OWNER has the ultimate power to drive everyone upon request, this is $apply()

Send password when using scp to copy files from one server to another

Just pass with sshpass -p "your password" at the beginning of your scp command

sshpass -p "your password" scp ./abc.txt hostname/abc.txt

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

I had faced the similar error when supporting one application. It was about the generated classes for a SOAP Webservice.

The issue was caused due to the missing classes. When javax.xml.bind.Marshaller was trying to marshal the jaxb object it was not finding all dependent classes which were generated by using wsdl and xsd. after adding the jar with all the classes at the class path the issue was resolved.

sys.stdin.readline() reads without prompt, returning 'nothing in between'

stdin.read(1)

will not return when you press one character - it will wait for '\n'. The problem is that the second character is buffered in standard input, and the moment you call another input - it will return immediately because it gets its input from buffer.

How to tell a Mockito mock object to return something different the next time it is called?

First of all don't make the mock static. Make it a private field. Just put your setUp class in the @Before not @BeforeClass. It might be run a bunch, but it's cheap.

Secondly, the way you have it right now is the correct way to get a mock to return something different depending on the test.

Multiple file upload in php

$property_images = $_FILES['property_images']['name'];
    if(!empty($property_images))
    {
        for($up=0;$up<count($property_images);$up++)
        {
            move_uploaded_file($_FILES['property_images']['tmp_name'][$up],'../images/property_images/'.$_FILES['property_images']['name'][$up]);
        }
    }

How to extract a string between two delimiters

Try as

String s = "ABC[ This is to extract ]";
        Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
        Matcher m = p.matcher(s);
        m.find();
        String text = m.group(1);
        System.out.println(text);

How do I go about adding an image into a java project with eclipse?

You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol

How to change the URI (URL) for a remote Git repository?

Change remote git URI to [email protected] rather than https://github.com

git remote set-url origin [email protected]:<username>/<repo>.git

Example:

git remote set-url origin [email protected]:Chetabahana/my_repo_name.git

The benefit is that you may do git push automatically when you use ssh-agent :

#!/bin/bash

# Check ssh connection
ssh-add -l &>/dev/null
[[ "$?" == 2 ]] && eval `ssh-agent`
ssh-add -l &>/dev/null
[[ "$?" == 1 ]] && expect $HOME/.ssh/agent

# Send git commands to push
git add . && git commit -m "your commit" && git push -u origin master

Put a script file $HOME/.ssh/agent to let it runs ssh-add using expect as below:

#!/usr/bin/expect -f
set HOME $env(HOME)
spawn ssh-add $HOME/.ssh/id_rsa
expect "Enter passphrase for $HOME/.ssh/id_rsa:"
send "<my_passphrase>\n";
expect "Identity added: $HOME/.ssh/id_rsa ($HOME/.ssh/id_rsa)"
interact

Angularjs simple file download causes router to redirect

If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.

I hope it, will be helpfull.

HTML :

<a href="#" class="btn btn-default" file-name="'fileName.extension'"  ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>

DIRECTIVE :

directive('fileDownload',function(){
    return{
        restrict:'A',
        scope:{
            fileDownload:'=',
            fileName:'=',
        },

        link:function(scope,elem,atrs){


            scope.$watch('fileDownload',function(newValue, oldValue){

                if(newValue!=undefined && newValue!=null){
                    console.debug('Downloading a new file'); 
                    var isFirefox = typeof InstallTrigger !== 'undefined';
                    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;
                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                    var isBlink = (isChrome || isOpera) && !!window.CSS;

                    if(isFirefox || isIE || isChrome){
                        if(isChrome){
                            console.log('Manage Google Chrome download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var downloadLink = angular.element('<a></a>');//create a new  <a> tag element
                            downloadLink.attr('href',fileURL);
                            downloadLink.attr('download',scope.fileName);
                            downloadLink.attr('target','_self');
                            downloadLink[0].click();//call click function
                            url.revokeObjectURL(fileURL);//revoke the object from URL
                        }
                        if(isIE){
                            console.log('Manage IE download>10');
                            window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName); 
                        }
                        if(isFirefox){
                            console.log('Manage Mozilla Firefox download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var a=elem[0];//recover the <a> tag from directive
                            a.href=fileURL;
                            a.download=scope.fileName;
                            a.target='_self';
                            a.click();//we call click function
                        }


                    }else{
                        alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
                    }
                }
            });

        }
    }
})

IN CONTROLLER:

$scope.myBlobObject=undefined;
$scope.getFile=function(){
        console.log('download started, you can show a wating animation');
        serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
        .then(function(data){//is important that the data was returned as Aray Buffer
                console.log('Stream download complete, stop animation!');
                $scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        },function(fail){
                console.log('Download Error, stop animation and show error message');
                                    $scope.myBlobObject=[];
                                });
                            }; 

IN SERVICE:

function getStream(params){
                 console.log("RUNNING");
                 var deferred = $q.defer();

                 $http({
                     url:'../downloadURL/',
                     method:"PUT",//you can use also GET or POST
                     data:params,
                     headers:{'Content-type': 'application/json'},
                     responseType : 'arraybuffer',//THIS IS IMPORTANT
                    })
                    .success(function (data) {
                        console.debug("SUCCESS");
                        deferred.resolve(data);
                    }).error(function (data) {
                         console.error("ERROR");
                         deferred.reject(data);
                    });

                 return deferred.promise;
                };

BACKEND(on SPRING):

@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
        @RequestBody Map<String,String> spParams
        ) throws IOException {
        OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}

ERROR 2006 (HY000): MySQL server has gone away

If it's reconnecting and getting connection ID 2, the server has almost definitely just crashed.

Contact the server admin and get them to diagnose the problem. No non-malicious SQL should crash the server, and the output of mysqldump certainly should not.

It is probably the case that the server admin has made some big operational error such as assigning buffer sizes of greater than the architecture's address-space limits, or more than virtual memory capacity. The MySQL error-log will probably have some relevant information; they will be monitoring this if they are competent anyway.

How to vertically align text inside a flexbox?

Set the display in li as flex and set align-items to center.

li {
  display: flex;

  /* Align items vertically */
  align-items: center;

  /* Align items horizontally */
  justify-content: center;

}

I, personally, would also target pseudo elements and use border-box (Universal selector * and pseudo elements)

*,
*::before,
*::after {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
  

Remove characters from a string

I know this is old but if you do a split then join it will remove all occurrences of a particular character ie:

var str = theText.split('A').join('')

will remove all occurrences of 'A' from the string, obviously it's not case sensitive

How do I convert a org.w3c.dom.Document object to a String?

If you are ok to do transformation, you may try this.

DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());

NPM: npm-cli.js not found when running npm

On Windows 10:

  1. Press windows key, type edit the system environment variables then enter.
  2. Click environment variables...
  3. On the lower half of the window that opened with title Environment Variables there you will see a table titled System Variables, with two columns, the first one titled variable.
  4. Find the row with variable Path and click it.
  5. Click edit which will open a window titled Edit evironment variable.
  6. Here if you find

C:\Program Files\nodejs\node_modules\npm\bin

select it, and click edit button to your right, then edit the field to the path where you have the nodejs folder, in my case it was just shortening it to :

C:\Program Files\nodejs

Then I closed all my cmd or powershell terminals, opened them again and npm was working.

fast way to copy formatting in excel

Does:

Set Sheets("Output").Range("$A$1:$A$500") =  Sheets(sheet_).Range("$A$1:$A$500")

...work? (I don't have Excel in front of me, so can't test.)

Laravel Eloquent: How to get only certain columns from joined tables

For Laravel >= 5.2

Use the ->pluck() method

$roles = DB::table('roles')->pluck('title');

If you would like to retrieve an array containing the values of a single column, you may use the pluck method


For Laravel <= 5.1

Use the ->lists() method

$roles = DB::table('roles')->lists('title');

This method will return an array of role titles. You may also specify a custom key column for the returned array:

How to set viewport meta for iPhone that handles rotation properly?

I had this issue myself, and I wanted to both be able to set the width, and have it update on rotate and allow the user to scale and zoom the page (the current answer provides the first but prevents the later as a side-effect).. so I came up with a fix that keeps the view width correct for the orientation, but still allows for zooming, though it is not super straight forward.

First, add the following Javascript to the webpage you are displaying:

 <script type='text/javascript'>
 function setViewPortWidth(width) {
  var metatags = document.getElementsByTagName('meta');
  for(cnt = 0; cnt < metatags.length; cnt++) { 
   var element = metatags[cnt];
   if(element.getAttribute('name') == 'viewport') {

    element.setAttribute('content','width = '+width+'; maximum-scale = 5; user-scalable = yes');
    document.body.style['max-width'] = width+'px';
   }
  }
 }
 </script>

Then in your - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation method, add:

float availableWidth = [EmailVC webViewWidth];
NSString *stringJS;

stringJS = [NSString stringWithFormat:@"document.body.offsetWidth"];
float documentWidth = [[_webView stringByEvaluatingJavaScriptFromString:stringJS] floatValue];

if(documentWidth > availableWidth) return; // Don't perform if the document width is larger then available (allow auto-scale)

// Function setViewPortWidth defined in EmailBodyProtocolHandler prepend
stringJS = [NSString stringWithFormat:@"setViewPortWidth(%f);",availableWidth];
[_webView stringByEvaluatingJavaScriptFromString:stringJS];

Additional Tweaking can be done by modifying more of the viewportal content settings:

http://www.htmlgoodies.com/beyond/webmaster/toolbox/article.php/3889591/Detect-and-Set-the-iPhone--iPads-Viewport-Orientation-Using-JavaScript-CSS-and-Meta-Tags.htm

Also, I understand you can put a JS listener for onresize or something like to trigger the rescaling, but this worked for me as I'm doing it from Cocoa Touch UI frameworks.

Hope this helps someone :)

Curl error: Operation timed out

I got same problem lot of time. Check your request url, if you are requesting on local server like 127.1.1/api or 192.168...., try to change it, make sure you are hitting cloud.

XPath to select multiple tags

Not sure if this helps, but with XSL, I'd do something like:

<xsl:for-each select="a/b">
    <xsl:value-of select="c"/>
    <xsl:value-of select="d"/>
    <xsl:value-of select="e"/>
</xsl:for-each>

and won't this XPath select all children of B nodes:

a/b/*

Go doing a GET request and building the Querystring

Use r.URL.Query() when you appending to existing query, if you are building new set of params use the url.Values struct like so

package main

import (
    "fmt"
    "log"
    "net/http"
    "net/url"
    "os"
)

func main() {
    req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
    if err != nil {
        log.Print(err)
        os.Exit(1)
    }

    // if you appending to existing query this works fine 
    q := req.URL.Query()
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")

    // or you can create new url.Values struct and encode that like so
    q := url.Values{}
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")

    req.URL.RawQuery = q.Encode()

    fmt.Println(req.URL.String())
    // Output:
    // http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}

Collections sort(List<T>,Comparator<? super T>) method example

You probably want something like this:

Collections.sort(students, new Comparator<Student>() {
                     public int compare(Student s1, Student s2) {
                           if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
                               return s1.getName().compareTo(s2.getName());
                           } else {
                             return s1.getAge().compareTo(s2.getAge());
                          }
                      }
);

This sorts the students first by name. If a name is missing, or two students have the same name, they are sorted by their age.

How do I declare a namespace in JavaScript?

I use this approach:

var myNamespace = {}
myNamespace._construct = function()
{
    var staticVariable = "This is available to all functions created here"

    function MyClass()
    {
       // Depending on the class, we may build all the classes here
       this.publicMethod = function()
       {
          //Do stuff
       }
    }

    // Alternatively, we may use a prototype.
    MyClass.prototype.altPublicMethod = function()
    {
        //Do stuff
    }

    function privateStuff()
    {
    }

    function publicStuff()
    {
       // Code that may call other public and private functions
    }

    // List of things to place publically
    this.publicStuff = publicStuff
    this.MyClass = MyClass
}
myNamespace._construct()

// The following may or may not be in another file
myNamespace.subName = {}
myNamespace.subName._construct = function()
{
   // Build namespace
}
myNamespace.subName._construct()

External code can then be:

var myClass = new myNamespace.MyClass();
var myOtherClass = new myNamepace.subName.SomeOtherClass();
myNamespace.subName.publicOtherStuff(someParameter);

Constants in Kotlin -- what's a recommended way to create them?

For primitives and Strings:

/** The empty String. */
const val EMPTY_STRING = ""

For other cases:

/** The empty array of Strings. */
@JvmField val EMPTY_STRING_ARRAY = arrayOfNulls<String>(0)

Example:

/*
 * Copyright 2018 Vorlonsoft LLC
 *
 * Licensed under The MIT License (MIT)
 */

package com.vorlonsoft.android.rate

import com.vorlonsoft.android.rate.Constants.Utils.Companion.UTILITY_CLASS_MESSAGE

/**
 * Constants Class - the constants class of the AndroidRate library.
 *
 * @constructor Constants is a utility class and it can't be instantiated.
 * @since       1.1.8
 * @version     1.2.1
 * @author      Alexander Savin
 */
internal class Constants private constructor() {
    /** Constants Class initializer block. */
    init {
        throw UnsupportedOperationException("Constants$UTILITY_CLASS_MESSAGE")
    }

    /**
     * Constants.Date Class - the date constants class of the AndroidRate library.
     *
     * @constructor Constants.Date is a utility class and it can't be instantiated.
     * @since       1.1.8
     * @version     1.2.1
     * @author      Alexander Savin
     */
    internal class Date private constructor() {
        /** Constants.Date Class initializer block. */
        init {
            throw UnsupportedOperationException("Constants.Date$UTILITY_CLASS_MESSAGE")
        }

        /** The singleton contains date constants. */
        companion object {
            /** The time unit representing one year in days. */
            const val YEAR_IN_DAYS = 365.toShort()
        }
    }

    /**
     * Constants.Utils Class - the utils constants class of the AndroidRate library.
     *
     * @constructor Constants.Utils is a utility class and it can't be instantiated.
     * @since       1.1.8
     * @version     1.2.1
     * @author      Alexander Savin
     */
    internal class Utils private constructor() {
        /** Constants.Utils Class initializer block. */
        init {
            throw UnsupportedOperationException("Constants.Utils$UTILITY_CLASS_MESSAGE")
        }

        /** The singleton contains utils constants. */
        companion object {
            /** The empty String. */
            const val EMPTY_STRING = ""
            /** The empty array of Strings. */
            @JvmField val EMPTY_STRING_ARRAY = arrayOfNulls<String>(0)
            /** The part 2 of a utility class unsupported operation exception message. */
            const val UTILITY_CLASS_MESSAGE = " is a utility class and it can't be instantiated!"
        }
    }
}

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

This worked for me.

   /**
     * return date in specific format, given a timestamp.
     *
     * @param  timestamp  $datetime
     * @return string
     */
    public static function showDateString($timestamp)
    {
      if ($timestamp !== NULL) {
        $date = new DateTime();
        $date->setTimestamp(intval($timestamp));
        return $date->format("d-m-Y");
      }
      return '';
    }

JAVA_HOME directory in Linux

On Linux you can run $(dirname $(dirname $(readlink -f $(which javac))))

On Mac you can run $(dirname $(readlink $(which javac)))/java_home

I'm not sure about windows but I imagine where javac would get you pretty close

Google Maps API 3 - Custom marker color for default (dot) marker

You can use this code it works fine.

 var pinImage = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/009900/");<br>

 var marker = new google.maps.Marker({
            position: yourlatlong,
            icon: pinImage,
            map: map
        });

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Another approach is to use @ExceptionHandler with @ControllerAdvice to centralize all your handlers in the same class, if not you must put the handler methods in every controller you want to manage an exception.

Your handler class:

@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(MyBadRequestException.class)
  public ResponseEntity<MyError> handleException(MyBadRequestException e) {
    return ResponseEntity
        .badRequest()
        .body(new MyError(HttpStatus.BAD_REQUEST, e.getDescription()));
  }
}

Your custom exception:

public class MyBadRequestException extends RuntimeException {

  private String description;

  public MyBadRequestException(String description) {
    this.description = description;
  }

  public String getDescription() {
    return this.description;
  }
}

Now you can throw exceptions from any of your controllers, and you can define other handlers inside you advice class.

Convert string to integer type in Go?

Try this

import ("strconv")

value := "123"
number,err := strconv.ParseUint(value, 10, 32)
finalIntNum := int(number) //Convert uint64 To int

Create controller for partial view in ASP.NET MVC

The most important thing is, the action created must return partial view, see below.

public ActionResult _YourPartialViewSection()
{
    return PartialView();
}

Python: How to create a unique file name?

In case you need short unique IDs as your filename, try shortuuid, shortuuid uses lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.

>>> import shortuuid
>>> shortuuid.uuid()
'Tw8VgM47kSS5iX2m8NExNa'
>>> len(ui)
22

compared to

>>> import uuid
>>> unique_filename = str(uuid.uuid4())
>>> len(unique_filename)
36
>>> unique_filename
'2d303ad1-79a1-4c1a-81f3-beea761b5fdf'

Resize on div element

// this is a Jquery plugin function that fires an event when the size of an element is changed
// usage: $().sizeChanged(function(){})

(function ($) {

$.fn.sizeChanged = function (handleFunction) {
    var element = this;
    var lastWidth = element.width();
    var lastHeight = element.height();

    setInterval(function () {
        if (lastWidth === element.width()&&lastHeight === element.height())
            return;
        if (typeof (handleFunction) == 'function') {
            handleFunction({ width: lastWidth, height: lastHeight },
                           { width: element.width(), height: element.height() });
            lastWidth = element.width();
            lastHeight = element.height();
        }
    }, 100);


    return element;
};

}(jQuery));

Android, How to limit width of TextView (and add three dots at the end of text)?

        <TextView
            android:id="@+id/product_description"
            android:layout_width="165dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:paddingLeft="12dp"
            android:paddingRight="12dp"
            android:text="Pack of 4 summer printed pajama"
            android:textColor="#d2131c"
            android:textSize="12sp"
            android:maxLines="2"
            android:ellipsize="end"/>

How to tell which commit a tag points to in Git?

Use

git rev-parse --verify <tag>^{commit}

(which would return SHA-1 of a commit even for annotated tag).


git show-ref <tag> would also work if <tag> is not annotated. And there is always git for-each-ref (see documentation for details).

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

Table row and column number in jQuery

You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number:

$('td').click(function(){
  var col = $(this).parent().children().index($(this));
  var row = $(this).parent().parent().children().index($(this).parent());
  alert('Row: ' + row + ', Column: ' + col);
});

Check a running example here.

How to print the contents of RDD?

In python

   linesWithSessionIdCollect = linesWithSessionId.collect()
   linesWithSessionIdCollect

This will printout all the contents of the RDD

CSS Calc Viewport Units Workaround?

Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.

Example here: https://codesandbox.io/s/21r4z95p7j

You can even utilize the bottom gutter space if you so choose, simply by adding another "item".

Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  background-color: #334;_x000D_
  color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  min-height: 100vh;_x000D_
  min-width: 100vw;_x000D_
  display: grid;_x000D_
  grid-template-columns: 100%;_x000D_
  grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  background-color: #558;_x000D_
  padding: 2px;_x000D_
  margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
  background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Parcel Sandbox</title>_x000D_
    <meta charset="UTF-8" />_x000D_
    <link rel="stylesheet" href="src/index.css" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="app">_x000D_
      <div class="main">_x000D_
        <div class="item">Item 1</div>_x000D_
        <!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
      </div>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Using a batch to copy from network drive to C: or D: drive

This might be due to a security check. This thread might help you.

There are two suggestions: one with pushd and one with a registry change. I'd suggest to use the first one...

Authenticate Jenkins CI for Github private repository

One thing that got this working for me is to make sure that github.com is in ~jenkins/.ssh/known_hosts.

How can I change UIButton title color?

Solution in Swift 3:

button.setTitleColor(UIColor.red, for: .normal)

This will set the title color of button.

Warning: Cannot modify header information - headers already sent by ERROR

You are trying to send headers information after outputing content.

If you want to do this, look for output buffering.

Therefore, look to use ob_start();

Using RegEx in SQL Server

A similar approach to @mwigdahl's answer, you can also implement a .NET CLR in C#, with code such as;

using System.Data.SqlTypes;
using RX = System.Text.RegularExpressions;

public partial class UserDefinedFunctions
{
 [Microsoft.SqlServer.Server.SqlFunction]
 public static SqlString Regex(string input, string regex)
 {
  var match = RX.Regex.Match(input, regex).Groups[1].Value;
  return new SqlString (match);
 }
}

Installation instructions can be found here

Difference between VARCHAR and TEXT in MySQL

TL;DR

TEXT

  • fixed max size of 65535 characters (you cannot limit the max size)
  • takes 2 + c bytes of disk space, where c is the length of the stored string.
  • cannot be (fully) part of an index. One would need to specify a prefix length.

VARCHAR(M)

  • variable max size of M characters
  • M needs to be between 1 and 65535
  • takes 1 + c bytes (for M ≤ 255) or 2 + c (for 256 ≤ M ≤ 65535) bytes of disk space where c is the length of the stored string
  • can be part of an index

More Details

TEXT has a fixed max size of 2¹6-1 = 65535 characters.
VARCHAR has a variable max size M up to M = 2¹6-1.
So you cannot choose the size of TEXT but you can for a VARCHAR.

The other difference is, that you cannot put an index (except for a fulltext index) on a TEXT column.
So if you want to have an index on the column, you have to use VARCHAR. But notice that the length of an index is also limited, so if your VARCHAR column is too long you have to use only the first few characters of the VARCHAR column in your index (See the documentation for CREATE INDEX).

But you also want to use VARCHAR, if you know that the maximum length of the possible input string is only M, e.g. a phone number or a name or something like this. Then you can use VARCHAR(30) instead of TINYTEXT or TEXT and if someone tries to save the text of all three "Lord of the Ring" books in your phone number column you only store the first 30 characters :)

Edit: If the text you want to store in the database is longer than 65535 characters, you have to choose MEDIUMTEXT or LONGTEXT, but be careful: MEDIUMTEXT stores strings up to 16 MB, LONGTEXT up to 4 GB. If you use LONGTEXT and get the data via PHP (at least if you use mysqli without store_result), you maybe get a memory allocation error, because PHP tries to allocate 4 GB of memory to be sure the whole string can be buffered. This maybe also happens in other languages than PHP.

However, you should always check the input (Is it too long? Does it contain strange code?) before storing it in the database.

Notice: For both types, the required disk space depends only on the length of the stored string and not on the maximum length.
E.g. if you use the charset latin1 and store the text "Test" in VARCHAR(30), VARCHAR(100) and TINYTEXT, it always requires 5 bytes (1 byte to store the length of the string and 1 byte for each character). If you store the same text in a VARCHAR(2000) or a TEXT column, it would also require the same space, but, in this case, it would be 6 bytes (2 bytes to store the string length and 1 byte for each character).

For more information have a look at the documentation.

Finally, I want to add a notice, that both, TEXT and VARCHAR are variable length data types, and so they most likely minimize the space you need to store the data. But this comes with a trade-off for performance. If you need better performance, you have to use a fixed length type like CHAR. You can read more about this here.

Insert a row to pandas dataframe

I put together a short function that allows for a little more flexibility when inserting a row:

def insert_row(idx, df, df_insert):
    dfA = df.iloc[:idx, ]
    dfB = df.iloc[idx:, ]

    df = dfA.append(df_insert).append(dfB).reset_index(drop = True)

    return df

which could be further shortened to:

def insert_row(idx, df, df_insert):
    return df.iloc[:idx, ].append(df_insert).append(df.iloc[idx:, ]).reset_index(drop = True)

Then you could use something like:

df = insert_row(2, df, df_new)

where 2 is the index position in df where you want to insert df_new.

See line breaks and carriage returns in editor

Just to clarify why :set list won't show CR's as ^M without e ++ff=unix and why :set list has nothing to do with ^M's.

Internally when Vim reads a file into its buffer, it replaces all line-ending characters with its own representation (let's call it $'s). To determine what characters should be removed, it firstly detects in what format line endings are stored in a file. If there are only CRLF '\r\n' or only CR '\r' or only LF '\n' line-ending characters, then the 'fileformat' is set to dos, mac and unix respectively.

When list option is set, Vim displays $ character when the line break occurred no matter what fileformat option has been detected. It uses its own internal representation of line-breaks and that's what it displays.

Now when you write buffer to the disc, Vim inserts line-ending characters according to what fileformat options has been detected, essentially converting all those internal $'s with appropriate characters. If the fileformat happened to be unix then it will simply write \n in place of its internal line-break.

The trick is to force Vim to read a dos encoded file as unix one. The net effect is that it will remove all \n's leaving \r's untouched and display them as ^M's in your buffer. Setting :set list will additionally show internal line-endings as $. After all, you see ^M$ in place of dos encoded line-breaks.

Also notice that :set list has nothing to do with showing ^M's. You can check it by yourself (make sure you have disabled list option first) by inserting single CR using CTRL-V followed by Enter in insert mode. After writing buffer to disc and opening it again you will see ^M despite list option being set to 0.

You can find more about file formats on http://vim.wikia.com/wiki/File_format or by typing:help 'fileformat' in Vim.

Does java.util.List.isEmpty() check if the list itself is null?

You're trying to call the isEmpty() method on a null reference (as List test = null; ). This will surely throw a NullPointerException. You should do if(test!=null) instead (Checking for null first).

The method isEmpty() returns true, if an ArrayList object contains no elements; false otherwise (for that the List must first be instantiated that is in your case is null).

Edit:

You may want to see this question.

Where can I find a list of escape characters required for my JSON ajax return type?

Here is a list of special characters that you can escape when creating a string literal for JSON:

\b  Backspace (ASCII code 08)
\f  Form feed (ASCII code 0C)
\n  New line
\r  Carriage return
\t  Tab
\v  Vertical tab
\'  Apostrophe or single quote
\"  Double quote
\\  Backslash character

Reference: String literals

Some of these are more optional than others. For instance, your string should be perfectly valid whether you escape the tab character or leave in a tab literal. You should certainly be handling the backslash and quote characters, though.

Javascript find json value

var obj = [
  {"name": "Afghanistan", "code": "AF"}, 
  {"name": "Åland Islands", "code": "AX"}, 
  {"name": "Albania", "code": "AL"}, 
  {"name": "Algeria", "code": "DZ"}
];

// the code you're looking for
var needle = 'AL';

// iterate over each element in the array
for (var i = 0; i < obj.length; i++){
  // look for the entry with a matching `code` value
  if (obj[i].code == needle){
     // we found it
    // obj[i].name is the matched result
  }
}

"elseif" syntax in JavaScript

You are missing a space between else and if

It should be else if instead of elseif

if(condition)
{

} 
else if(condition)
{

}
else
{

}

How to calculate number of days between two dates

Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.

Hibernate error - QuerySyntaxException: users is not mapped [from users]

I recommend this pattern:

@Entity(name = User.PERSISTANCE_NAME)
@Table(name = User.PERSISTANCE_NAME )
public class User {    
    static final String PERSISTANCE_NAME = "USER";

    // Column definitions here

}

How does Go update third-party packages?

Go to path and type

go get -u ./..

It will update all require packages.

string sanitizer for filename

one way

$bad='/[\/:*?"<>|]/';
$string = 'fi?le*';

function sanitize($str,$pat)
{
    return preg_replace($pat,"",$str);

}
echo sanitize($string,$bad);

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
{
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);
}

Then you enumerate all stored credentials by calling

VaultEnumerateVaults

Then you go over the results.

SyntaxError: unexpected EOF while parsing

You're missing a closing parenthesis ) in print():

print('{0}+{1}={2}'.format(n1,n2,t1))

and you're also not storing the returned value from int(), so z is still a string.

z = input('?')
z = int(z)

or simply:

z = int(input('?'))

MVC 3 file upload and model binding

For multiple files; note the newer "multiple" attribute for input:

Form:

@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    <label for="files">Filename:</label>
    <input type="file" name="files" multiple="true" id="files" />
    <input type="submit"  />
}

Controller:

[HttpPost]
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files)
{
    return View();
}

Bash integer comparison

Easier solution;

#/bin/bash
if (( ${1:-2} >= 2 )); then
    echo "First parameter must be 0 or 1"
fi
# rest of script...

Output

$ ./test 
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1

Explanation

  • (( )) - Evaluates the expression using integers.
  • ${1:-2} - Uses parameter expansion to set a value of 2 if undefined.
  • >= 2 - True if the integer is greater than or equal to two 2.

Bold words in a string of strings.xml in Android

As David Olsson has said, you can use HTML in your string resources:

<resource>
    <string name="my_string">A string with <i>actual</i> <b>formatting</b>!</string>
</resources>

Then if you use getText(R.string.my_string) rather than getString(R.string.my_string) you get back a CharSequence rather than a String that contains the formatting embedded.

CORS with spring-boot and angularjs not working

This is what worked for me.

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors();
    }

}

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
            .addMapping("/**")
            .allowedMethods("*")
            .allowedHeaders("*")
            .allowedOrigins("*")
            .allowCredentials(true);
    }

}

How to compare 2 dataTables

How about merging 2 data tables and then comparing the changes? Not sure if that will fill 100% of your needs but for the quick compare it will do a job.

public DataTable GetTwoDataTablesChanges(DataTable firstDataTable, DataTable secondDataTable)
{ 
     firstDataTable.Merge(secondDataTable);
     return secondDataTable.GetChanges();
}

You can read more about DataTable.Merge()

here

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

I ran this in the command prompt(have windows 7 os): JAVA_HOME=C:\Program Files\Android\Android Studio\jre

where what its = to is the path to that jre folder, so anyone's can be different.

OWIN Startup Class Missing

My case? I had startup file, but it is excluded in the project. I just included it and the error left.

Error : ORA-01704: string literal too long

Try to split the characters into multiple chunks like the query below and try:

Insert into table (clob_column) values ( to_clob( 'chunk 1' ) || to_clob( 'chunk 2' ) );

It worked for me.

Split string in Lua?

A lot of these answers only accept single-character separators, or don't deal with edge cases well (e.g. empty separators), so I thought I would provide a more definitive solution.

Here are two functions, gsplit and split, adapted from the code in the Scribunto MediaWiki extension, which is used on wikis like Wikipedia. The code is licenced under the GPL v2. I have changed the variable names and added comments to make the code a bit easier to understand, and I have also changed the code to use regular Lua string patterns instead of Scribunto's patterns for Unicode strings. The original code has test cases here.

-- gsplit: iterate over substrings in a string separated by a pattern
-- 
-- Parameters:
-- text (string)    - the string to iterate over
-- pattern (string) - the separator pattern
-- plain (boolean)  - if true (or truthy), pattern is interpreted as a plain
--                    string, not a Lua pattern
-- 
-- Returns: iterator
--
-- Usage:
-- for substr in gsplit(text, pattern, plain) do
--   doSomething(substr)
-- end
local function gsplit(text, pattern, plain)
  local splitStart, length = 1, #text
  return function ()
    if splitStart then
      local sepStart, sepEnd = string.find(text, pattern, splitStart, plain)
      local ret
      if not sepStart then
        ret = string.sub(text, splitStart)
        splitStart = nil
      elseif sepEnd < sepStart then
        -- Empty separator!
        ret = string.sub(text, splitStart, sepStart)
        if sepStart < length then
          splitStart = sepStart + 1
        else
          splitStart = nil
        end
      else
        ret = sepStart > splitStart and string.sub(text, splitStart, sepStart - 1) or ''
        splitStart = sepEnd + 1
      end
      return ret
    end
  end
end

-- split: split a string into substrings separated by a pattern.
-- 
-- Parameters:
-- text (string)    - the string to iterate over
-- pattern (string) - the separator pattern
-- plain (boolean)  - if true (or truthy), pattern is interpreted as a plain
--                    string, not a Lua pattern
-- 
-- Returns: table (a sequence table containing the substrings)
local function split(text, pattern, plain)
  local ret = {}
  for match in gsplit(text, pattern, plain) do
    table.insert(ret, match)
  end
  return ret
end

Some examples of the split function in use:

local function printSequence(t)
  print(unpack(t))
end

printSequence(split('foo, bar,baz', ',%s*'))       -- foo     bar     baz
printSequence(split('foo, bar,baz', ',%s*', true)) -- foo, bar,baz
printSequence(split('foo', ''))                    -- f       o       o

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.

css transition opacity fade background

It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.

If you want to fade to black(ish), you'll need a black container around the image. Something like:

.ctr {
    margin: 0; 
    padding: 0;
    background-color: black;
    display: inline-block;
}

and

<div class="ctr"><img ... /></div>

Error "can't use subversion command line client : svn" when opening android project checked out from svn

Under Linux, got same problem after Android Studio update (and several months without using it...).

I solved it by running the following command in a console:

mv .subversion/ .subversion.bak

I prefer that command to rm -R .subversion since it left me a rollback option.

wildcard * in CSS for classes

Yes you can do this.

*[id^='term-']{
    [css here]
}

This will select all ids that start with 'term-'.

As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.

How do I get the day month and year from a Windows cmd.exe script?

For one line!


Try using for wmic OS Get localdatetime^|find "." in for /f without tokens and/or delims, this works in any language / region and also, no user settings interfere with the layout of the output.

  • In command line:
for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo= year: !_date:~0,4!&&echo=month:   !_date:~4,2!&echo=  day:   !_date:~6,2!"

  • In bat/cmd file:
for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo= year: !_date:~0,4!&&echo=month:   !_date:~4,2!&echo=  day:   !_date:~6,2!"

Results:


 year: 2019
month:   06
  day:   12

  • With Hour and Minute in bat/cmd file:
for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo=  year: !_date:~0,4!&&echo= month:   !_date:~4,2!&echo=   day:   !_date:~6,2!&echo=  hour:   !_date:~8,2!&echo=minute:   !_date:~10,2!"

  • With Hour and Minute in command line:
for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo=  year: !_date:~0,4!&&echo= month:   !_date:~4,2!&echo=   day:   !_date:~6,2!&echo=  hour:   !_date:~8,2!&echo=minute:   !_date:~10,2!"

Results:


  year: 2020
 month:   05
   day:   16
  hour:   00
minute:   46

Why does python use 'else' after for and while loops?

Here's another idiomatic use case besides searching. Let's say you wanted to wait for a condition to be true, e.g. a port to be open on a remote server, along with some timeout. Then you could utilize a while...else construct like so:

import socket
import time

sock = socket.socket()
timeout = time.time() + 15
while time.time() < timeout:
    if sock.connect_ex(('127.0.0.1', 80)) is 0:
        print('Port is open now!')
        break
    print('Still waiting...')
else:
    raise TimeoutError()

Getting String value from enum in Java

if status is of type Status enum, status.name() will give you its defined name.

Correct way of using log4net (logger naming)

Regarding how you log messages within code, I would opt for the second approach:

ILog log = LogManager.GetLogger(typeof(Bar));
log.Info("message");

Where messages sent to the log above will be 'named' using the fully-qualifed type Bar, e.g.

MyNamespace.Foo.Bar [INFO] message

The advantage of this approach is that it is the de-facto standard for organising logging, it also allows you to filter your log messages by namespace. For example, you can specify that you want to log INFO level message, but raise the logging level for Bar specifically to DEBUG:

<log4net>
    <!-- appenders go here -->
    <root>
        <level value="INFO" />
        <appender-ref ref="myLogAppender" />
    </root>

    <logger name="MyNamespace.Foo.Bar">
        <level value="DEBUG" />
    </logger>
</log4net>

The ability to filter your logging via name is a powerful feature of log4net, if you simply log all your messages to "myLog", you loose much of this power!

Regarding the EPiServer CMS, you should be able to use the above approach to specify a different logging level for the CMS and your own code.

For further reading, here is a codeproject article I wrote on logging:

Eclipse fonts and background color

You can install eclipse theme plugin then select default. Please visit here: http://eclipsecolorthemes.org/?view=plugin

What is the best way to initialize a JavaScript Date to midnight?

A one-liner for object configs:

new Date(new Date().setHours(0,0,0,0));

When creating an element:

dateFieldConfig = {
      name: "mydate",
      value: new Date(new Date().setHours(0, 0, 0, 0)),
}

How to convert php array to utf8?

There is an easy way

array_walk_recursive(
  $array,
  function (&$entry) {
    $entry = mb_convert_encoding(
        $entry,
        'UTF-8'
    );
  }
);

Visual Studio Code: format is not using indent settings

Also make sure your Workspace Settings aren't overriding your User Settings. The UI doesn't make it very obvious which settings you're editing and "File > Preferences > Settings" defaults to User Settings even though Workspace Settings trump User Settings.

enter image description here

You can also edit Workspace settings directly: /.vscode/settings.json

How to use clock() in C++

#include <iostream>
#include <ctime>
#include <cstdlib> //_sleep()  --- just a function that waits a certain amount of milliseconds

using namespace std;

int main()
{

    clock_t cl;     //initializing a clock type

    cl = clock();   //starting time of clock

    _sleep(5167);   //insert code here

    cl = clock() - cl;  //end point of clock

    _sleep(1000);   //testing to see if it actually stops at the end point

    cout << cl/(double)CLOCKS_PER_SEC << endl;  //prints the determined ticks per second (seconds passed)


    return 0;
}

//outputs "5.17"

Force a screen update in Excel VBA

Text boxes in worksheets are sometimes not updated when their text or formatting is changed, and even the DoEvent command does not help.

As there is no command in Excel to refresh a worksheet in the way a user form can be refreshed, it is necessary to use a trick to force Excel to update the screen.

The following commands seem to do the trick:

- ActiveSheet.Calculate    
- ActiveWindow.SmallScroll    
- Application.WindowState = Application.WindowState

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

Get a resource using getResource()

One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

Rails: update_attribute vs update_attributes

update_attribute and update_attributes are similar, but with one big difference: update_attribute does not run validations.

Also:

  • update_attribute is used to update record with single attribute.

    Model.update_attribute(:column_name, column_value1)
    
  • update_attributes is used to update record with multiple attributes.

    Model.update_attributes(:column_name1 => column_value1, :column_name2 => column_value2, ...)
    

These two methods are really easy to confuse given their similar names and works. Therefore, update_attribute is being removed in favor of update_column.

Now, in Rails4 you can use Model.update_column(:column_name, column_value) at the place of Model.update_attribute(:column_name, column_value)

Click here to get more info about update_column.

Android view pager with page indicator

I have also used the SimpleViewPagerIndicator from @JROD. It also crashes as described by @manuelJ.

According to his documentation:

SimpleViewPagerIndicator pageIndicator = (SimpleViewPagerIndicator) findViewById(R.id.page_indicator);
pageIndicator.setViewPager(pager);

Make sure you add this line as well:

pageIndicator.notifyDataSetChanged();

It crashes with an array out of bounds exception because the SimpleViewPagerIndicator is not getting instantiated properly and the items are empty. Calling the notifyDataSetChanged results in all the values being set properly or rather reset properly.

Git submodule head 'reference is not a tree' error

This answer is for users of SourceTree with limited terminal git experience.

Open the problematic submodule from within the Git project (super-project).

Fetch and ensure 'Fetch all tags' is checked.

Rebase pull your Git project.

This will solve the 'reference is not a tree' problem 9 out of ten times. That 1 time it won't, is a terminal fix as described by the top answer.

Page vs Window in WPF?

Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame

Windows are just normal WPF application Windows, but can host Pages via a Frame container

Git - deleted some files locally, how do I get them from a remote repository

git checkout filename

git reset --hard might do the trick as well

Difference between subprocess.Popen and os.system

If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace os.system() with subprocess.Popen():

sts = os.system("mycmd" + " myarg")

...does the same thing as...

sts = Popen("mycmd" + " myarg", shell=True).wait()

The "improved" code looks more complicated, but it's better because once you know subprocess.Popen(), you don't need anything else. subprocess.Popen() replaces several other tools (os.system() is just one of those) that were scattered throughout three other Python modules.

If it helps, think of subprocess.Popen() as a very flexible os.system().

jquery disable form submit on enter

Even shorter:

$('myform').submit(function() {
  return false;
});

Set the value of a variable with the result of a command in a Windows batch file

The only way I've seen it done is if you do this:

for /f "delims=" %a in ('ver') do @set foobar=%a

ver is the version command for Windows and on my system it produces:

Microsoft Windows [Version 6.0.6001]

Source

Gunicorn worker timeout error

Could it be this? http://docs.gunicorn.org/en/latest/settings.html#timeout

Other possibilities could be your response is taking too long or is stuck waiting.

Array Size (Length) in C#

yourArray.Length :)

Copy mysql database from remote server to local computer

Better yet use a oneliner:

Dump remoteDB to localDB:

mysqldump -uroot -pMypsw -h remoteHost remoteDB | mysql -u root -pMypsw localDB

Dump localDB to remoteDB:

mysqldump -uroot -pmyPsw localDB | mysql -uroot -pMypsw -h remoteHost remoteDB

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

To view your iOS device's console in Safari on your Mac (Mac only apparently):

  1. On your iOS device, go to Settings > Safari > Advanced and switch on Web Inspector
  2. On your iOS device, load your web page in Safari
  3. Connect your device directly to your Mac
  4. On your Mac, if you've not already got Safari's Developer menu activated, go to Preferences > Advanced, and select "Show Develop menu in menu bar"
  5. On your Mac, go to Develop > [your iOS device name] > [your web page]

Safari's Inspector will appear showing a console for your iOS device.

Stopword removal with NLTK

@alvas has a good answer. But again it depends on the nature of the task, for example in your application you want to consider all conjunction e.g. and, or, but, if, while and all determiner e.g. the, a, some, most, every, no as stop words considering all others parts of speech as legitimate, then you might want to look into this solution which use Part-of-Speech Tagset to discard words, Check table 5.1:

import nltk

STOP_TYPES = ['DET', 'CNJ']

text = "some data here "
tokens = nltk.pos_tag(nltk.word_tokenize(text))
good_words = [w for w, wtype in tokens if wtype not in STOP_TYPES]

Where do I call the BatchNormalization function in Keras?

Batch Normalization is used to normalize the input layer as well as hidden layers by adjusting mean and scaling of the activations. Because of this normalizing effect with additional layer in deep neural networks, the network can use higher learning rate without vanishing or exploding gradients. Furthermore, batch normalization regularizes the network such that it is easier to generalize, and it is thus unnecessary to use dropout to mitigate overfitting.

Right after calculating the linear function using say, the Dense() or Conv2D() in Keras, we use BatchNormalization() which calculates the linear function in a layer and then we add the non-linearity to the layer using Activation().

from keras.layers.normalization import BatchNormalization
model = Sequential()
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(64, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(2, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('softmax'))

sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, 
validation_split=0.2, verbose = 2)

How is Batch Normalization applied?

Suppose we have input a[l-1] to a layer l. Also we have weights W[l] and bias unit b[l] for the layer l. Let a[l] be the activation vector calculated(i.e. after adding the non-linearity) for the layer l and z[l] be the vector before adding non-linearity

  1. Using a[l-1] and W[l] we can calculate z[l] for the layer l
  2. Usually in feed-forward propagation we will add bias unit to the z[l] at this stage like this z[l]+b[l], but in Batch Normalization this step of addition of b[l] is not required and no b[l] parameter is used.
  3. Calculate z[l] means and subtract it from each element
  4. Divide (z[l] - mean) using standard deviation. Call it Z_temp[l]
  5. Now define new parameters ? and ß that will change the scale of the hidden layer as follows:

    z_norm[l] = ?.Z_temp[l] + ß

In this code excerpt, the Dense() takes the a[l-1], uses W[l] and calculates z[l]. Then the immediate BatchNormalization() will perform the above steps to give z_norm[l]. And then the immediate Activation() will calculate tanh(z_norm[l]) to give a[l] i.e.

a[l] = tanh(z_norm[l])

Update React component every second

@Waisky suggested:

You need to use setInterval to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:

If you'd like to do the same thing, using Hooks:

const [time, setTime] = useState(Date.now());

useEffect(() => {
  const interval = setInterval(() => setTime(Date.now()), 1000);
  return () => {
    clearInterval(interval);
  };
}, []);

Regarding the comments:

You don't need to pass anything inside []. If you pass time in the brackets, it means run the effect every time the value of time changes, i.e., it invokes a new setInterval every time, time changes, which is not what we're looking for. We want to only invoke setInterval once when the component gets mounted and then setInterval calls setTime(Date.now()) every 1000 seconds. Finally, we invoke clearInterval when the component is unmounted.

Note that the component gets updated, based on how you've used time in it, every time the value of time changes. That has nothing to do with putting time in [] of useEffect.

jquery ajax function not working

you need to prevent the default behavior of your form when submitting

by adding this:

$("#postcontent").on('submit' , function(e) {

  e.preventDefault();

  //then the rest of your code
}

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

Detect browser or tab closing

Sorry, I was not able to add a comment to one of existing answers, but in case you wanted to implement a kind of warning dialog, I just wanted to mention that any event handler function has an argument - event. In your case you can call event.preventDefault() to disallow leaving the page automatically, then issue your own dialog. I consider this a way better option than using standard ugly and insecure alert(). I personally implemented my own set of dialog boxes based on kendoWindow object (Telerik's Kendo UI, which is almost fully open-sourced, except of kendoGrid and kendoEditor). You can also use dialog boxes from jQuery UI. Please note though, that such things are asynchronous, and you will need to bind a handler to onclick event of every button, but this is all quite easy to implement.

However, I do agree that the lack of the real close event is terrible: if you, for instance, want to reset your session state at the back-end only on case of the real close, it's a problem.

How can I login to a website with Python?

import cookielib
import urllib
import urllib2

url = 'http://www.someserver.com/auth/login'
values = {'email-email' : '[email protected]',
          'password-clear' : 'Combination',
          'password-password' : 'mypassword' }

data = urllib.urlencode(values)
cookies = cookielib.CookieJar()

opener = urllib2.build_opener(
    urllib2.HTTPRedirectHandler(),
    urllib2.HTTPHandler(debuglevel=0),
    urllib2.HTTPSHandler(debuglevel=0),
    urllib2.HTTPCookieProcessor(cookies))

response = opener.open(url, data)
the_page = response.read()
http_headers = response.info()
# The login cookies should be contained in the cookies variable

For more information visit: https://docs.python.org/2/library/urllib2.html

Java SecurityException: signer information does not match

I was running JUNIT 5 and was also referencing Hamcrest external jar. But Hamcrest is also part of JUNIT 5 library. So, I have to change the order of external Hamecrest jar file up the JUNIT 5 library in build path.

enter image description here

converting a javascript string to a html object

In addition to Gaby aka's method, we can find elements inside htmlObject in this way -

htmlObj.find("#box").html();

Fiddle is available here - http://jsfiddle.net/ashwyn/76gL3/

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

Why do you want to enforce that only a single thread can access the DB at any one time?

It is the job of the database driver to implement any necessary locking, assuming a Connection is only used by one thread at a time!

Most likely, your database is perfectly capable of handling multiple, parallel access

How to display a jpg file in Python?

from PIL import Image

image = Image.open('File.jpg')
image.show()

Can I replace groups in Java regex?

Use $n (where n is a digit) to refer to captured subsequences in replaceFirst(...). I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group.

Pattern p = Pattern.compile("(\\d)(.*)(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
    // replace first number with "number" and second number with the first
    String output = m.replaceFirst("number $3$1");  // number 46
}

Consider (\D+) for the second group instead of (.*). * is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (\d) has nothing to match, before it can match to the final digit.

Python: Get the first character of the first string in a list?

You almost had it right. The simplest way is

mylist[0][0]   # get the first character from the first item in the list

but

mylist[0][:1]  # get up to the first character in the first item in the list

would also work.

You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.

How to parse a JSON string into JsonNode in Jackson?

A third variant:

ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readValue("{\"k1\":\"v1\"}", JsonNode.class);

Can you have multiple $(document).ready(function(){ ... }); sections?

I think the better way to go is to put switch to named functions (Check this overflow for more on that subject). That way you can call them from a single event.

Like so:

function firstFunction() {
    console.log("first");
}

function secondFunction() {
    console.log("second");
}


function thirdFunction() {
    console.log("third");
}

That way you can load them in a single ready function.

jQuery(document).on('ready', function(){
   firstFunction();
   secondFunction();
   thirdFunction();

});

This will output the following to your console.log:

first
second
third

This way you can reuse the functions for other events.

jQuery(window).on('resize',function(){
    secondFunction();
});

Check this fiddle for working version

Composer update memory limit

I am facing problems with composer because it consumes all the available memory, and then, the process get killed ( actualy, the output message is "Killed")

So, I was looking for a solution to limit composer memory usage.

I tried ( from @Sven answers )

$ php -d memory_limit=512M /usr/local/bin/composer update

But it didn't work because

"Composer internally increases the memory_limit to 1.5G."

-> Thats from composer oficial website.

Then I found a command that works :

$ COMPOSER_MEMORY_LIMIT=512M php composer.phar update

Althought, in my case 512mb is not enough !

Source : https://www.agileana.com/blog/composer-memory-limit-troubleshooting/

No output to console from a WPF application?

Old post, but I ran into this so if you're trying to output something to Output in a WPF project in Visual Studio, the contemporary method is:

Include this:

using System.Diagnostics;

And then:

Debug.WriteLine("something");

Oracle : how to subtract two dates and get minutes of the result

When you subtract two dates in Oracle, you get the number of days between the two values. So you just have to multiply to get the result in minutes instead:

SELECT (date2 - date1) * 24 * 60 AS minutesBetween
FROM ...

White space showing up on right side of page when background image should extend full length of page

I've also had the same issue ( Website body background rendering a right white margin in iPhone Safari ) and found that adding the background image to the <html> tag fixed the problem.

Before

body {background:url('images/back.jpg');}

After

html, body {background:url('images/back.jpg');}

map vs. hash_map in C++

They are implemented in very different ways.

hash_map (unordered_map in TR1 and Boost; use those instead) use a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key.

map is implemented as a balanced binary search tree (usually a red/black tree).

An unordered_map should give slightly better performance for accessing known elements of the collection, but a map will have additional useful characteristics (e.g. it is stored in sorted order, which allows traversal from start to finish). unordered_map will be faster on insert and delete than a map.

Setting a div's height in HTML with CSS

I gave up on strictly CSS and used a little jquery:

var leftcol = $("#leftcolumn");
var rightcol = $("#rightcolumn");
var leftcol_height = leftcol.height();
var rightcol_height = rightcol.height();

if (leftcol_height > rightcol_height)
    rightcol.height(leftcol_height);
else
    leftcol.height(rightcol_height);

Using JAXB to unmarshal/marshal a List<String>

@GET
@Path("/test2")
public Response test2(){
   List<String> list=new Vector<String>();
   list.add("a");
   list.add("b");

   final GenericEntity<List<String>> entity = new GenericEntity<List<String>>(list) { };
   return Response.ok().entity(entity).build();
}

gridview data export to excel in asp.net

Something else to check is make sure viewstate is on (I just solved this yesterday). If you don't have viewstate on, the gridview will be blank until you load it again.

.NET DateTime to SqlDateTime Conversion

If you are checking for DBNULL, converting a SQL Datetime to a .NET DateTime should not be a problem. However, you can run into problems converting a .NET DateTime to a valid SQL DateTime.

SQL Server does not recognize dates prior to 1/1/1753. Thats the year England adopted the Gregorian Calendar. Usually checking for DateTime.MinValue is sufficient, but if you suspect that the data could have years before the 18th century, you need to make another check or use a different data type. (I often wonder what Museums use in their databases)

Checking for max date is not really necessary, SQL Server and .NET DateTime both have a max date of 12/31/9999 It may be a valid business rule but it won't cause a problem.

How to break out of jQuery each Loop

According to the documentation return false; should do the job.

We can break the $.each() loop [..] by making the callback function return false.

Return false in the callback:

function callback(indexInArray, valueOfElement) {
  var booleanKeepGoing;

  this; // == valueOfElement (casted to Object)

  return booleanKeepGoing; // optional, unless false 
                           // and want to stop looping
}

BTW, continue works like this:

Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

How to pass credentials to httpwebrequest for accessing SharePoint Library

You could also use:

request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 

import android packages cannot be resolved

What all the others said.

Specifically, I recommend you go to Project > Properties > Java Build Path > Libraries and make sure you have exactly one copy of android.jar referenced. (Sometimes you can get two if you're importing a project.) And that its path is correct.

Sometimes you can get the system to resolve this for you by clicking a different target SDK in Project > Properties > Android, then restoring your original selection.

How to convert a Date to a formatted string in VB.net?

You can use the ToString overload. Have a look at this page for more info

So just Use myDate.ToString("yyyy-MM-dd HH:mm:ss")

or something equivalent

Global Variable in app.js accessible in routes?

My preferred way is to use circular dependencies*, which node supports

  • in app.js define var app = module.exports = express(); as your first order of business
  • Now any module required after the fact can var app = require('./app') to access it


app.js

var express   = require('express');
var app = module.exports = express(); //now app.js can be required to bring app into any file

//some app/middleware, config, setup, etc, including app.use(app.router)

require('./routes'); //module.exports must be defined before this line


routes/index.js

var app = require('./app');

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

//require in some other route files...each of which requires app independently
require('./user');
require('./blog');

Round double in two decimal places in C#?

I think all these answers are missing the question. The problem was to "Round UP", not just "Round". It is my understanding that Round Up means that ANY fractional value about a whole digit rounds up to the next WHOLE digit. ie: 48.0000000 = 48 but 25.00001 = 26. Is this not the definition of rounding up? (or have my past 60 years in accounting been misplaced?

Compare two List<T> objects for equality, ignoring order

I use this method )

public delegate bool CompareValue<in T1, in T2>(T1 val1, T2 val2);

public static bool CompareTwoArrays<T1, T2>(this IEnumerable<T1> array1, IEnumerable<T2> array2, CompareValue<T1, T2> compareValue)
{
    return array1.Select(item1 => array2.Any(item2 => compareValue(item1, item2))).All(search => search)
            && array2.Select(item2 => array1.Any(item1 => compareValue(item1, item2))).All(search => search);
}

Saving the PuTTY session logging

This is a bit confusing, but follow these steps to save the session.

  1. Category -> Session -> enter public IP in Host and 22 in port.
  2. Connection -> SSH -> Auth -> select the .ppk file
  3. Category -> Session -> enter a name in Saved Session -> Click Save

To open the session, double click on particular saved session.

How to convert int[] into List<Integer> in Java?

Also from guava libraries... com.google.common.primitives.Ints:

List<Integer> Ints.asList(int...)

PHP - regex to allow letters and numbers only

As the OP said that he wants letters and numbers ONLY (no underscore!), one more way to have this in php regex is to use posix expressions:

/^[[:alnum:]]+$/

Note: This will not work in Java, JavaScript, Python, Ruby, .NET

connecting to phpMyAdmin database with PHP/MySQL

Connect to MySQL

<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'username';

/*** mysql password ***/
$password = 'password';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?>

Also mysqli_connect() function to open a new connection to the MySQL server.

<?php
// Create connection
$con=mysqli_connect(host,username,password,dbname); 

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?> 

Difference in make_shared and normal shared_ptr in C++

The shared pointer manages both the object itself, and a small object containing the reference count and other housekeeping data. make_shared can allocate a single block of memory to hold both of these; constructing a shared pointer from a pointer to an already-allocated object will need to allocate a second block to store the reference count.

As well as this efficiency, using make_shared means that you don't need to deal with new and raw pointers at all, giving better exception safety - there is no possibility of throwing an exception after allocating the object but before assigning it to the smart pointer.

jQuery: count number of rows in a table

row_count =  $('#my_table').find('tr').length;
column_count =  $('#my_table').find('td').length / row_count;

Transpose list of lists

One way to do it is with NumPy transpose. For a list, a:

>>> import numpy as np
>>> np.array(a).T.tolist()
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Or another one without zip:

>>> map(list,map(None,*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

What is Gradle in Android Studio?

You can find everything you need to know about Gradle here: Gradle Plugin User Guide

Goals of the new Build System

The goals of the new build system are:

  • Make it easy to reuse code and resources
  • Make it easy to create several variants of an application, either for multi-apk distribution or for different flavors of an application
  • Make it easy to configure, extend and customize the build process
  • Good IDE integration

Why Gradle?

Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins.

Here are some of its features that made us choose Gradle:

  • Domain Specific Language (DSL) to describe and manipulate the build logic
  • Build files are Groovy based and allow mixing of declarative elements through the DSL and using code to manipulate the DSL elements to provide custom logic.
  • Built-in dependency management through Maven and/or Ivy.
  • Very flexible. Allows using best practices but doesn’t force its own way of doing things.
  • Plugins can expose their own DSL and their own API for build files to use.
  • Good Tooling API allowing IDE integration

Prevent HTML5 video from being downloaded (right-click saved)?

Short Answer: Encrypt the link like youtube does, don't know how than ask youtube/google of how they do it. (Just in case you want to get straight into the point.)

I would like to point out to anyone that this is possible because youtube does it and if they can so can any other website and it isn't from the browser either because I tested it on a couple browsers such as microsoft edge and internet explorer and so there is a way to disable it and seen that people still say it...I tries looking for an answer because if youtube can than there has to be a way and the only way to see how they do it is if someone looked into the scripts of youtube which I am doing now. I also checked to see if it was a custom context menu as well and it isn't because the context menu is over flowing the inspect element and I mean like it is over it and I looked and it never creates a new class and also it is impossible to actually access inspect element with javascript so it can't be. You can tell when it double right-click a youtube video that it pops up the context menu for chrome. Besides...youtube wouldn't add that function in. I am doing research and looking through the source of youtube so I will be back if I find the answer...if anyone says you can't than, well they didn't do research like I have. The only way to download youtube videos is through a video download.

Okay...I did research and my research stays that you can disable it except there is no javascript to it...you have to be able to encrypt the links to the video for you to be able to disable it because I think any browser won't show it if it can't find it and when I opened a youtube video link it showed as this "blob:https://www.youtube.com/e5c4808e-297e-451f-80da-3e838caa1275" without quotes so it is encrypting it so it cannot be saved...you need to know php for that but like the answer you picked out of making it harder, youtube makes it the hardest of heavy encrypting it, you need to be an advance php programmer but if you don't know that than take the person you picked as best answer of making it hard to download it...but if you know php than heavy encrypt the video link so it only is able to be read on yours...I don't know how to explain how they do it but they did and there is a way. The way youtube Encrypts there videos is quite smart so if you want to know how to than just ask youtube/google of how they do it...hope this helps for you although you already picked a best answer. So encrypting the link is best in short terms.

Push git commits & tags simultaneously

Git GUI

Git GUI has a PUSH button - pardon the pun, and the dialog box it opens has a checkbox for tags.

I pushed a branch from the command line, without tags, and then tried again pushing the branch using the --follow-tags option descibed above. The option is described as following annotated tags. My tags were simple tags.

I'd fixed something, tagged the commit with the fix in, (so colleagues can cherry pick the fix,) then changed the software version number and tagged the release I created (so colleagues can clone that release).

Git returned saying everything was up-to-date. It did not send the tags! Perhaps because the tags weren't annotated. Perhaps because there was nothing new on the branch.

When I did a similar push with Git GUI, the tags were sent.

Tags sent with Git GUI

For the time being, I am going to be pushing my changes to my remotes with Git GUI and not with the command line and --follow-tags.

How can I find out what version of git I'm running?

If you're using the command-line tools, running git --version should give you the version number.

Disable webkit's spin buttons on input type="number"?

I discovered that there is a second portion of the answer to this.

The first portion helped me, but I still had a space to the right of my type=number input. I had zeroed out the margin on the input, but apparently I had to zero out the margin on the spinner as well.

This fixed it:

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

How to give a Linux user sudo access?

This answer will do what you need, although usually you don't add specific usernames to sudoers. Instead, you have a group of sudoers and just add your user to that group when needed. This way you don't need to use visudo more than once when giving sudo permission to users.

If you're on Ubuntu, the group is most probably already set up and called admin:

$ sudo cat /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#

...

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

On other distributions, like Arch and some others, it's usually called wheel and you may need to set it up: Arch Wiki

To give users in the wheel group full root privileges when they precede a command with "sudo", uncomment the following line: %wheel ALL=(ALL) ALL

Also note that on most systems visudo will read the EDITOR environment variable or default to using vi. So you can try to do EDITOR=vim visudo to use vim as the editor.

To add a user to the group you should run (as root):

# usermod -a -G groupname username

where groupname is your group (say, admin or wheel) and username is the username (say, john).

How to initialize a nested struct?

package main

type    Proxy struct {
        Address string
        Port    string
    }

type Configuration struct {
    Proxy
    Val   string

}

func main() {

    c := &Configuration{
        Val: "test",
        Proxy: Proxy {
            Address: "addr",
            Port:    "80",
        },
    }

}

Getting full-size profile picture

For Angular:

getUserPicture(userId) {   
FB.api('/' + userId, {fields: 'picture.width(800).height(800)'}, function(response) {
  console.log('getUserPicture',response);
});
}

How to set root password to null

If you know your Root Password and just wish to reset it then do as below:

  • Start MySQL Service from control panel > Administrative Tools > Services. (only if it was stopped by you earlier ! Otherwise, just skip this step)

  • Start MySQL Workbench

  • Type in this command/SQL line

    ALTER USER 'root'@'localhost' PASSWORD EXPIRE;

To reset any other user password... just type other user name instead of root.

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Read and write to binary files in C?

I'm quite happy with my "make a weak pin storage program" solution. Maybe it will help people who need a very simple binary file IO example to follow.

$ ls
WeakPin  my_pin_code.pin  weak_pin.c
$ ./WeakPin
Pin: 45 47 49 32
$ ./WeakPin 8 2
$ Need 4 ints to write a new pin!
$./WeakPin 8 2 99 49
Pin saved.
$ ./WeakPin
Pin: 8 2 99 49
$
$ cat weak_pin.c
// a program to save and read 4-digit pin codes in binary format

#include <stdio.h>
#include <stdlib.h>

#define PIN_FILE "my_pin_code.pin"

typedef struct { unsigned short a, b, c, d; } PinCode;


int main(int argc, const char** argv)
{
    if (argc > 1)  // create pin
    {
        if (argc != 5)
        {
            printf("Need 4 ints to write a new pin!\n");
            return -1;
        }
        unsigned short _a = atoi(argv[1]);
        unsigned short _b = atoi(argv[2]);
        unsigned short _c = atoi(argv[3]);
        unsigned short _d = atoi(argv[4]);
        PinCode pc;
        pc.a = _a; pc.b = _b; pc.c = _c; pc.d = _d;
        FILE *f = fopen(PIN_FILE, "wb");  // create and/or overwrite
        if (!f)
        {
            printf("Error in creating file. Aborting.\n");
            return -2;
        }

        // write one PinCode object pc to the file *f
        fwrite(&pc, sizeof(PinCode), 1, f);  

        fclose(f);
        printf("Pin saved.\n");
        return 0;
    }

    // else read existing pin
    FILE *f = fopen(PIN_FILE, "rb");
    if (!f)
    {
        printf("Error in reading file. Abort.\n");
        return -3;
    }
    PinCode pc;
    fread(&pc, sizeof(PinCode), 1, f);
    fclose(f);

    printf("Pin: ");
    printf("%hu ", pc.a);
    printf("%hu ", pc.b);
    printf("%hu ", pc.c);
    printf("%hu\n", pc.d);
    return 0;
}
$

How do I modify a MySQL column to allow NULL?

Under some circumstances (if you get "ERROR 1064 (42000): You have an error in your SQL syntax;...") you need to do

ALTER TABLE mytable MODIFY mytable.mycolumn varchar(255);

Returning http 200 OK with error within response body

I think people have put too much weight into the application logic versus protocol matter. The important thing is that the response should make sense. What if you have an API that serves a dynamic resource and a request is made for X which is derived from template Y with data Z and either Y or Z isn't currently available? Is that a business logic error or a technical error? The correct answer is, "who cares?"

Your API and your responses need to be intelligible and consistent. It should conform to some kind of spec, and that spec should define what a valid response is. Something that conforms to a valid response should yield a 200 code. Something that does not conform to a valid response should yield a 4xx or 5xx code indicative of why a valid response couldn't be generated.

If your spec's definition of a valid response permits { "error": "invalid ID" }, then it's a successful response. If your spec doesn't make that accommodation, it would be a poor decision to return that response with a 200 code.

I'd draw an analogy to calling a function parseFoo. What happens when you call parseFoo("invalid data")? Does it return an error result (maybe null)? Or does it throw an exception? Many will take a near-religious position on whether one approach or the other is correct, but ultimately it's up to the API specification.

"The status-code element is a three-digit integer code giving the result of the attempt to understand and satisfy the request"

Obviously there's a difference of opinion with regards to whether "successfully returning an error" constitutes an HTTP success or error. I see different people interpreting the same specs different ways. So pick a side, sure, but also accept that either way the whole world isn't going to agree with you. Me? I find myself somewhere in the middle, but I'll offer some commonsense considerations.

  1. If your server-side code catches an unexpected exception when dispatching a request, that sounds like the very definition of a 500 Internal Server Error. This seems to be OP's situation. The application should not return a 200 for unexpected errors, but also see point 3.
  2. If your server-side code should be able to gracefully handle a given invalid input, and it doesn't constitute an "exceptional" error condition, your spec should accommodate HTTP 200 responses that provide meaningful diagnostic information.
  3. Above all: Have a spec. Make it consistent. Stick to it.

In OP's situation, it sounds like you have a de-facto standard that unhandled exceptions yield a 200 with a distinguishable response body. It's not ideal, but if it's not breaking things and actively causing problems, you probably have bigger, more important problems to solve.

Importing a CSV file into a sqlite3 database table using Python

The following can also add fields' name based on the CSV header:

import sqlite3

def csv_sql(file_dir,table_name,database_name):
    con = sqlite3.connect(database_name)
    cur = con.cursor()
    # Drop the current table by: 
    # cur.execute("DROP TABLE IF EXISTS %s;" % table_name)

    with open(file_dir, 'r') as fl:
        hd = fl.readline()[:-1].split(',')
        ro = fl.readlines()
        db = [tuple(ro[i][:-1].split(',')) for i in range(len(ro))]

    header = ','.join(hd)
    cur.execute("CREATE TABLE IF NOT EXISTS %s (%s);" % (table_name,header))
    cur.executemany("INSERT INTO %s (%s) VALUES (%s);" % (table_name,header,('?,'*len(hd))[:-1]), db)
    con.commit()
    con.close()

# Example:
csv_sql('./surveys.csv','survey','eco.db')

Exec : display stdout "live"

I'd just like to add that one small issue with outputting the buffer strings from a spawned process with console.log() is that it adds newlines, which can spread your spawned process output over additional lines. If you output stdout or stderr with process.stdout.write() instead of console.log(), then you'll get the console output from the spawned process 'as is'.

I saw that solution here: Node.js: printing to console without a trailing newline?

Hope that helps someone using the solution above (which is a great one for live output, even if it is from the documentation).

Delete item from array and shrink array

I have created this function, or class. Im kinda new but my friend needed this also so I created this:

public String[] name(int index, String[] z ){
    if(index > z.length){
        return z;
    } else {
        String[] returnThis = new String[z.length - 1];
        int newIndex = 0;
        for(int i = 0; i < z.length; i++){
            if(i != index){
                returnThis[newIndex] = z[i];
                newIndex++;
            }
        }
        return returnThis; 
    }
}

Since its pretty revelant, I thought I would post it here.

How to add rows dynamically into table layout

Here's technique I figured out after a bit of trial and error that allows you to preserve your XML styles and avoid the issues of using a <merge/> (i.e. inflate() requires a merge to attach to root, and returns the root node). No runtime new TableRow()s or new TextView()s required.

Code

Note: Here CheckBalanceActivity is some sample Activity class

TableLayout table = (TableLayout)CheckBalanceActivity.this.findViewById(R.id.attrib_table);
for(ResourceBalance b : xmlDoc.balance_info)
{
    // Inflate your row "template" and fill out the fields.
    TableRow row = (TableRow)LayoutInflater.from(CheckBalanceActivity.this).inflate(R.layout.attrib_row, null);
    ((TextView)row.findViewById(R.id.attrib_name)).setText(b.NAME);
    ((TextView)row.findViewById(R.id.attrib_value)).setText(b.VALUE);
    table.addView(row);
}
table.requestLayout();     // Not sure if this is needed.

attrib_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TableRow style="@style/PlanAttribute"  xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
        style="@style/PlanAttributeText"
        android:id="@+id/attrib_name"
        android:textStyle="bold"/>
    <TextView
        style="@style/PlanAttributeText"
        android:id="@+id/attrib_value"
        android:gravity="right"
        android:textStyle="normal"/>
</TableRow>

Styling mat-select in Angular Material

For Angular9+, according to this, you can use:

.mat-select-panel {
    background: red;
    ....
}

Demo


Angular Material uses mat-select-content as class name for the select list content. For its styling I would suggest four options.

1. Use ::ng-deep:

Use the /deep/ shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The /deep/ combinator works to any depth of nested components, and it applies to both the view children and content children of the component. Use /deep/, >>> and ::ng-deep only with emulated view encapsulation. Emulated is the default and most commonly used view encapsulation. For more information, see the Controlling view encapsulation section. The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

CSS:

::ng-deep .mat-select-content{
    width:2000px;
    background-color: red;
    font-size: 10px;   
}

DEMO


2. Use ViewEncapsulation

... component CSS styles are encapsulated into the component's view and don't affect the rest of the application. To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes: .... None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.

None value is what you will need to break the encapsulation and set material style from your component. So can set on the component's selector:

Typscript:

  import {ViewEncapsulation } from '@angular/core';
  ....
  @Component({
        ....
        encapsulation: ViewEncapsulation.None
 })  

CSS

.mat-select-content{
    width:2000px;
    background-color: red;
    font-size: 10px;
}

DEMO


3. Set class style in style.css

This time you have to 'force' styles with !important too.

style.css

 .mat-select-content{
   width:2000px !important;
   background-color: red !important;
   font-size: 10px !important;
 } 

DEMO


4. Use inline style

<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>

DEMO

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

On Debian/Ubuntu use:

sudo apt-get install g++-multilib libc6-dev-i386

Android - Start service on boot

Following should work. I have verified. May be your problem is somewhere else.

Receiver:

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
            Log.d("TAG", "MyReceiver");
            Intent serviceIntent = new Intent(context, Test1Service.class);
            context.startService(serviceIntent);
        }
    }
}

Service:

public class Test1Service extends Service {
    /** Called when the activity is first created. */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "Service created.");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "Service started.");
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d("TAG", "Service started.");
    }
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0"
      android:installLocation="internalOnly">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
    
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BATTERY_STATS" 
    />
<!--        <activity android:name=".MyActivity">
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER"></category> 
            </intent-filter>
       </activity> -->
        <service android:name=".Test1Service" 
                  android:label="@string/app_name"
                  >
        </service>
        <receiver android:name=".MyReceiver">  
            <intent-filter>  
                <action android:name="android.intent.action.BOOT_COMPLETED" /> 
            </intent-filter>  
        </receiver> 
    </application>
</manifest>

html vertical align the text inside input type button

The simplest thing you can do is use reset.css. It normalizes the default stylesheet across browsers, and coincidentally allows button { vertical-align: middle; } to work just fine. Give it a shot - I use it in virtually all of my projects just to kill little bugs like this.

https://gist.github.com/nathansmith/288292

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

How to get "their" changes in the middle of conflicting Git rebase?

You want to use:

git checkout --ours foo/bar.java
git add foo/bar.java

If you rebase a branch feature_x against main (i.e. running git rebase main while on branch feature_x), during rebasing ours refers to main and theirs to feature_x.

As pointed out in the git-rebase docs:

Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.

For further details read this thread.

Create a tar.xz in one command

Try this: tar -cf file.tar file-to-compress ; xz -z file.tar

Note:

  1. tar.gz and tar.xz are not the same; xz provides better compression.
  2. Don't use pipe | because this runs commands simultaneously. Using ; or & executes commands one after another.

jQuery - Getting the text value of a table cell in the same row as a clicked element

This will also work

$(this).parent().parent().find('td').text()

How to backup a local Git repository?

came to this question via google.

Here is what i did in the simplest way.

git checkout branch_to_clone

then create a new git branch from this branch

git checkout -b new_cloned_branch
Switched to branch 'new_cloned_branch'

come back to original branch and continue:

git checkout branch_to_clone

Assuming you screwed up and need to restore something from backup branch :

git checkout new_cloned_branch -- <filepath>  #notice the space before and after "--"

Best part if anything is screwed up, you can just delete the source branch and move back to backup branch!!

How do you use the "WITH" clause in MySQL?

I liked @Brad's answer from this thread, but wanted a way to save the results for further processing (MySql 8):

-- May need to adjust the recursion depth first
SET @@cte_max_recursion_depth = 10000 ; -- permit deeper recursion

-- Some boundaries 
set @startDate = '2015-01-01'
    , @endDate = '2020-12-31' ; 

-- Save it to a table for later use
drop table if exists tmpDates ;
create temporary table tmpDates as      -- this has to go _before_ the "with", Duh-oh! 
    WITH RECURSIVE t as (
        select @startDate as dt
      UNION
        SELECT DATE_ADD(t.dt, INTERVAL 1 DAY) FROM t WHERE DATE_ADD(t.dt, INTERVAL 1 DAY) <= @endDate
    )
    select * FROM t     -- need this to get the "with"'s results as a "result set", into the "create"
;

-- Exists?
select * from tmpDates ;

Which produces:

dt        |
----------|
2015-01-01|
2015-01-02|
2015-01-03|
2015-01-04|
2015-01-05|
2015-01-06|

Oracle SQL Query for listing all Schemas in a DB

How about :

SQL> select * from all_users;

it will return list of all users/schemas, their ID's and date created in DB :

USERNAME                          USER_ID CREATED
------------------------------ ---------- ---------
SCHEMA1                         120 09-SEP-15
SCHEMA2                         119 09-SEP-15
SCHEMA3                         118 09-SEP-15

Permutation of array

There are n! total permutations for the given array size n. Here is code written in Java using DFS.

public List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> results = new ArrayList<List<Integer>>();
    if (nums == null || nums.length == 0) {
        return results;
    }
    List<Integer> result = new ArrayList<>();
    dfs(nums, results, result);
    return results;
}

public void dfs(int[] nums, List<List<Integer>> results, List<Integer> result) {
    if (nums.length == result.size()) {
        List<Integer> temp = new ArrayList<>(result);
        results.add(temp);
    }        
    for (int i=0; i<nums.length; i++) {
        if (!result.contains(nums[i])) {
            result.add(nums[i]);
            dfs(nums, results, result);
            result.remove(result.size() - 1);
        }
    }
}

For input array [3,2,1,4,6], there are totally 5! = 120 possible permutations which are:

[[3,4,6,2,1],[3,4,6,1,2],[3,4,2,6,1],[3,4,2,1,6],[3,4,1,6,2],[3,4,1,2,6],[3,6,4,2,1],[3,6,4,1,2],[3,6,2,4,1],[3,6,2,1,4],[3,6,1,4,2],[3,6,1,2,4],[3,2,4,6,1],[3,2,4,1,6],[3,2,6,4,1],[3,2,6,1,4],[3,2,1,4,6],[3,2,1,6,4],[3,1,4,6,2],[3,1,4,2,6],[3,1,6,4,2],[3,1,6,2,4],[3,1,2,4,6],[3,1,2,6,4],[4,3,6,2,1],[4,3,6,1,2],[4,3,2,6,1],[4,3,2,1,6],[4,3,1,6,2],[4,3,1,2,6],[4,6,3,2,1],[4,6,3,1,2],[4,6,2,3,1],[4,6,2,1,3],[4,6,1,3,2],[4,6,1,2,3],[4,2,3,6,1],[4,2,3,1,6],[4,2,6,3,1],[4,2,6,1,3],[4,2,1,3,6],[4,2,1,6,3],[4,1,3,6,2],[4,1,3,2,6],[4,1,6,3,2],[4,1,6,2,3],[4,1,2,3,6],[4,1,2,6,3],[6,3,4,2,1],[6,3,4,1,2],[6,3,2,4,1],[6,3,2,1,4],[6,3,1,4,2],[6,3,1,2,4],[6,4,3,2,1],[6,4,3,1,2],[6,4,2,3,1],[6,4,2,1,3],[6,4,1,3,2],[6,4,1,2,3],[6,2,3,4,1],[6,2,3,1,4],[6,2,4,3,1],[6,2,4,1,3],[6,2,1,3,4],[6,2,1,4,3],[6,1,3,4,2],[6,1,3,2,4],[6,1,4,3,2],[6,1,4,2,3],[6,1,2,3,4],[6,1,2,4,3],[2,3,4,6,1],[2,3,4,1,6],[2,3,6,4,1],[2,3,6,1,4],[2,3,1,4,6],[2,3,1,6,4],[2,4,3,6,1],[2,4,3,1,6],[2,4,6,3,1],[2,4,6,1,3],[2,4,1,3,6],[2,4,1,6,3],[2,6,3,4,1],[2,6,3,1,4],[2,6,4,3,1],[2,6,4,1,3],[2,6,1,3,4],[2,6,1,4,3],[2,1,3,4,6],[2,1,3,6,4],[2,1,4,3,6],[2,1,4,6,3],[2,1,6,3,4],[2,1,6,4,3],[1,3,4,6,2],[1,3,4,2,6],[1,3,6,4,2],[1,3,6,2,4],[1,3,2,4,6],[1,3,2,6,4],[1,4,3,6,2],[1,4,3,2,6],[1,4,6,3,2],[1,4,6,2,3],[1,4,2,3,6],[1,4,2,6,3],[1,6,3,4,2],[1,6,3,2,4],[1,6,4,3,2],[1,6,4,2,3],[1,6,2,3,4],[1,6,2,4,3],[1,2,3,4,6],[1,2,3,6,4],[1,2,4,3,6],[1,2,4,6,3],[1,2,6,3,4],[1,2,6,4,3]]

Hope this helps.

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Spring is a light weight and open source framework created by Rod Johnson in 2003. Spring is a complete and a modular framework, Spring framework can be used for all layer implementations for a real time application or spring can be used for the development of particular layer of a real time application.

Struts is an open-source web application framework for developing Java EE web applications. It uses and extends the Java Servlet API to encourage developers to adopt a model–view–controller (MVC) architecture. It was originally created by Craig McClanahan and donated to the Apache Foundation in May, 2000.

Listed below is the comparison chart of difference between Spring and Strut Framework

enter image description here

How to input matrix (2D list) in Python?

you can accept a 2D list in python this way ...

simply

arr2d = [[j for j in input().strip()] for i in range(n)] 
# n is no of rows


for characters

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = list(input().strip())
print(a)

or

n = int(input().strip())
n = int(input().strip())
a = []
for i in range(n):
    a[i].append(list(input().strip()))
print(a)

for numbers

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = [int(j) for j in input().strip().split(" ")]
print(a)

where n is no of elements in columns while m is no of elements in a row.

In pythonic way, this will create a list of list

Increasing (or decreasing) the memory available to R processes

Use memory.limit(). You can increase the default using this command, memory.limit(size=2500), where the size is in MB. You need to be using 64-bit in order to take real advantage of this.

One other suggestion is to use memory efficient objects wherever possible: for instance, use a matrix instead of a data.frame.

Force index use in Oracle

You can use optimizer hints

select /*+ INDEX(table_name index_name) */ from table etc...

More on using optimizer hints: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/hintsref.htm

How to open a Bootstrap modal window using jQuery?

Try

$("#myModal").modal("toggle")

To open or close the modal with id myModal.

If the above is not working then it means bootstrap.js has been overridden by some other js file. Here is a solution

1:- Move bootstrap.js to the bottom so that it will override other js files.

2:- Make sure the order is like below

<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Other js files -->
<script src="plugins/jQuery/bootstrap.min.js"></script>

How do you send a Firebase Notification to all devices via CURL?

The most easiest way I came up with to send the push notification to all the devices is to subscribe them to a topic "all" and then send notification to this topic. Copy this in your main activity

FirebaseMessaging.getInstance().subscribeToTopic("all");

Now send the request as

{
   "to":"/topics/all",
   "data":
   {
      "title":"Your title",
      "message":"Your message"
      "image-url":"your_image_url"
   }
}

This might be inefficient or non-standard way, but as I mentioned above it's the easiest. Please do post if you have any better way to send a push notification to all the devices.

You can follow this tutorial if you're new to sending push notifications using Firebase Cloud Messaging Tutorial - Push Notifications using FCM


To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to TopicA and either TopicB or TopicC:

{
   "data":
   {
      "title": "Your title",
      "message": "Your message"
      "image-url": "your_image_url"
   },
   "condition": "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
}

Read more about conditions and topics here on FCM documentation

What is the difference between Python and IPython?

From my experience I've found that some commands which run in IPython do not run in base Python. For example, pwd and ls don't work alone in base Python. However they will work if prefaced with a % such as: %pwd and %ls.

Also, in IPython, you can run the cd command like: cd C:\Users\... This doesn't seem to work in base python, even when prefaced with a % however.

How to show code but hide output in RMarkdown?

For what it's worth.

```{r eval=FALSE}

The document will display the code by default but will prevent the code block from being executed, and thus will also not display any results.

form_for but to post to a different action

I have done it like that

<%= form_for :user, url: {action: "update", params: {id: @user.id}} do |f| %>

Note the optional parameter id set to user instance id attribute.

How to remove anaconda from windows completely?

there is a start item folder in C:\ drive. Remove ur anaconda3 folder there, simple and you are good to go. In my case I found here "C:\Users\pravu\AppData\Roaming\Microsoft\Windows\Start Menu\Programs"

WCF service maxReceivedMessageSize basicHttpBinding issue

Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:

<services>
  <service name="Service.IService">
    <clear />
    <endpoint binding="basicHttpBinding" contract="Service.IService" />
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
        maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </binding>
  </basicHttpBinding>
  <webHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
  </webHttpBinding>
</bindings>

Also note that I removed the bindingConfiguration attribute from the endpoint node. Otherwise you would get an exception.

This same solution was found here : Problem with large requests in WCF

How do I run a Java program from the command line on Windows?

Assuming the file is called "CopyFile.java", do the following:

javac CopyFile.java
java -cp . CopyFile

The first line compiles the source code into executable byte code. The second line executes it, first adding the current directory to the class path (just in case).

How to remove time portion of date in C# in DateTime object only?

DateTime.Date

var newDate = DateTime.Now; //newDate.Date property is date portion of DateTime

How can I add an item to a IEnumerable<T> collection?

You cannot, because IEnumerable<T> does not necessarily represent a collection to which items can be added. In fact, it does not necessarily represent a collection at all! For example:

IEnumerable<string> ReadLines()
{
     string s;
     do
     {
          s = Console.ReadLine();
          yield return s;
     } while (!string.IsNullOrEmpty(s));
}

IEnumerable<string> lines = ReadLines();
lines.Add("foo") // so what is this supposed to do??

What you can do, however, is create a new IEnumerable object (of unspecified type), which, when enumerated, will provide all items of the old one, plus some of your own. You use Enumerable.Concat for that:

 items = items.Concat(new[] { "foo" });

This will not change the array object (you cannot insert items into to arrays, anyway). But it will create a new object that will list all items in the array, and then "Foo". Furthermore, that new object will keep track of changes in the array (i.e. whenever you enumerate it, you'll see the current values of items).

DateTime format to SQL format using C#

Let's use the built in SqlDateTime class

new SqlDateTime(DateTime.Now).ToSqlString()

But still need to check for null values. This will throw overflow exception

new SqlDateTime(DateTime.MinValue).ToSqlString()

SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

Plot yerr/xerr as shaded region rather than error bars

Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between():

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)

plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()

enter image description here

See also the matplotlib examples.

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Alright, this is probably the easiest way to do it:

  1. First of all, you will have to install GAPPS.
  2. Next, open the virtual box and wait for the home screen to show up on Genymotion.
  3. Drag and drop the GAPPS folder that you had downloaded earlier on into Genymotion.
  4. You would get a prompt. Click OK. You would see a lot of errors, but just ignore them and wait for the successful prompt to come up. Click OK again and restart the virtual device.
  5. A Google account screen should show up. Open up the playstore app if it doesn't show up. Sign into your account. Again ignore the errors.
  6. The playstore should open now and should be fully functional.

Converting Integer to String with comma for thousands

use Extension

import java.text.NumberFormat

val Int.commaString: String
  get() = NumberFormat.getInstance().format(this)

val String.commaString: String
  get() = NumberFormat.getNumberInstance().format(this.toDouble())

val Long.commaString: String
  get() = NumberFormat.getInstance().format(this)

val Double.commaString: String
  get() = NumberFormat.getInstance().format(this)

result

1234.commaString => 1,234
"1234.456".commaString => 1,234.456
1234567890123456789.commaString => 1,234,567,890,123,456,789
1234.456.commaString => 1,234.456

How to call a php script/function on a html button click

Use jQuery.In the HTML page -

<button type="button">Click Me</button>

<script>
$(document).ready(function() {
$("button").click(function(){
  $.ajax({
    url:"php_page.php", //the page containing php script
    type: "POST", //request type
    success:function(result){
    alert(result);
    }
  });
});
})
</script>

Php page -

echo "Hello";

simple vba code gives me run time error 91 object variable or with block not set

You need Set with objects:

 Set rng = Sheet8.Range("A12")

Sheet8 is fine.

 Sheet1.[a1]