Programs & Examples On #Varying

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

Varying is an alias for varchar, so no difference, see documentation :)

The notations varchar(n) and char(n) are aliases for character varying(n) and character(n), respectively. character without length specifier is equivalent to character(1). If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.

Angular2 router (@angular/router), how to set default route?

Only you need to add other parameter in your route, the parameter is useAsDefault:true. For example, if you want the DashboardComponent as default you need to do this:

@RouteConfig([
    { path: '/Dashboard', component: DashboardComponent , useAsDefault:true},
    .
    .
    .
    ])

I recomend you to add names to your routes.

{ path: '/Dashboard',name:'Dashboard', component: DashboardComponent , useAsDefault:true}

How to ignore HTML element from tabindex?

You can use tabindex="-1".

The W3C HTML5 specification supports negative tabindex values:

If the value is a negative integer
The user agent must set the element's tabindex focus flag, but should not allow the element to be reached using sequential focus navigation.


Watch out though that this is a HTML5 feature and might not work with old browsers.
To be W3C HTML 4.01 standard (from 1999) compliant, tabindex would need to be positive.


Sample usage below in pure HTML.

_x000D_
_x000D_
<input />_x000D_
<input tabindex="-1" placeholder="NoTabIndex" />_x000D_
<input />
_x000D_
_x000D_
_x000D_

MySQL Insert query doesn't work with WHERE clause

correct syntax for mysql insert into statement using post method is:

$sql="insert into ttable(username,password) values('$_POST[username]','$_POST[password]')";

How do I print the key-value pairs of a dictionary in python

To Print key-value pair, for example:

players = {
     'lebron': 'lakers',
     'giannis':   'milwakee bucks',
     'durant':  'brooklyn nets',
     'kawhi':   'clippers',    
}

for player,club in players.items():

print(f"\n{player.title()} is the leader of {club}")

The above code, key-value pair:

 'lebron': 'lakers', - Lebron is key and lakers is value

for loop - specify key, value in dictionary.item():

Now Print (Player Name is the leader of club).

the Output is:

#Lebron is the leader of lakers
#Giannis is the leader of milwakee bucks
#Durant is the leader of brooklyn nets
#Kawhi is the leader of clippers

What is a method group in C#?

The ToString function has many overloads - the method group would be the group consisting of all the different overloads for that function.

Array copy values to keys in PHP

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So I solved it like this:

foreach($array as $key => $val) {
    $new_array[$val]=$val;
}

Reset push notification settings for app

Another just for testing solution to this is by simply changing your bundle id. Just don't forget to change it back once you're done!

React: "this" is undefined inside a component function

I ran into a similar bind in a render function and ended up passing the context of this in the following way:

{someList.map(function(listItem) {
  // your code
}, this)}

I've also used:

{someList.map((listItem, index) =>
    <div onClick={this.someFunction.bind(this, listItem)} />
)}

Android EditText Max Length

I had the same problem.

Here is a workaround

android:inputType="textNoSuggestions|textVisiblePassword"
android:maxLength="6"

Thx to How can I turnoff suggestions in EditText?

Download JSON object as a file from browser

The download property of links is new and not is supported in Internet Explorer (see the compatibility table here). For a cross-browser solution to this problem I would take a look at FileSaver.js

How to insert text into the textarea at the current cursor position?

New answer:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText

I'm not sure about the browser support for this though.

Tested in Chrome 81.

_x000D_
_x000D_
function typeInTextarea(newText, el = document.activeElement) {_x000D_
  const [start, end] = [el.selectionStart, el.selectionEnd];_x000D_
  el.setRangeText(newText, start, end, 'select');_x000D_
}_x000D_
_x000D_
document.getElementById("input").onkeydown = e => {_x000D_
  if (e.key === "Enter") typeInTextarea("lol");_x000D_
}
_x000D_
<input id="input" />_x000D_
<br/><br/>_x000D_
<div>Press Enter to insert "lol" at caret.</div>_x000D_
<div>It'll replace a selection with the given text.</div>
_x000D_
_x000D_
_x000D_

Old answer:

A pure JS modification of Erik Pukinskis' answer:

_x000D_
_x000D_
function typeInTextarea(newText, el = document.activeElement) {_x000D_
  const start = el.selectionStart_x000D_
  const end = el.selectionEnd_x000D_
  const text = el.value_x000D_
  const before = text.substring(0, start)_x000D_
  const after  = text.substring(end, text.length)_x000D_
  el.value = (before + newText + after)_x000D_
  el.selectionStart = el.selectionEnd = start + newText.length_x000D_
  el.focus()_x000D_
}_x000D_
_x000D_
document.getElementById("input").onkeydown = e => {_x000D_
  if (e.key === "Enter") typeInTextarea("lol");_x000D_
}
_x000D_
<input id="input" />_x000D_
<br/><br/>_x000D_
<div>Press Enter to insert "lol" at caret.</div>
_x000D_
_x000D_
_x000D_

Tested in Chrome 47, 81, and Firefox 76.

If you want to change the value of the currently selected text while you're typing in the same field (for an autocomplete or similar effect), pass document.activeElement as the first parameter.

It's not the most elegant way to do this, but it's pretty simple.

Example usages:

typeInTextarea('hello');
typeInTextarea('haha', document.getElementById('some-id'));

Android textview usage as label and value

You can use <LinearLayout> to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use. Here is an example:

<LinearLayout
                    style="@style/FormItem"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                <TextView
                        style="@style/FormLabel"
                        android:layout_width="wrap_content"
                        android:layout_height="@dimen/default_element_height"
                        android:text="@string/name_label"
                        />

                <EditText
                        style="@style/FormText.Editable"
                        android:id="@+id/cardholderName"
                        android:layout_width="wrap_content"
                        android:layout_height="@dimen/default_element_height"
                        android:layout_weight="1"
                        android:gravity="right|center_vertical"
                        android:hint="@string/card_name_hint"
                        android:imeOptions="actionNext"
                        android:singleLine="true"
                        />
            </LinearLayout>

Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?

How to get all table names from a database?

In your example problem is passed table name pattern in getTables function of DatabaseMetaData.

Some database supports Uppercase identifier, some support lower case identifiers. For example oracle fetches the table name in upper case, while postgreSQL fetch it in lower case.

DatabaseMetaDeta provides a method to determine how the database stores identifiers, can be mixed case, uppercase, lowercase see:http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()

From below example, you can get all tables and view of providing table name pattern, if you want only tables then remove "VIEW" from TYPES array.

public class DBUtility {
    private static final String[] TYPES = {"TABLE", "VIEW"};
    public static void getTableMetadata(Connection jdbcConnection, String tableNamePattern, String schema, String catalog, boolean isQuoted) throws HibernateException {
            try {
                DatabaseMetaData meta = jdbcConnection.getMetaData();
                ResultSet rs = null;
                try {
                    if ( (isQuoted && meta.storesMixedCaseQuotedIdentifiers())) {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    } else if ( (isQuoted && meta.storesUpperCaseQuotedIdentifiers())
                        || (!isQuoted && meta.storesUpperCaseIdentifiers() )) {
                        rs = meta.getTables(
                                StringHelper.toUpperCase(catalog),
                                StringHelper.toUpperCase(schema),
                                StringHelper.toUpperCase(tableNamePattern),
                                TYPES
                            );
                    }
                    else if ( (isQuoted && meta.storesLowerCaseQuotedIdentifiers())
                            || (!isQuoted && meta.storesLowerCaseIdentifiers() )) {
                        rs = meta.getTables( 
                                StringHelper.toLowerCase( catalog ),
                                StringHelper.toLowerCase(schema), 
                                StringHelper.toLowerCase(tableNamePattern), 
                                TYPES 
                            );
                    }
                    else {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    }

                    while ( rs.next() ) {
                        String tableName = rs.getString("TABLE_NAME");
                        System.out.println("table = " + tableName);
                    }



                }
                finally {
                    if (rs!=null) rs.close();
                }
            }
            catch (SQLException sqlException) {
                // TODO 
                sqlException.printStackTrace();
            }

    }

    public static void main(String[] args) {
        Connection jdbcConnection;
        try {
            jdbcConnection = DriverManager.getConnection("", "", "");
            getTableMetadata(jdbcConnection, "tbl%", null, null, false);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Laravel 5: Retrieve JSON array from $request

Just a mention with jQuery v3.2.1 and Laravel 5.6.

Case 1: The JS object posted directly, like:

$.post("url", {name:'John'}, function( data ) {
});

Corresponding Laravel PHP code should be:

parse_str($request->getContent(),$data); //JSON will be parsed to object $data

Case 2: The JSON string posted, like:

$.post("url", JSON.stringify({name:'John'}), function( data ) {
});

Corresponding Laravel PHP code should be:

$data = json_decode($request->getContent(), true);

Appending a line to a file only if it does not already exist

The answers using grep are wrong. You need to add an -x option to match the entire line otherwise lines like #text to add will still match when looking to add exactly text to add.

So the correct solution is something like:

grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar

Convert timestamp to string

try this

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string  = dateFormat.format(new Date());
System.out.println(string);

you can create any format see this

How to bind to a PasswordBox in MVVM

For anyone who is aware of the risks this implementation imposes, to have the password sync to your ViewModel simply add Mode=OneWayToSource.

XAML

<PasswordBox
    ff:PasswordHelper.Attach="True"
    ff:PasswordHelper.Password="{Binding Path=Password, Mode=OneWayToSource}" />

Limiting Python input strings to certain characters and lengths

if any( [ i>'z' or i<'a' for i in raw_input]):
    print "Error: Contains illegal characters"
elif len(raw_input)>15:
    print "Very long string"

Find the paths between two given nodes?

What you're trying to do is essentially to find a path between two vertices in a (directed?) graph check out Dijkstra's algorithm if you need shortest path or write a simple recursive function if you need whatever paths exist.

Silent installation of a MSI package

The proper way to install an MSI silently is via the msiexec.exe command line as follows:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"

Quick explanation:

 /L*V "C:\Temp\msilog.log"= verbose logging
 /QN = run completely silently
 /i = run install sequence 

There is a much more comprehensive answer here: Batch script to install MSI. This answer provides details on the msiexec.exe command line options and a description of how to find the "public properties" that you can set on the command line at install time. These properties are generally different for each MSI.

What is the purpose of .PHONY in a Makefile?

It is a build target that is not a filename.

I have created a table in hive, I would like to know which directory my table is created in?

in the 'default' directory if you have not specifically mentioned your location.

you can use describe and describe extended to know about the table structure.

How do I import a pre-existing Java project into Eclipse and get up and running?

  1. Create a new Java project in Eclipse. This will create a src folder (to contain your source files).

  2. Also create a lib folder (the name isn't that important, but it follows standard conventions).

  3. Copy the ./com/* folders into the /src folder (you can just do this using the OS, no need to do any fancy importing or anything from the Eclipse GUI).

  4. Copy any dependencies (jar files that your project itself depends on) into /lib (note that this should NOT include the TGGL jar - thanks to commenter Mike Deck for pointing out my misinterpretation of the OPs post!)

  5. Copy the other TGGL stuff into the root project folder (or some other folder dedicated to licenses that you need to distribute in your final app)

  6. Back in Eclipse, select the project you created in step 1, then hit the F5 key (this refreshes Eclipse's view of the folder tree with the actual contents.

  7. The content of the /src folder will get compiled automatically (with class files placed in the /bin file that Eclipse generated for you when you created the project). If you have dependencies (which you don't in your current project, but I'll include this here for completeness), the compile will fail initially because you are missing the dependency jar files from the project classpath.

  8. Finally, open the /lib folder in Eclipse, right click on each required jar file and choose Build Path->Add to build path.

That will add that particular jar to the classpath for the project. Eclipse will detect the change and automatically compile the classes that failed earlier, and you should now have an Eclipse project with your app in it.

How to correctly set Http Request Header in Angular 2

Your parameter for the request options in http.put() should actually be of type RequestOptions. Try something like this:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);

let options = new RequestOptions({ headers: headers });
return this.http
    .put(url, JSON.stringify(student), options)

Getting only Month and Year from SQL DATE

Some of the databases such as MS ACCESS or RODBC may not support the SQL SERVER functions, but for any database that has the FORMAT function you can simply do this:

SELECT FORMAT(<your-date-field>,"YYYY-MM") AS year-date FROM <your-table>

Executing Batch File in C#

System.Diagnostics.Process.Start("c:\\batchfilename.bat");

this simple line will execute the batch file.

SQL Combine Two Columns in Select Statement

I think this is what you are looking for -

select Address1+Address2 as CompleteAddress from YourTable
where Address1+Address2 like '%YourSearchString%'

To prevent a compound word being created when we append address1 with address2, you can use this -

select Address1 + ' ' + Address2 as CompleteAddress from YourTable 
where Address1 + ' ' + Address2 like '%YourSearchString%'

So, '123 Center St' and 'Apt 3B' will not be '123 Center StApt 3B' but will be '123 Center St Apt 3B'.

HTML - How to do a Confirmation popup to a Submit button and then send the request?

Use window.confirm() instead of window.alert().

HTML:

<input type="submit" onclick="return clicked();" value="Button" />

JavaScript:

function clicked() {
    return confirm('clicked');
}

Simple way to unzip a .zip file using zlib

zlib handles the deflate compression/decompression algorithm, but there is more than that in a ZIP file.

You can try libzip. It is free, portable and easy to use.

UPDATE: Here I attach quick'n'dirty example of libzip, with all the error controls ommited:

#include <zip.h>

int main()
{
    //Open the ZIP archive
    int err = 0;
    zip *z = zip_open("foo.zip", 0, &err);

    //Search for the file of given name
    const char *name = "file.txt";
    struct zip_stat st;
    zip_stat_init(&st);
    zip_stat(z, name, 0, &st);

    //Alloc memory for its uncompressed contents
    char *contents = new char[st.size];

    //Read the compressed file
    zip_file *f = zip_fopen(z, name, 0);
    zip_fread(f, contents, st.size);
    zip_fclose(f);

    //And close the archive
    zip_close(z);

    //Do something with the contents
    //delete allocated memory
    delete[] contents;
}

Excel concatenation quotes

I was Forming some Programming Logic Used CHAR(34) for Quotes at Excel : A small Part of same I am posting which can be helpfull ,Hopefully

1   Customers
2   Invoices

Formula Used :

=CONCATENATE("listEvents.Add(",D4,",",CHAR(34),E4,CHAR(34),");")

Result :

listEvents.Add(1,"Customers");
listEvents.Add(2,"Invoices");

Getting NetworkCredential for current user (C#)

If the web service being invoked uses windows integrated security, creating a NetworkCredential from the current WindowsIdentity should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.

Edit: To get the credentials for the current identity, use the following:

Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");

How to truncate string using SQL server

You can also use the Cast() operation :

 Declare @name varchar(100);
set @name='....';
Select Cast(@name as varchar(10)) as new_name

Appending to an existing string

Yet an other way:

s.insert(-1, ' world')

jQuery: how to scroll to certain anchor/div on page load?

I have tried some hours now and the easiest way to stop browsers to jump to the anchor instead of scrolling to it is: Using another anchor (an id you do not use on the site). So instead of linking to "http://#YourActualID" you link to "http://#NoIDonYourSite". Poof, browsers won’t jump anymore.

Then just check if an anchor is set (with the script provided below, that is pulled out of the other thread!). And set your actual id you want to scroll to.

$(document).ready(function(){


  $(window).load(function(){
    // Remove the # from the hash, as different browsers may or may not include it
    var hash = location.hash.replace('#','');

    if(hash != ''){

       // Clear the hash in the URL
       // location.hash = '';   // delete front "//" if you want to change the address bar
        $('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000);

       }
   });
});

See https://lightningsoul.com/media/article/coding/30/YOUTUBE-SOCKREAD-SCRIPT-FOR-MIRC#content for a working example.

What does 'git remote add upstream' help achieve?

Let's take an example: You want to contribute to django, so you fork its repository. In the while you work on your feature, there is much work done on the original repo by other people. So the code you forked is not the most up to date. setting a remote upstream and fetching it time to time makes sure your forked repo is in sync with the original repo.

Change background color of iframe issue

You can do it using javascript

  • Change iframe background color
  • Change background color of the loaded page (same domain)

Plain javascript

var iframe = document.getElementsByTagName('iframe')[0];
iframe.style.background = 'white';
iframe.contentWindow.document.body.style.backgroundColor = 'white';

jQuery

$('iframe').css('background', 'white');
$('iframe').contents().find('body').css('backgroundColor', 'white');

How to declare a global variable in C++

Not sure if this is correct in any sense but this seems to work for me.

someHeader.h
inline int someVar;

I don't have linking/multiple definition issues and it "just works"... ;- )

It's quite handy for "quick" tests... Try to avoid global vars tho, because every says so... ;- )

ImportError: Cannot import name X

Don't name your current python script with the name of some other module you import

Solution: rename your working python script

Example:

  1. you are working in medicaltorch.py
  2. in that script, you have: from medicaltorch import datasets as mt_datasets where medicaltorch is supposed to be an installed module

This will fail with the ImportError. Just rename your working python script in 1.

Using jQuery to build table rows from AJAX response(json)

I have created this JQuery function

/**
 * Draw a table from json array
 * @param {array} json_data_array Data array as JSON multi dimension array
 * @param {array} head_array Table Headings as an array (Array items must me correspond to JSON array)
 * @param {array} item_array JSON array's sub element list as an array
 * @param {string} destinaion_element '#id' or '.class': html output will be rendered to this element
 * @returns {string} HTML output will be rendered to 'destinaion_element'
 */

function draw_a_table_from_json(json_data_array, head_array, item_array, destinaion_element) {
    var table = '<table>';
    //TH Loop
    table += '<tr>';
    $.each(head_array, function (head_array_key, head_array_value) {
        table += '<th>' + head_array_value + '</th>';
    });
    table += '</tr>';
    //TR loop
    $.each(json_data_array, function (key, value) {

        table += '<tr>';
        //TD loop
        $.each(item_array, function (item_key, item_value) {
            table += '<td>' + value[item_value] + '</td>';
        });
        table += '</tr>';
    });
    table += '</table>';

    $(destinaion_element).append(table);
}
;

How to create SPF record for multiple IPs?

The open SPF wizard from the previous answer is no longer available, neither the one from Microsoft.

Change "on" color of a Switch

<androidx.appcompat.widget.SwitchCompat
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:thumbTint="@color/white"
                app:trackTint="@drawable/checker_track"/>

And inside checker_track.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/lightish_blue" android:state_checked="true"/>
    <item android:color="@color/hint" android:state_checked="false"/>
</selector>

XPath Query: get attribute href from a tag

For the following HTML document:

<html>
  <body>
    <a href="http://www.example.com">Example</a> 
    <a href="http://www.stackoverflow.com">SO</a> 
  </body>
</html>

The xpath query /html/body//a/@href (or simply //a/@href) will return:

    http://www.example.com
    http://www.stackoverflow.com

To select a specific instance use /html/body//a[N]/@href,

    $ /html/body//a[2]/@href
    http://www.stackoverflow.com

To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:

    $ /html/body//a[contains(@href,'example')]/@href
    http://www.example.com

Mixing the two:

    $ /html/body//a[contains(@href,'com')][2]/@href
    http://www.stackoverflow.com

How to override and extend basic Django admin templates?

for app index add this line to somewhere common py file like url.py

admin.site.index_template = 'admin/custom_index.html'

for app module index : add this line to admin.py

admin.AdminSite.app_index_template = "servers/servers-home.html"

for change list : add this line to admin class:

change_list_template = "servers/servers_changelist.html"

for app module form template : add this line to your admin class

change_form_template = "servers/server_changeform.html"

etc. and find other in same admin's module classes

How to sort in mongoose?

This is how I got sort to work in mongoose 2.3.0 :)

// Find First 10 News Items
News.find({
    deal_id:deal._id // Search Filters
},
['type','date_added'], // Columns to Return
{
    skip:0, // Starting Row
    limit:10, // Ending Row
    sort:{
        date_added: -1 //Sort by Date Added DESC
    }
},
function(err,allNews){
    socket.emit('news-load', allNews); // Do something with the array of 10 objects
})

Convert PEM to PPK file format

I'm rather shocked that this has not been answered since the solution is very simple.

As mentioned in previous posts, you would not want to convert it using C#, but just once. This is easy to do with PuTTYGen.

  1. Download your .pem from AWS
  2. Open PuTTYgen
  3. Click "Load" on the right side about 3/4 down
  4. Set the file type to *.*
  5. Browse to, and Open your .pem file
  6. PuTTY will auto-detect everything it needs, and you just need to click "Save private key" and you can save your ppk key for use with PuTTY

Enjoy!

Pass values of checkBox to controller action in asp.net mvc4

I did had a problem with the most of solutions, since I was trying to use a checkbox with a specific style. I was in need of the values of the checkbox to send them to post from a list, once the values were collected, needed to save it. I did manage to work it around after a while.

Hope it helps someone. Here's the code below:

Controller:

    [HttpGet]
    public ActionResult Index(List<Model> ItemsModelList)
    {

        ItemsModelList = new List<Model>()
        {                
            //example two values
            //checkbox 1
            new Model{ CheckBoxValue = true},
            //checkbox 2
            new Model{ CheckBoxValue = false}

        };

        return View(new ModelLists
        {
            List = ItemsModelList

        });


    }

    [HttpPost]
    public ActionResult Index(ModelLists ModelLists)
    {
        //Use a break point here to watch values
        //Code... (save for example)
        return RedirectToAction("Index", "Home");

    }

Model 1:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace waCheckBoxWithModel.Models
    {
        public class Model
{

    public bool CheckBoxValue { get; set; }

}
    }

Model 2:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace waCheckBoxWithModel.Models
    {
        public class ModelLists
{

    public List<Model> List { get; set; }

}
    }

View (Index):

    @{
ViewBag.Title = "Index";

@model waCheckBoxWithModel.Models.ModelLists
    }
    <style>

.checkBox {
    display: block;
    position: relative;
    margin-bottom: 12px;
    cursor: pointer;
    font-size: 22px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

    /* hide default checkbox*/
    .checkBox input {
        position: absolute;
        opacity: 0;
        cursor: pointer;
    }

/* checkmark */
.checkmark {
    position: absolute;
    top: 0;
    left: 0;
    height: 25px;
    width: 25px;
    background: #fff;
    border-radius: 4px;
    border-width: 1px;
    box-shadow: inset 0px 0px 10px #ccc;
}

/* On mouse-over change backgroundcolor */
.checkBox:hover input ~ .checkmark {
    /*background-color: #ccc;*/
}

/* background effect */
.checkBox input:checked ~ .checkmark {
    background-color: #fff;
}

/* checkmark (hide when not checked) */
.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

/* show checkmark (checked) */
.checkBox input:checked ~ .checkmark:after {
    display: block;
}

/* Style checkmark */
.checkBox .checkmark:after {
    left: 9px;
    top: 7px;
    width: 5px;
    height: 10px;
    border: solid #1F4788;
    border-width: 0 2px 2px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}
   </style>

    @using (Html.BeginForm())
    {

    <div>

@{
    int cnt = Model.List.Count;
    int i = 0;

}

@foreach (var item in Model.List)
{

    {
        if (cnt >= 1)
        { cnt--; }
    }

    @Html.Label("Example" + " " + (i + 1))

    <br />

    <label class="checkBox">
        @Html.CheckBoxFor(m => Model.List[i].CheckBoxValue)
        <span class="checkmark"></span>
    </label>

    { i++;}

    <br />

}

<br />
<input type="submit" value="Go to Post Index" />    

    </div>

    }

Get child node index

ES—Shorter

[...element.parentNode.children].indexOf(element);

The spread Operator is a shortcut for that

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

Javascript objects: get parent

when I load in a json object I usually setup the relationships by iterating through the object arrays like this:

    for (var i = 0; i < some.json.objectarray.length; i++) {
        var p = some.json.objectarray[i];
        for (var j = 0; j < p.somechildarray.length; j++) {
            p.somechildarray[j].parent = p;
        }
    }

then you can access the parent object of some object in the somechildarray by using .parent

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

My problem was that I was trying to create a ASPX web application in a subfolder of a folder that already had a web.config file, and

So I opened up the parent folder in Visual Studio as a Web Site (Open > Web Site) I was able to add a new item ASPX page that had no issue parsing/loading.

TypeError: $.ajax(...) is not a function?

Reference the jquery min version that includes ajax:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

Also possible is to fix this with np.arange() instead of range which works for float numbers:

import numpy as np
for i in np.arange(c/10):

Ruby objects and JSON serialization (without Rails)

Actually, there is a gem called Jsonable, https://github.com/treeder/jsonable. It's pretty sweet.

How to make a checkbox checked with jQuery?

$('#test').attr('checked','checked');

$('#test').removeAttr('checked');

How to make an AlertDialog in Flutter?

If you want beautiful and responsive alert dialog then you can use flutter packages like

rflutter alert ,fancy dialog,rich alert,sweet alert dialogs,easy dialog & easy alert

These alerts are good looking and responsive. Among them rflutter alert is the best. currently I am using rflutter alert for my apps.

write newline into a file

Or you could use something like the following. Pay attention to "\n":

/**
 * Created by mona on 3/26/16.
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
public class FileExample {


    public static void main (String[] args) throws java.io.IOException {

        File newFile = new File("tweet.txt");
        FileWriter fileWriter = new FileWriter(newFile);
        fileWriter.write("Mona Jalal");
        fileWriter.append("\nMona Mona");
        fileWriter.close();
        FileReader fileReader = new FileReader(newFile);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        fileReader.close();
        bufferedReader.close();



    }
}

SQL/mysql - Select distinct/UNIQUE but return all columns?

SELECT *
FROM tblname
GROUP BY duplicate_values
ORDER BY ex.VISITED_ON DESC
LIMIT 0 , 30

in ORDER BY i have just put example here, you can also add ID field in this

Delete files older than 15 days using PowerShell

If you are having problems with the above examples on a Windows 10 box, try replacing .CreationTime with .LastwriteTime. This worked for me.

dir C:\locationOfFiles -ErrorAction SilentlyContinue | Where { ((Get-Date)-$_.LastWriteTime).days -gt 15 } | Remove-Item -Force

Egit rejected non-fast-forward

Applicable for Eclipse Luna + Eclipse Git 3.6.1

I,

  1. cloned git repository
  2. made some changes in source code
  3. staged changes from Git Staging View
  4. finally, commit and Push!

And I faced this issue with EGit and here is how I fixed it..

Yes, someone committed the changes before I commit my changes. So the changes are rejected. After this error, the changes gets actually committed to local repository. I did not want to just Pull the changes because I wanted to maintain linear history as pointed out in - In what cases could `git pull` be harmful?

So, I executed following steps

  1. from Git Repository perspective, right click on the concerned Git
    project
  2. select Fetch from Upstream - it fetches remote updates (refs and objects) but no updates are made locally. for more info refer What is the difference between 'git pull' and 'git fetch'?
  3. select Rebase... - this open a popup, click on Preserve merges during rebase see why
    What exactly does git's "rebase --preserve-merges" do (and why?)
  4. click on Rebase button
  5. if there is/are a conflict(s), go to step 6 else step 11
  6. a Rebase Result popup would appear, just click on OK
  7. file comparator would open up, you need to modify left side file.
  8. once you are done with merging changes correctly, goto Git Staging view
  9. stage the changes. i.e. add to index
  10. on the same view, click on Rebase-> Continue. repeat 7 to 10 until all conflicts are resolved.
  11. from History view, select your commit row and select Push Commit
  12. select Rebase Commits of local....... checkbox and click next. refer why - Git: rebase onto development branch from upstream
  13. click on Finish

Note: if you have multiple local repository commits, you need to squash them in one commit to avoid multiple merges.

How to add an Access-Control-Allow-Origin header

In your file.php of request ajax, can set value header.

<?php header('Access-Control-Allow-Origin: *'); //for all ?>

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

How do you find all subclasses of a given class in Java?

Don't forget that the generated Javadoc for a class will include a list of known subclasses (and for interfaces, known implementing classes).

How to use OpenSSL to encrypt/decrypt files?

Encrypt:

openssl enc -in infile.txt -out encrypted.dat -e -aes256 -k symmetrickey

Decrypt:

openssl enc -in encrypted.dat -out outfile.txt -d -aes256 -k symmetrickey

For details, see the openssl(1) docs.

Why use Gradle instead of Ant or Maven?

It's also much easier to manage native builds. Ant and Maven are effectively Java-only. Some plugins exist for Maven that try to handle some native projects, but they don't do an effective job. Ant tasks can be written that compile native projects, but they are too complex and awkward.

We do Java with JNI and lots of other native bits. Gradle simplified our Ant mess considerably. When we started to introduce dependency management to the native projects it was messy. We got Maven to do it, but the equivalent Gradle code was a tiny fraction of what was needed in Maven, and people could read it and understand it without becoming Maven gurus.

Block Comments in a Shell Script

I like a single line open and close:

if [ ]; then ##
    ...
    ...
fi; ##

The '##' helps me easily find the start and end to the block comment. I can stick a number after the '##' if I've got a bunch of them. To turn off the comment, I just stick a '1' in the '[ ]'. I also avoid some issues I've had with single-quotes in the commented block.

How to set cursor to input box in Javascript?

You have not provided enough code to help You likely submit the form and reload the page OR you have an object on the page like an embedded PDF that steals the focus.

Here is the canonical plain javascript method of validating a form It can be improved with onubtrusive JS which will remove the inline script, but this is the starting point DEMO

function validate(formObj) {
  document.getElementById("errorMsg").innerHTML = "";    
  var quantity = formObj.quantity;
  if (isNaN(quantity)) {
    quantity.value="";
    quantity.focus();
    document.getElementById("errorMsg").innerHTML = "Only numeric value is allowed";
    return false;
  }
  return true; // allow submit
}   

Here is the HTML

<form onsubmit="return validate(this)">
    <input type="text" name="quantity" value="" />
    <input type="submit" />
</form>    
<span id="errorMsg"></span>

Should I set max pool size in database connection string? What happens if I don't?

"currently yes but i think it might cause problems at peak moments" I can confirm, that I had a problem where I got timeouts because of peak requests. After I set the max pool size, the application ran without any problems. IIS 7.5 / ASP.Net

How to send a PUT/DELETE request in jQuery?

Here's an updated ajax call for when you are using JSON with jQuery > 1.9:

$.ajax({
    url: '/v1/object/3.json',
    method: 'DELETE',
    contentType: 'application/json',
    success: function(result) {
        // handle success
    },
    error: function(request,msg,error) {
        // handle failure
    }
});

How to perform keystroke inside powershell?

If I understand correctly, you want PowerShell to send the ENTER keystroke to some interactive application?

$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('title of the application window')
Sleep 1
$wshell.SendKeys('~')

If that interactive application is a PowerShell script, just use whatever is in the title bar of the PowerShell window as the argument to AppActivate (by default, the path to powershell.exe). To avoid ambiguity, you can have your script retitle its own window by using the title 'new window title' command.

A few notes:

  • The tilde (~) represents the ENTER keystroke. You can also use {ENTER}, though they're not identical - that's the keypad's ENTER key. A complete list is available here: http://msdn.microsoft.com/en-us/library/office/aa202943%28v=office.10%29.aspx.
  • The reason for the Sleep 1 statement is to wait 1 second because it takes a moment for the window to activate, and if you invoke SendKeys immediately, it'll send the keys to the PowerShell window, or to nowhere.
  • Be aware that this can be tripped up, if you type anything or click the mouse during the second that it's waiting, preventing to window you activate with AppActivate from being active. You can experiment with reducing the amount of time to find the minimum that's reliably sufficient on your system (Sleep accepts decimals, so you could try .5 for half a second). I find that on my 2.6 GHz Core i7 Win7 laptop, anything less than .8 seconds has a significant failure rate. I use 1 second to be safe.
  • IMPORTANT WARNING: Be extra careful if you're using this method to send a password, because activating a different window between invoking AppActivate and invoking SendKeys will cause the password to be sent to that different window in plain text!

Sometimes wscript.shell's SendKeys method can be a little quirky, so if you run into problems, replace the fourth line above with this:

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait('~');

How to remove whitespace from a string in typescript?

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

How to open in default browser in C#

This opened the default for me:

System.Diagnostics.Process.Start(e.LinkText.ToString());

$(this).val() not working to get text from span using jquery

To retrieve text of an auto generated span value just do this :

var al = $("#id-span-name").text();    
alert(al);

iFrame Height Auto (CSS)

@SweetSpice, use position as absolute in place of relative. It will work

#frame{
overflow: hidden;
width: 860px;
height: 100%;
position: absolute;
}

Count textarea characters

textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);

You are calling textareaLengthCheck and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:

textarea.addEventListener("keypress",textareaLengthCheck,false);

Aside from that:

var length = textarea.length;

textarea is the actual textarea, not the value. Try this instead:

var length = textarea.value.length;

Combined with the previous suggestion, your function should be:

function textareaLengthCheck() {
    var length = this.value.length;
    // rest of code
};

PHP Array to CSV

Instead of writing out values consider using fputcsv().

This may solve your problem immediately.

Unnamed/anonymous namespaces vs. static functions

From experience I'll just note that while it is the C++ way to put formerly-static functions into the anonymous namespace, older compilers can sometimes have problems with this. I currently work with a few compilers for our target platforms, and the more modern Linux compiler is fine with placing functions into the anonymous namespace.

But an older compiler running on Solaris, which we are wed to until an unspecified future release, will sometimes accept it, and other times flag it as an error. The error is not what worries me, it's what it might be doing when it accepts it. So until we go modern across the board, we are still using static (usually class-scoped) functions where we'd prefer the anonymous namespace.

Display animated GIF in iOS

From iOS 11 Photos framework allows to add animated Gifs playback.

Sample app can be dowloaded here

More info about animated Gifs playback (starting from 13:35 min): https://developer.apple.com/videos/play/wwdc2017/505/

enter image description here

how to save canvas as png image?

I used this solution to set the file name:

HTML:

<a href="#" id="downloader" onclick="download()" download="image.png">Download!</a>
<canvas id="canvas"></canvas>

JavaScript:

function download(){
    document.getElementById("downloader").download = "image.png";
    document.getElementById("downloader").href = document.getElementById("canvas").toDataURL("image/png").replace(/^data:image\/[^;]/, 'data:application/octet-stream');
}

How do I call a SQL Server stored procedure from PowerShell?

Use sqlcmd instead of osql if it's a 2005 database

Syntax error on print with Python 3

In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print("Hello World")

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

I just ran into the same problem. The reason was that the virtual memory file "pagefile.sys" was located on the same drive as our data files for our databases (D: drive). It had doubled in size and filled the disk but windows wasn't picking it up, i.e. it looked like we had 80 GB free when we actually didn't.

Restarting SQL server didn't help, perhaps defragment would give the OS time to free up the pagefile, but we just rebooted the server and voila, the pagefile had shrunk and everything worked fine.

What is interesting is that during the 30 min we were investigating, windows didn't calculate the size of the pagefile.sys at all (80gb). After restart windows did find the pagefile and included it's size in the total disk usage (now 40gb - which is still too big).

UPDATE and REPLACE part of a string

replace for persian word

UPDATE dbo.TblNews
SET keyWords = REPLACE(keyWords, '-', N'?')

help: dbo.TblNews -- table name

keyWords -- fild name

_DEBUG vs NDEBUG

The macro NDEBUG controls whether assert() statements are active or not.

In my view, that is separate from any other debugging - so I use something other than NDEBUG to control debugging information in the program. What I use varies, depending on the framework I'm working with; different systems have different enabling macros, and I use whatever is appropriate.

If there is no framework, I'd use a name without a leading underscore; those tend to be reserved to 'the implementation' and I try to avoid problems with name collisions - doubly so when the name is a macro.

Adding Jar files to IntellijIdea classpath

On the Mac version I was getting the error when trying to run JSON-Clojure.json.clj, which is the script to export a database table to JSON. To get it to work I had to download the latest Clojure JAR from http://clojure.org/ and then right-click on PHPStorm app in the Finder and "Show Package Contents". Then go to Contents in there. Then open the lib folder, and see a bunch of .jar files. Copy the clojure-1.8.0.jar file from the unzipped archive I downloaded from clojure.org into the aforementioned lib folder inside the PHPStorm.app/Contents/lib. Restart the app. Now it freaking works.

EDIT: You also have to put the JSR-223 script engine into PHPStorm.app/Contents/lib. It can be built from https://github.com/ato/clojure-jsr223 or downloaded from https://www.dropbox.com/s/jg7s0c41t5ceu7o/clojure-jsr223-1.5.1.jar?dl=0 .

How do I check if an object's type is a particular subclass in C++?

I was thinking along the lines of using typeid()...

Well, yes, it could be done by comparing: typeid().name(). If we take the already described situation, where:

class Base;
class A : public Base {...};
class B : public Base {...};

void foo(Base *p)
{
  if(/* p is A */) /* do X */
  else /* do Y */
}

A possible implementation of foo(Base *p) would be:

#include <typeinfo>

void foo(Base *p)
{
    if(typeid(*p) == typeid(A))
    {
        // the pointer is pointing to the derived class A
    }  
    else if (typeid(*p).name() == typeid(B).name()) 
    {
        // the pointer is pointing to the derived class B
    }
}

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

What does int argc, char *argv[] mean?

Suppose you run your program thus (using sh syntax):

myprog arg1 arg2 'arg 3'

If you declared your main as int main(int argc, char *argv[]), then (in most environments), your main() will be called as if like:

p = { "myprog", "arg1", "arg2", "arg 3", NULL };
exit(main(4, p));

However, if you declared your main as int main(), it will be called something like

exit(main());

and you don't get the arguments passed.

Two additional things to note:

  1. These are the only two standard-mandated signatures for main. If a particular platform accepts extra arguments or a different return type, then that's an extension and should not be relied upon in a portable program.
  2. *argv[] and **argv are exactly equivalent, so you can write int main(int argc, char *argv[]) as int main(int argc, char **argv).

How to submit a form using PhantomJS

Also, CasperJS provides a nice high-level interface for navigation in PhantomJS, including clicking on links and filling out forms.

CasperJS

Updated to add July 28, 2015 article comparing PhantomJS and CasperJS.

(Thanks to commenter Mr. M!)

Submit form using <a> tag

Using Jquery you can do something like this:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#btnSubmit').click(function() {_x000D_
    $('#deleteFrm').submit();_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form action="" id="deleteFrm" method="POST">_x000D_
  <a id="btnSubmit">Submit</a>_x000D_
</form>
_x000D_
_x000D_
_x000D_

What is the problem with shadowing names defined in outer scopes?

It depends how long the function is. The longer the function, the greater the chance that someone modifying it in future will write data thinking that it means the global. In fact, it means the local, but because the function is so long, it's not obvious to them that there exists a local with that name.

For your example function, I think that shadowing the global is not bad at all.

Paste a multi-line Java String in Eclipse

The EclipsePasteAsJavaString plug-in allows you to insert text as a Java string by Ctrl + Shift + V

Example

Paste as usual via Ctrl+V:

some text with tabs and new lines

Paste as Java string via Ctrl+Shift+V

"some text\twith tabs\r\n" + "and new \r\n" + "lines"

How can I list all of the files in a directory with Perl?

If you want to get content of given directory, and only it (i.e. no subdirectories), the best way is to use opendir/readdir/closedir:

opendir my $dir, "/some/path" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;

You can also use:

my @files = glob( $dir . '/*' );

But in my opinion it is not as good - mostly because glob is quite complex thing (can filter results automatically) and using it to get all elements of directory seems as a too simple task.

On the other hand, if you need to get content from all of the directories and subdirectories, there is basically one standard solution:

use File::Find;

my @content;
find( \&wanted, '/some/path');
do_something_with( @content );

exit;

sub wanted {
  push @content, $File::Find::name;
  return;
}

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

You can use the following if you want to specify tricky formats:

df['date_col'] =  pd.to_datetime(df['date_col'], format='%d/%m/%Y')

More details on format here:

Print in new line, java

    String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.

    System.out.println("line 1" + newLine + "line2");

How to get row index number in R?

I'm interpreting your question to be about getting row numbers.

  • You can try as.numeric(rownames(df)) if you haven't set the rownames. Otherwise use a sequence of 1:nrow(df).
  • The which() function converts a TRUE/FALSE row index into row numbers.

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

Python Web Crawlers and "getting" html source code

If you are using Python > 3.x you don't need to install any libraries, this is directly built in the python framework. The old urllib2 package has been renamed to urllib:

from urllib import request

response = request.urlopen("https://www.google.com")
# set the correct charset below
page_source = response.read().decode('utf-8')
print(page_source)

How do I remove background-image in css?

If your div rule is just div {...}, then #a {...} will be sufficient. If it is more complicated, you need a "more specific" selector, as defined by the CSS specification on specificity. (#a being more specific than div is just single aspect in the algorithm.)

Live video streaming using Java?

You can do this today in Java with the Red5 media server from Flash. If you want to also decode and encode video in Java, you can use the Xuggler project.

JavaScript naming conventions

I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.

How could I put a border on my grid control in WPF?

If nesting your grid in a border control

<Border>
    <Grid>
    </Grid>
</Border>

does not do what you want, then you are going to have to make your own control template for the grid (or border) that DOES do what you want.

How to compute the similarity between two text documents?

Identical to @larsman, but with some preprocessing

import nltk, string
from sklearn.feature_extraction.text import TfidfVectorizer

nltk.download('punkt') # if necessary...


stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)

def stem_tokens(tokens):
    return [stemmer.stem(item) for item in tokens]

'''remove punctuation, lowercase, stem'''
def normalize(text):
    return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))

vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')

def cosine_sim(text1, text2):
    tfidf = vectorizer.fit_transform([text1, text2])
    return ((tfidf * tfidf.T).A)[0,1]


print cosine_sim('a little bird', 'a little bird')
print cosine_sim('a little bird', 'a little bird chirps')
print cosine_sim('a little bird', 'a big dog barks')

Detect IE version (prior to v9) in JavaScript

Detect IE in JS using conditional comments

// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
//     ie === undefined
// If you're in IE (>=5) then you can determine which version:
//     ie === 7; // IE7
// Thus, to detect IE:
//     if (ie) {}
// And to detect the version:
//     ie === 6 // IE6
//     ie > 7 // IE8, IE9 ...
//     ie < 9 // Anything less than IE9
// ----------------------------------------------------------

// UPDATE: Now using Live NodeList idea from @jdalton

var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());

How can I convert NSDictionary to NSData and vice versa?

In Swift 2 you can do it in this way:

var dictionary: NSDictionary = ...

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary

In Swift 3:

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)

How to cast ArrayList<> from List<>

import java.util.List;
import java.util.Arrays;
import java.util.*;

public class Merge
{  
  public static void main(String[] args) {
  // This is normal way
  // List<Integer> l1 = new ArrayList<Integer>(); l1.add(2); l1.add(5); l1.add(10); l1.add(22); 
  // List<Integer> l2 = new ArrayList<Integer>(); l2.add(3); l2.add(8); l2.add(15); 

 //Array.asList only have the list interface, but ArrayList is inherited from List Interface with few more property like ArrayList.remove()
 List<Integer> templ1 = Arrays.asList(2,5,10,22); 
 List<Integer> templ2 =  Arrays.asList(3,8,12);
//So creation of ArrayList with the given list is required, then only ArrayList.remove function works. 
 List<Integer> l1 = new ArrayList<Integer>(templ1);
 List<Integer> l2 = new ArrayList<Integer>(templ2);
 List<Integer> l3 = new ArrayList<Integer>();

 Iterator itr1 = l1.iterator();
 while(itr1.hasNext()){
    int x = (Integer) itr1.next();
    Iterator itr2 = l2.iterator();
    while(itr2.hasNext()) {
      int y = (Integer) itr2.next(); 
      if(x < y) {
        l3.add(x);
        break;
      }
      else{
        l3.add(y);
        itr2.remove();
         
      }
    }
 }
 
 Iterator it = l1.iterator(); 
 while (it.hasNext()){
  int k = (Integer) it.next();
  if (l3.contains(k)){
     continue;
  }
  else{
     l3.add(k);
     System.out.println(k);
  }
 }
 
 Iterator itr2 = l2.iterator();
 while (itr2.hasNext()){
  int k = (Integer) itr2.next();
  l3.add(k);
 }
 
 System.out.println(l3);
 }
}

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!

What is the color code for transparency in CSS?

how to make transparent elements with css:

CSS for IE:

filter: alpha(opacity = 52);

CSS for other browsers:

opacity:0.52;

How to construct a set out of list items in python?

You can also use list comprehension to create set.

s = {i for i in range(5)}

Using a global variable with a thread

Well, running example:

WARNING! NEVER DO THIS AT HOME/WORK! Only in classroom ;)

Use semaphores, shared variables, etc. to avoid rush conditions.

from threading import Thread
import time

a = 0  # global variable


def thread1(threadname):
    global a
    for k in range(100):
        print("{} {}".format(threadname, a))
        time.sleep(0.1)
        if k == 5:
            a += 100


def thread2(threadname):
    global a
    for k in range(10):
        a += 1
        time.sleep(0.2)


thread1 = Thread(target=thread1, args=("Thread-1",))
thread2 = Thread(target=thread2, args=("Thread-2",))

thread1.start()
thread2.start()

thread1.join()
thread2.join()

and the output:

Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 2
Thread-1 3
Thread-1 3
Thread-1 104
Thread-1 104
Thread-1 105
Thread-1 105
Thread-1 106
Thread-1 106
Thread-1 107
Thread-1 107
Thread-1 108
Thread-1 108
Thread-1 109
Thread-1 109
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110

If the timing were right, the a += 100 operation would be skipped:

Processor executes at T a+100 and gets 104. But it stops, and jumps to next thread Here, At T+1 executes a+1 with old value of a, a == 4. So it computes 5. Jump back (at T+2), thread 1, and write a=104 in memory. Now back at thread 2, time is T+3 and write a=5 in memory. Voila! The next print instruction will print 5 instead of 104.

VERY nasty bug to be reproduced and caught.

ASP.NET MVC Global Variables

Technically any static variable or Property on a class, anywhere in your project, will be a Global variable e.g.

public static class MyGlobalVariables
{
    public static string MyGlobalString { get; set; }
}

But as @SLaks says, they can 'potentially' be bad practice and dangerous, if not handled correctly. For instance, in that above example, you would have multiple requests (threads) trying to access the same Property, which could be an issue if it was a complex type or a collection, you would have to implement some form of locking.

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

Best way to show a loading/progress indicator?

ProgressDialog is deprecated from Android Oreo. Use ProgressBar instead

ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
// To dismiss the dialog
progress.dismiss();

OR

ProgressDialog.show(this, "Loading", "Wait while loading...");

Read more here.

By the way, Spinner has a different meaning in Android. (It's like the select dropdown in HTML)

JavaScript unit test tools for TDD

You should have a look at env.js. See my blog for an example how to write unit tests with env.js.

javascript set cookie with expire time

document.cookie = "cookie_name=cookie_value; max-age=31536000; path=/";

Will set the value for a year.

How to loop over directories in Linux?

find . -type d -maxdepth 1

Proper way to declare custom exceptions in modern Python?

see how exceptions work by default if one vs more attributes are used (tracebacks omitted):

>>> raise Exception('bad thing happened')
Exception: bad thing happened

>>> raise Exception('bad thing happened', 'code is broken')
Exception: ('bad thing happened', 'code is broken')

so you might want to have a sort of "exception template", working as an exception itself, in a compatible way:

>>> nastyerr = NastyError('bad thing happened')
>>> raise nastyerr
NastyError: bad thing happened

>>> raise nastyerr()
NastyError: bad thing happened

>>> raise nastyerr('code is broken')
NastyError: ('bad thing happened', 'code is broken')

this can be done easily with this subclass

class ExceptionTemplate(Exception):
    def __call__(self, *args):
        return self.__class__(*(self.args + args))
# ...
class NastyError(ExceptionTemplate): pass

and if you don't like that default tuple-like representation, just add __str__ method to the ExceptionTemplate class, like:

    # ...
    def __str__(self):
        return ': '.join(self.args)

and you'll have

>>> raise nastyerr('code is broken')
NastyError: bad thing happened: code is broken

'int' object has no attribute '__getitem__'

Some of the problems:

for i in range[6]:
            for j in range[6]:

should be:

range(6)

Why use Redux over Facebook Flux?

I'm an early adopter and implemented a mid-large single page application using the Facebook Flux library.

As I'm a little late to the conversation I'll just point out that despite my best hopes Facebook seem to consider their Flux implementation to be a proof of concept and it has never received the attention it deserves.

I'd encourage you to play with it, as it exposes more of the inner working of the Flux architecture which is quite educational, but at the same time it does not provide many of the benefits that libraries like Redux provide (which aren't that important for small projects, but become very valuable for bigger ones).

We have decided that moving forward we will be moving to Redux and I suggest you do the same ;)

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

  1. Uninstall all JDKs installed on your computer from the Java Control Panel
  2. Search for C:\ProgramData\Oracle\Java and delete that directory and all files contained within. You can do this from the command line using rmdir /S C:\ProgramData\Oracle\Java
  3. Then search for C:\ProgramData\Oracle and delete the oracle folder. You can do this using rmdir /S C:\ProgramData\Oracle
  4. Now install JDK and set the path.

  5. Run the program.You won't find the same problem anymore.

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

Shorter and dealing with a column (entire, not just a section of a column):

=COUNTA(A:A)

COUNTA

Beware, a cell containing just a space would be included in the count.

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

You may have come to this question with MySQL version 8 installed (like me) and not found a satisfactory answer. You can no longer create users like this in version 8:

GRANT ALL PRIVILEGES ON *.* TO 'steves'@'[hostname].com' IDENTIFIED BY '[OBSCURED]' WITH GRANT OPTION;

The rather confusing error message that you get back is: ERROR 1410 (42000): You are not allowed to create a user with GRANT

In order to create users in version 8 you have to do it in two steps:

CREATE USER 'steves'@'[hostname].com' IDENTIFIED BY '[OBSCURED]';
GRANT ALL PRIVILEGES ON *.* TO 'steves'@'[hostname].com' WITH GRANT OPTION;

Of course, if you prefer, you can also supply a limited number of privileges (instead of GRANT ALL PRIVILEGES), e.g. GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER

How can I change the image displayed in a UIImageView programmatically?

This worked for me

[ImageViewName setImage:[UIImage imageNamed: @"ImageName.png"]];

Make sure that the ImageView is declared properly in the .h file and is linked with the IB element.

How to set up tmux so that it starts up with specified windows opened?

:~$ tmux new-session "tmux source-file ~/session1"  

session1

neww
split-window -v 'ipython'  
split-window -h  
new-window 'mutt'  

create an alias in .bashrc

:~$ echo `alias tmux_s1='tmux new-session "tmux source-file ~/session1"'` >>~/.bashrc  
:~$ . ~/.bashrc  
:~$ tmux_s1  

How do I call an Angular.js filter with multiple arguments?

like this:

var items = $filter('filter')(array, {Column1:false,Column2:'Pending'});

scp from Linux to Windows

Download pscp from Putty download page, then use it from Windows Command Line CMD as follows:

pscp username_linux_machine@ip_of_linux_machine:/home/ubuntu/myfile.ext C:\Users\Name\Downloads

Copying starts once you enter the password for the Linux machine.

How to select an item in a ListView programmatically?

Most likely, the item is being selected, you just can't tell because a different control has the focus. There are a couple of different ways that you can solve this, depending on the design of your application.

  1. The simple solution is to set the focus to the ListView first whenever your form is displayed. The user typically sets focus to controls by clicking on them. However, you can also specify which controls gets the focus programmatically. One way of doing this is by setting the tab index of the control to 0 (the lowest value indicates the control that will have the initial focus). A second possibility is to use the following line of code in your form's Load event, or immediately after you set the Selected property:

    myListView.Select();
    

    The problem with this solution is that the selected item will no longer appear highlighted when the user sets focus to a different control on your form (such as a textbox or a button).

  2. To fix that, you will need to set the HideSelection property of the ListView control to False. That will cause the selected item to remain highlighted, even when the control loses the focus.

    When the control has the focus, the selected item's background will be painted with the system highlight color. When the control does not have the focus, the selected item's background will be painted in the system color used for grayed (or disabled) text.

    You can set this property either at design time, or through code:

    myListView.HideSelection = false;
    

Understanding dispatch_async

Swift version

This is the Swift version of David's Objective-C answer. You use the global queue to run things in the background and the main queue to update the UI.

DispatchQueue.global(qos: .background).async {
    
    // Background Thread
    
    DispatchQueue.main.async {
        // Run UI Updates
    }
}

Firebug like plugin for Safari browser

The Safari built in dev tool is great. I have to admit that Firebug on Firefox is my long time favorite, but I think that the Safari tool do a great job too!

How do I add an "Add to Favorites" button or link on my website?

  if (window.sidebar) { // Mozilla Firefox Bookmark
     window.sidebar.addPanel(document.title,location.href,"");

It adds the bookmark but in the sidebar.

Get PHP class property by string

Here is my attempt. It has some common 'stupidity' checks built in, making sure you don't try to set or get a member which isn't available.

You could move those 'property_exists' checks to __set and __get respectively and call them directly within magic().

<?php

class Foo {
    public $Name;

    public function magic($member, $value = NULL) {
        if ($value != NULL) {
            if (!property_exists($this, $member)) {
                trigger_error('Undefined property via magic(): ' .
                    $member, E_USER_ERROR);
                return NULL;
            }
            $this->$member = $value;
        } else {
            if (!property_exists($this, $member)) {
                trigger_error('Undefined property via magic(): ' .
                    $member, E_USER_ERROR);
                return NULL;
            }
            return $this->$member;
        }
    }
};

$f = new Foo();

$f->magic("Name", "Something");
echo $f->magic("Name") , "\n";

// error
$f->magic("Fame", "Something");
echo $f->magic("Fame") , "\n";

?>

How to deserialize xml to object

The comments above are correct. You're missing the decorators. If you want a generic deserializer you can use this.

public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
    T returnObject = default(T);
    if (string.IsNullOrEmpty(XmlFilename)) return default(T);

    try
    {
        StreamReader xmlStream = new StreamReader(XmlFilename);
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        returnObject = (T)serializer.Deserialize(xmlStream);
    }
    catch (Exception ex)
    {
        ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
    }
    return returnObject;
}

Then you'd call it like this:

MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);

Difference between margin and padding?

The simplest defenition is ; padding is a space given inside the border of the container element and margin is given outside. For a element which is not a container, padding may not make much sense, but margin defenitly will help to arrange it.

How to execute raw queries with Laravel 5.1?

you can run raw query like this way too.

DB::table('setting_colleges')->first();

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

Just for those new to iOS buddies (like me) who decided to have multiple cells and in a different xib file, the solution is not to have identifier but to do this:

let cell = Bundle.main.loadNibNamed("newsDetails", owner: self, options: nil)?.first as! newsDetailsTableViewCell

here newsDetails is xib file name.

Split List into Sublists with LINQ

The question was how to "Split List into Sublists with LINQ", but sometimes you may want those sub-lists to be references to the original list, not copies. This allows you to modify the original list from the sub-lists. In that case, this may work for you.

public static IEnumerable<Memory<T>> RefChunkBy<T>(this T[] array, int size)
{
    if (size < 1 || array is null)
    {
        throw new ArgumentException("chunkSize must be positive");
    }

    var index = 0;
    var counter = 0;

    for (int i = 0; i < array.Length; i++)
    {
        if (counter == size)
        {
            yield return new Memory<T>(array, index, size);
            index = i;
            counter = 0;
        }
        counter++;

        if (i + 1 == array.Length)
        {
            yield return new Memory<T>(array, index, array.Length - index);
        }
    }
}

Usage:

var src = new[] { 1, 2, 3, 4, 5, 6 };

var c3 = RefChunkBy(src, 3);      // {{1, 2, 3}, {4, 5, 6}};
var c4 = RefChunkBy(src, 4);      // {{1, 2, 3, 4}, {5, 6}};

// as extension method
var c3 = src.RefChunkBy(3);      // {{1, 2, 3}, {4, 5, 6}};
var c4 = src.RefChunkBy(4);      // {{1, 2, 3, 4}, {5, 6}};

var sum = c3.Select(c => c.Span.ToArray().Sum());    // {6, 15}
var count = c3.Count();                 // 2
var take2 = c3.Select(c => c.Span.ToArray().Take(2));  // {{1, 2}, {4, 5}}

Feel free to make this code better.

How to determine if .NET Core is installed

The following commands are available with .NET Core SDK 2.1 (v2.1.300):

To list all installed .NET Core SDKs use: dotnet --list-sdks

To list all installed .NET Core runtimes use dotnet --list-runtimes

(tested on Windows as of writing, 03 Jun 2018, and again on 23 Aug 2018)

Update as of 24 Oct 2018: Better option is probably now dotnet --info in a terminal or PowerShell window as already mentioned in other answers.

Accessing value inside nested dictionaries

As always in python, there are of course several ways to do it, but there is one obvious way to do it.

tmpdict["ONE"]["TWO"]["THREE"] is the obvious way to do it.

When that does not fit well with your algorithm, that may be a hint that your structure is not the best for the problem.

If you just want to just save you repetative typing, you can of course alias a subset of the dict:

>>> two_dict = tmpdict['ONE']['TWO'] # now you can just write two_dict for tmpdict['ONE']['TWO']
>>> two_dict["spam"] = 23
>>> tmpdict
{'ONE': {'TWO': {'THREE': 10, 'spam': 23}}}

Documentation for using JavaScript code inside a PDF file

The comprehensive place for Acrobat JavaScript documentation is the Acrobat SDK, which can be downloaded from the Adobe website. In the Documentation section, you will find all the material needed to work with Acrobat JavaScript.

To complete the documentation you may in addition get the specification of the JavaScript Core. My book of choice for that is "JavaScript, the Definitive Guide" by David Flanagan, published by O'Reilly.

How to get row data by clicking a button in a row in an ASP.NET gridview

You can also use button click event like this:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="Button1" runat="server" Text="Button" 
                    OnClick="MyButtonClick" />
    </ItemTemplate>
</asp:TemplateField>
protected void MyButtonClick(object sender, System.EventArgs e)
{
    //Get the button that raised the event
    Button btn = (Button)sender;

    //Get the row that contains this button
    GridViewRow gvr = (GridViewRow)btn.NamingContainer;
} 

OR

You can do like this to get data:

 void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
 {

    // If multiple ButtonField column fields are used, use the
    // CommandName property to determine which button was clicked.
    if(e.CommandName=="Select")
    {
      // Convert the row index stored in the CommandArgument
      // property to an Integer.
      int index = Convert.ToInt32(e.CommandArgument);    

      // Get the last name of the selected author from the appropriate
      // cell in the GridView control.
      GridViewRow selectedRow = CustomersGridView.Rows[index];
    }
}

and Button in gridview should have command like this and handle rowcommand event:

<asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="false"
        onrowcommand="CustomersGridView_RowCommand"
        runat="server">

        <columns>
          <asp:buttonfield buttontype="Button" 
            commandname="Select"
            headertext="Select Customer" 
            text="Select"/>
        </columns>
  </asp:gridview>

Check full example on MSDN

How to stop tracking and ignore changes to a file in Git?

To save some time the rules you add to your .gitignore can be used for removing multiple files/folders i.e.

git rm --cached app/**/*.xml

or

git rm --cached -r app/widgets/yourfolder/

e.t.c.

Unique on a dataframe with only selected columns

Ok, if it doesn't matter which value in the non-duplicated column you select, this should be pretty easy:

dat <- data.frame(id=c(1,1,3),id2=c(1,1,4),somevalue=c("x","y","z"))
> dat[!duplicated(dat[,c('id','id2')]),]
  id id2 somevalue
1  1   1         x
3  3   4         z

Inside the duplicated call, I'm simply passing only those columns from dat that I don't want duplicates of. This code will automatically always select the first of any ambiguous values. (In this case, x.)

Error 1022 - Can't write; duplicate key in table

Change the Foreign key name in MySQL. You can not have the same foreign key names in the database tables.

Check all your tables and all your foreign keys and avoid having two foreign keys with the same exact name.

Is it possible to validate the size and type of input=file in html5

I could do this (demo):

<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
    <form >
        <input type="file" id="f" data-max-size="32154" />
        <input type="submit" />
    </form>
<script>
$(function(){
    $('form').submit(function(){
        var isOk = true;
        $('input[type=file][data-max-size]').each(function(){
            if(typeof this.files[0] !== 'undefined'){
                var maxSize = parseInt($(this).attr('max-size'),10),
                size = this.files[0].size;
                isOk = maxSize > size;
                return isOk;
            }
        });
        return isOk;
    });
});
</script>
</body>
</html>

In Python, what is the difference between ".append()" and "+= []"?

"+" does not mutate the list

.append() mutates the old list

What is a Y-combinator?

The this-operator can simplify your life:

var Y = function(f) {
    return (function(g) {
        return g(g);
    })(function(h) {
        return function() {
            return f.apply(h(h), arguments);
        };
    });
};

Then you avoid the extra function:

var fac = Y(function(n) {
    return n == 0 ? 1 : n * this(n - 1);
});

Finally, you call fac(5).

how to insert date and time in oracle?

You are doing everything right by using a to_date function and specifying the time. The time is there in the database. The trouble is just that when you select a column of DATE datatype from the database, the default format mask doesn't show the time. If you issue a

alter session set nls_date_format = 'dd/MON/yyyy hh24:mi:ss'

or something similar including a time component, you will see that the time successfully made it into the database.

How to undo a git pull?

Even though the above solutions do work,This answer is for you in case you want to reverse the clock instead of undoing a git pull.I mean if you want to get your exact repo the way it was X Mins back then run the command

git reset --hard branchName@{"X Minutes ago"}

Note: before you actually go ahead and run this command please only try this command if you are sure about the time you want to go back to and heres about my situation.

I was currently on a branch develop, I was supposed to checkout to a new branch and pull in another branch lets say Branch A but I accidentally ran git pull origin B before checking out.

so to undo this change I tried this command

git reset --hard develop@{"10 Minutes ago"}

if you are on windows cmd and get error: unknown switch `e

try adding quotes like this

git reset --hard 'develop@{"10 Minutes ago"}'

Jquery post, response in new window

If you dont need a feedback about the requested data and also dont need any interactivity between the opener and the popup, you can post a hidden form into the popup:

Example:

<form method="post" target="popup" id="formID" style="display:none" action="https://example.com/barcode/generate" >
  <input type="hidden" name="packing_slip" value="35592" />
  <input type="hidden" name="reference" value="0018439" />
  <input type="hidden" name="total_boxes" value="1" />
</form>
<script type="text/javascript">
window.open('about:blank','popup','width=300,height=200')
document.getElementById('formID').submit();
</script>

Otherwise you could use jsonp. But this works only, if you have access to the other Server, because you have to modify the response.

Vertical align middle with Bootstrap responsive grid

Add !important rule to display: table of your .v-center class.

.v-center {
    display:table !important;
    border:2px solid gray;
    height:300px;
}

Your display property is being overridden by bootstrap to display: block.

Example

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

The remote certificate is invalid according to the validation procedure

You must check the certificate hash code.

ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain,
    errors) =>
        {
            var hashString = certificate.GetCertHashString();
            if (hashString != null)
            {
                var certHashString = hashString.ToLower();
                return certHashString == "dec2b525ddeemma8ccfaa8df174455d6e38248c5";
            }
            return false;
        };

Retrieve filename from file descriptor in C

You can use readlink on /proc/self/fd/NNN where NNN is the file descriptor. This will give you the name of the file as it was when it was opened — however, if the file was moved or deleted since then, it may no longer be accurate (although Linux can track renames in some cases). To verify, stat the filename given and fstat the fd you have, and make sure st_dev and st_ino are the same.

Of course, not all file descriptors refer to files, and for those you'll see some odd text strings, such as pipe:[1538488]. Since all of the real filenames will be absolute paths, you can determine which these are easily enough. Further, as others have noted, files can have multiple hardlinks pointing to them - this will only report the one it was opened with. If you want to find all names for a given file, you'll just have to traverse the entire filesystem.

CSS: Force float to do a whole new line

You can wrap them in a div and give the div a set width (the width of the widest image + margin maybe?) and then float the divs. Then, set the images to the center of their containing divs. Your margins between images won't be consistent for the differently sized images but it'll lay out much more nicely on the page.

CSS3 Transition - Fade out effect

This is the working code for your question.
Enjoy Coding....

<html>
   <head>

      <style>

         .animated {
            background-color: green;
            background-position: left top;
            padding-top:95px;
            margin-bottom:60px;
            -webkit-animation-duration: 10s;animation-duration: 10s;
            -webkit-animation-fill-mode: both;animation-fill-mode: both;
         }

         @-webkit-keyframes fadeOut {
            0% {opacity: 1;}
            100% {opacity: 0;}
         }

         @keyframes fadeOut {
            0% {opacity: 1;}
            100% {opacity: 0;}
         }

         .fadeOut {
            -webkit-animation-name: fadeOut;
            animation-name: fadeOut;
         }
      </style>

   </head>
   <body>

      <div id="animated-example" class="animated fadeOut"></div>

   </body>
</html>

Iterate over object in Angular

try to use this pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'values',  pure: false })
export class ValuesPipe implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value).map(key => value[key]);
  }
}

<div *ngFor="#value of object | values"> </div>

UL or DIV vertical scrollbar

You need to set a height on the DIV. Otherwise it will keep expanding indefinitely.

How to create jobs in SQL Server Express edition

SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.

There are a few third-party extensions that provide that capability - check out e.g.:

How do you write to a folder on an SD card in Android?

Found the answer here - http://mytechead.wordpress.com/2014/01/30/android-create-a-file-and-write-to-external-storage/

It says,

/**

* Method to check if user has permissions to write on external storage or not

*/

public static boolean canWriteOnExternalStorage() {
   // get the state of your external storage
   String state = Environment.getExternalStorageState();
   if (Environment.MEDIA_MOUNTED.equals(state)) {
    // if storage is mounted return true
      Log.v("sTag", "Yes, can write to external storage.");
      return true;
   }
   return false;
}

and then let’s use this code to actually write to the external storage:

// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/your-dir-name/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, "My-File-Name.txt");
FileOutputStream os = outStream = new FileOutputStream(file);
String data = "This is the content of my file";
os.write(data.getBytes());
os.close();

And this is it. If now you visit your /sdcard/your-dir-name/ folder you will see a file named - My-File-Name.txt with the content as specified in the code.

PS:- You need the following permission -

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Calling a Sub and returning a value

Sub don't return values and functions don't have side effects.

Sometimes you want both side effect and return value.

This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:

Sub getValue(retValue as Long)
    ...
    retValue = 42 
End SUb 

Sub Main()
    Dim retValue As Long
    getValue retValue 
    ... 
End SUb

How to list all functions in a Python module?

For global functions dir() is the command to use (as mentioned in most of these answers), however this lists both public functions and non-public functions together.

For example running:

>>> import re
>>> dir(re)

Returns functions/classes like:

'__all__', '_MAXCACHE', '_alphanum_bytes', '_alphanum_str', '_pattern_type', '_pickle', '_subx'

Some of which are not generally meant for general programming use (but by the module itself, except in the case of DunderAliases like __doc__, __file__ ect). For this reason it may not be useful to list them with the public ones (this is how Python knows what to get when using from module import *).

__all__ could be used to solve this problem, it returns a list of all the public functions and classes in a module (those that do not start with underscores - _). See Can someone explain __all__ in Python? for the use of __all__.

Here is an example:

>>> import re
>>> re.__all__
['match', 'fullmatch', 'search', 'sub', 'subn', 'split', 'findall', 'finditer', 'compile', 'purge', 'template', 'escape', 'error', 'A', 'I', 'L', 'M', 'S', 'X', 'U', 'ASCII', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'UNICODE']
>>>

All the functions and classes with underscores have been removed, leaving only those that are defined as public and can therefore be used via import *.

Note that __all__ is not always defined. If it is not included then an AttributeError is raised.

A case of this is with the ast module:

>>> import ast
>>> ast.__all__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ast' has no attribute '__all__'
>>>

Most efficient way to check if a file is empty in Java on Windows

Another way to do this is (using Apache Commons FileUtils) -

private void printEmptyFileName(final File file) throws IOException {
    if (FileUtils.readFileToString(file).trim().isEmpty()) {
        System.out.println("File is empty: " + file.getName());
    }        
}

Authentication issue when debugging in VS2013 - iis express

F4 doesn't always bring me to this panel. Besides, it is often said that a picture is worth a thousand words.

enter image description here

Selecting default item from Combobox C#

Remember that collections in C# are zero-based (in other words, the first item in a collection is at position zero). If you have two items in your list, and you want to select the last item, use SelectedIndex = 1.

Resolve host name to an ip address

Try tracert to resolve the hostname. IE you have Ip address 8.8.8.8 so you would use; tracert 8.8.8.8

How does HttpContext.Current.User.Identity.Name know which usernames exist?

How does [HttpContext.Current.User] know which usernames exist or do not exist?

Let's look at an example of one way this works. Suppose you are using Forms Authentication and the "OnAuthenticate" event fires. This event occurs "when the application authenticates the current request" (Reference Source).

Up until this point, the application has no idea who you are.

Since you are using Forms Authentication, it first checks by parsing the authentication cookie (usually .ASPAUTH) via a call to ExtractTicketFromCookie. This calls FormsAuthentication.Decrypt (This method is public; you can call this yourself!). Next, it calls Context.SetPrincipalNoDemand, turning the cookie into a user and stuffing it into Context.User (Reference Source).

CSS display:table-row does not expand when width is set to 100%

give on .view-type class float:left; or delete the float:right; of .view-name

edit: Wrap your div <div class="view-row"> with another div for example <div class="table">

and set the following css :

.table {
    display:table;
    width:100%;}

You have to use the table structure for correct results.

How to check if element in groovy array/hash/collection/list?

You can also use matches with regular expression like this:

boolean bool = List.matches("(?i).*SOME STRING HERE.*")

Add a duration to a moment (moment.js)

I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.

So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:

var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format

var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes 

var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format

It fulfills my requirement. May be it can help you.

Find Number of CPUs and Cores per CPU using Command Prompt

Based upon your comments - your path statement has been changed/is incorrect or the path variable is being incorrectly used for another purpose.

Mock a constructor with parameter

Starting with version 3.5.0 of Mockito and using the InlineMockMaker, you can now mock object constructions:

 try (MockedConstruction mocked = mockConstruction(A.class)) {
   A a = new A();
   when(a.check()).thenReturn("bar");
 }

Inside the try-with-resources construct all object constructions are returning a mock.

Changing ImageView source

Or try this one. For me it's working fine:

imageView.setImageDrawable(ContextCompat.getDrawable(this, image));

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

Eclipse error "Could not find or load main class"

I have checked all possible solutions including re-installation of JDK, eclipse as it worked for many people but unfortunately it didn't work for me. Also updated main class in pom.xml but it didn't help. It took my sleep away. I was trying different options and suddenly the magic happened when I checked this checkbox. It might be helpful for many people so thought of sharing enter image description here

Detecting negative numbers

if ($profitloss < 0)
{
   echo "The profitloss is negative";
}

Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.

In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:

$turnover = 10000;
$overheads = 12500;

$difference = abs($turnover-$overheads);

echo "The Difference is ".$difference;

This would produce The Difference is 2500.

Any way to Invoke a private method?

you can do this using ReflectionTestUtils of Spring (org.springframework.test.util.ReflectionTestUtils)

ReflectionTestUtils.invokeMethod(instantiatedObject,"methodName",argument);

Example : if you have a class with a private method square(int x)

Calculator calculator = new Calculator();
ReflectionTestUtils.invokeMethod(calculator,"square",10);

Comparing arrays in C#

I know this is an old topic, but I think it is still relevant, and would like to share an implementation of an array comparison method which I feel strikes the right balance between performance and elegance.

static bool CollectionEquals<T>(ICollection<T> a, ICollection<T> b, IEqualityComparer<T> comparer = null)
{
    return ReferenceEquals(a, b) || a != null && b != null && a.Count == b.Count && a.SequenceEqual(b, comparer);
}

The idea here is to check for all of the early out conditions first, then fall back on SequenceEqual. It also avoids doing extra branching and instead relies on boolean short-circuit to avoid unecessary execution. I also feel it looks clean and is easy to understand.

Also, by using ICollection for the parameters, it will work with more than just arrays.

Using "&times" word in html changes to ×

I suspect you did not know that there are different & escapes in HTML. The W3C you can see the codes. &times means × in HTML code. Use &amp;times instead.

How do you get the current text contents of a QComboBox?

If you want the text value of a QString object you can use the __str__ property, like this:

>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'

Hope that helps.

No Network Security Config specified, using platform default - Android Log

Check the URL it should be using https rather than http protocol.
In my case changing http to https in the URL solved it.

Favorite Visual Studio keyboard shortcuts

Ctrl + .

To include a missing library.

Show whitespace characters in Visual Studio Code

The option to make whitespace visible now appears as an option on the View menu, as "Toggle Render Whitespace" in version 1.15.1 of Visual Studio Code.

How to override the path of PHP to use the MAMP path?

This is not an ideal solution as you have to manage two ini files however, I managed to work around this on windows by copying the php ini file in mamp from the conf folder to your active php version in the bin folder.

[MAMP INSTALL]\conf\[ACTIVE PHP VERSION]\php.ini

copy to

[MAMP INSTALL]\bin\php\[ACTIVE PHP VERSION]

How to initialize a JavaScript Date to a particular time zone

I know its 3 years too late, but maybe it can help someone else because I haven't found anything like that except for the moment-timezone library, which is not exactly the same as what he's asking for here.

I've done something similar for german timezone, this is a little complex because of daylight saving time and leap years where you have 366 days.

it might need a little work with the "isDaylightSavingTimeInGermany" function while different timezones change on different times the daylight saving time.

anyway, check out this page: https://github.com/zerkotin/german-timezone-converter/wiki

the main methods are: convertLocalDateToGermanTimezone convertGermanDateToLocalTimezone

I've put an effort into documenting it, so it won't be so confusing.

How do I format XML in Notepad++?

Try TextFX ? TextFX Html Tidy ? Tidy: reindent XML

If you can't try with Eclipse, do right button, source, and correct indent.

AngularJS accessing DOM elements inside directive template

This answer comes a little bit late, but I just was in a similar need.

Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.

For example, use the directive like this:

<my-directive class2add="special-class" />

And get the following html:

<div>
    <ul>
       <li class="special-class">Item 1</li>
       <li class="special-class">Item 2</li>
    </ul>
</div>

The solution found here applied with templateUrl, would be:

app.directive("myDirective", function() {
    return {
        template: function(element, attrs){
            return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
        },
        link: function(scope, element, attrs) {
            var list = element.find("ul");
        }
    }
});

Just tried it successfully with AngularJS 1.4.9.

Hope it helps.

Upgrade python without breaking yum

I have written a quick guide on how to install the latest versions of Python 2 and Python 3 on CentOS 6 and CentOS 7. It currently covers Python 2.7.13 and Python 3.6.0:

# Start by making sure your system is up-to-date:
yum update
# Compilers and related tools:
yum groupinstall -y "development tools"
# Libraries needed during compilation to enable all features of Python:
yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel expat-devel
# If you are on a clean "minimal" install of CentOS you also need the wget tool:
yum install -y wget

The next steps depend on the version of Python you're installing.

For Python 2.7.14:

wget http://python.org/ftp/python/2.7.14/Python-2.7.14.tar.xz
tar xf Python-2.7.14.tar.xz
cd Python-2.7.14
./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall

# Strip the Python 2.7 binary:
strip /usr/local/lib/libpython2.7.so.1.0

For Python 3.6.3:

wget http://python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
tar xf Python-3.6.3.tar.xz
cd Python-3.6.3
./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall

# Strip the Python 3.6 binary:
strip /usr/local/lib/libpython3.6m.so.1.0

To install Pip:

# First get the script:
wget https://bootstrap.pypa.io/get-pip.py

# Then execute it using Python 2.7 and/or Python 3.6:
python2.7 get-pip.py
python3.6 get-pip.py

# With pip installed you can now do things like this:
pip2.7 install [packagename]
pip2.7 install --upgrade [packagename]
pip2.7 uninstall [packagename]

You are not supposed to change the system version of Python because it will break the system (as you found out). Installing other versions works fine as long as you leave the original system version alone. This can be accomplished by using a custom prefix (for example /usr/local) when running configure, and using make altinstall (instead of the normal make install) when installing your build of Python.

Having multiple versions of Python available is usually not a big problem as long as you remember to type the full name including the version number (for example "python2.7" or "pip2.7"). If you do all your Python work from a virtualenv the versioning is handled for you, so make sure you install and use virtualenv!

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

HTML Form: Select-Option vs Datalist-Option

To specifically answer a part of your question "Is there any situation in which it would be better to use one or the other?", consider a form with repeating sections. If the repeating section contains many select tags, then the options must be rendered for each select, for every row.

In such a case, I would consider using datalist with input, because the same datalist can be used for any number of inputs. This could potentially save a large amount of rendering time on the server, and would scale much better to any number of rows.

equivalent of vbCrLf in c#

You are looking for System.Environment.NewLine.

On Windows, this is equivalent to \r\n though it could be different under another .NET implementation, such as Mono on Linux, for example.

How do I select child elements of any depth using XPath?

If you are using the XmlDocument and XmlNode.

Say:

XmlNode f = root.SelectSingleNode("//form[@id='myform']");

Use:

XmlNode s = f.SelectSingleNode(".//input[@type='submit']");

It depends on the tool that you use. But .// will select any child, any depth from a reference node.

How can I debug a .BAT script?

I don't know of anyway to step through the execution of a .bat file but you can use echo and pause to help with debugging.

ECHO
Will echo a message in the batch file. Such as ECHO Hello World will print Hello World on the screen when executed. However, without @ECHO OFF at the beginning of the batch file you'll also get "ECHO Hello World" and "Hello World." Finally, if you'd just like to create a blank line, type ECHO. adding the period at the end creates an empty line.

PAUSE
Prompt the user to press any key to continue.

Source: Batch File Help

@workmad3: answer has more good tips for working with the echo command.

Another helpful resource... DDB: DOS Batch File Tips

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

The code that others are giving you only replace one occurrence, while using regular expressions replaces them all (like @sorgit said). To replace all the "want" with "not want", us this code:

var text = "this is some sample text that i want to replace";
var new_text = text.replace(/want/g, "dont want");
document.write(new_text);

The variable "new_text" will result in being "this is some sample text that i dont want to replace".

To get a quick guide to regular expressions, go here:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
To learn more about str.replace(), go here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
Good luck!

How to select following sibling/xml tag using xpath

Try the following-sibling axis (following-sibling::td).

Google Colab: how to read data from my google drive?

Good news, PyDrive has first class support on CoLab! PyDrive is a wrapper for the Google Drive python client. Here is an example on how you would download ALL files from a folder, similar to using glob + *:

!pip install -U -q PyDrive
import os
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

# 1. Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

# choose a local (colab) directory to store the data.
local_download_path = os.path.expanduser('~/data')
try:
  os.makedirs(local_download_path)
except: pass

# 2. Auto-iterate using the query syntax
#    https://developers.google.com/drive/v2/web/search-parameters
file_list = drive.ListFile(
    {'q': "'1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk' in parents"}).GetList()

for f in file_list:
  # 3. Create & download by id.
  print('title: %s, id: %s' % (f['title'], f['id']))
  fname = os.path.join(local_download_path, f['title'])
  print('downloading to {}'.format(fname))
  f_ = drive.CreateFile({'id': f['id']})
  f_.GetContentFile(fname)


with open(fname, 'r') as f:
  print(f.read())

Notice that the arguments to drive.ListFile is a dictionary that coincides with the parameters used by Google Drive HTTP API (you can customize the q parameter to be tuned to your use-case).

Know that in all cases, files/folders are encoded by id's (peep the 1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk) on Google Drive. This requires that you search Google Drive for the specific id corresponding to the folder you want to root your search in.

For example, navigate to the folder "/projects/my_project/my_data" that is located in your Google Drive.

Google Drive

See that it contains some files, in which we want to download to CoLab. To get the id of the folder in order to use it by PyDrive, look at the url and extract the id parameter. In this case, the url corresponding to the folder was:

https://drive.google.com/drive/folders/1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk

Where the id is the last piece of the url: 1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk.

How to write lists inside a markdown table?

Not that I know of, because all markdown references I am aware of, like this one, mention:

Cell content must be on one line only

You can try it with that Markdown Tables Generator (whose example looks like the one you mention in your question, so you may be aware of it already).

Pandoc

If you are using Pandoc’s markdown (which extends John Gruber’s markdown syntax on which the GitHub Flavored Markdown is based) you can use either grid_tables:

+---------------+---------------+--------------------+
| Fruit         | Price         | Advantages         |
+===============+===============+====================+
| Bananas       | $1.34         | - built-in wrapper |
|               |               | - bright color     |
+---------------+---------------+--------------------+
| Oranges       | $2.10         | - cures scurvy     |
|               |               | - tasty            |
+---------------+---------------+--------------------+

or multiline_tables.

-------------------------------------------------------------
 Centered   Default           Right Left
  Header    Aligned         Aligned Aligned
----------- ------- --------------- -------------------------
   First    row                12.0 Example of a row that
                                    spans multiple lines.

  Second    row                 5.0 Here's another one. Note
                                    the blank line between
                                    rows.
-------------------------------------------------------------